geoJSON onEachFeature Mouse Event - leaflet

I have a problem where i try to use the onEachFeature Methode for a geoJSON Layer. I try to assign a click listener to every Feature.
The problem is that i always get that error when i click at a feature:
Uncaught TypeError: Cannot read property 'detectChanges' of undefined
I can think of that this is because the Layer is assigned before the constructor runs but to do that in the ngOnInit function wont worked either. Would be cool if ther is a good way to do that :)
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
onEachFeature(feature , layer) {
layer.on('click', <LeafletMouseEvent> (e) => {
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}
layer: Layer[] = [];
fitBounds: LatLngBounds;
onEachFeature(feature , layer : geoJSON) {
layer.on('click', <LeafletMouseEvent> (e) => {
console.log("tets"+e.target.getBounds().toBBoxString());
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}
constructor(private changeDetector: ChangeDetectorRef){}
ngOnInit() {
let geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
this.layer.push(geoLayer);
}

You need to make sure that the right this is accessible in your callback. You do this using function.bind() in Javascript. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {
// Need to bind the proper this context
onEachFeature : this.onEachFeature.bind(this)
});
onEachFeature(feature , layer) {
// 'this' will now refer to your component's context
let that = this;
layer.on('click', <LeafletMouseEvent> (e) => {
that.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
// Aliased 'that' to refer to 'this' so it is in scope
that.changeDetector.detectChanges();
});
}
The let that = this trick is to make sure you don't have the same problem on the click event handler. But, you could also make that handler be a function in your class and use bind to set this.

Related

Mapbox GL JS: Style is not done loading

I have a map wher we can classically switch from one style to another, streets to satellite for example.
I want to be informed that the style is loaded to then add a layer.
According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.
That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.
My code is:
mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [5,45.5],
zoom: 7
});
map.on('load', function () {
loadRegionMask();
});
map.on('styledataloading', function (styledata) {
if (map.isStyleLoaded()) {
loadRegionMask();
}
});
$('#typeMap').on('click', function switchLayer(layer) {
var layerId = layer.target.control.id;
switch (layerId) {
case 'streets':
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
break;
case 'satellite':
map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
break;
}
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'regions.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadRegionMask() {
loadJSON(function(response) {
var geoPoints_JSON = JSON.parse(response);
map.addSource("region-boundaries", {
'type': 'geojson',
'data': geoPoints_JSON,
});
map.addLayer({
'id': 'region-fill',
'type': 'fill',
'source': "region-boundaries",
'layout': {},
'paint': {
'fill-color': '#C4633F',
'fill-opacity': 0.5
},
"filter": ["==", "$type", "Polygon"]
});
});
}
And the error is:
Uncaught Error: Style is not done loading
at t._checkLoaded (mapbox-gl.js:308)
at t.addSource (mapbox-gl.js:308)
at e.addSource (mapbox-gl.js:390)
at map.js:92 (map.addSource("region-boundaries",...)
at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?
1. Listen styledata event to solve your problem
You may need to listen styledata event in your project, since this is the only standard event mentioned in mapbox-gl-js documents, see https://docs.mapbox.com/mapbox-gl-js/api/#map.event:styledata.
You can use it in this way:
map.on('styledata', function() {
addLayer();
});
2. Reasons why you shouldn't use other methods mentioned above
setTimeout may work but is not a recommend way to solve the problem, and you would got unexpected result if your render work is heavy;
style.load is a private event in mapbox, as discussed in issue https://github.com/mapbox/mapbox-gl-js/issues/7579, so we shouldn't listen to it apparently;
.isStyleLoaded() works but can't be called all the time until style is full loaded, you need a listener rather than a judgement method;
Ok, this mapbox issue sucks, but I have a solution
myMap.on('styledata', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
I mix both solutions.
I was facing a similar issue and ended up with this solution:
I created a small function that would check if the style was done loading:
// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
if (map.isStyleLoaded()) {
return true; // When it is safe to manipulate layers
} else {
return false; // When it is not safe to manipulate layers
}
}
Then whenever I swap or otherwise modify layers in the app I use the function like this:
function swapLayer() {
var check = checkIfMapboxStyleIsLoaded();
if (!check) {
// It's not safe to manipulate layers yet, so wait 200ms and then check again
setTimeout(function() {
swapLayer();
}, 200);
return;
}
// Whew, now it's safe to manipulate layers!
the rest of the swapLayer logic goes here...
}
Use the style.load event. It will trigger once each time a new style loads.
map.on('style.load', function() {
addLayer();
});
My working example:
when I change style
map.setStyle()
I get error Uncaught Error: Style is not done loading
This solved my problem
Do not use map.on("load", loadTiles);
instead use
map.on('styledata', function() {
addLayer();
});
when you change style, map.setStyle(), you must wait for setStyle() finished, then to add other layers.
so far map.setStyle('xxx', callback) Does not allowed. To wait until callback, work around is use map.on("styledata"
map.on("load" not work, if you change map.setStyle(). you will get error: Uncaught Error: Style is not done loading
The current style event structure is broken (at least as of Mapbox GL v1.3.0). If you check map.isStyleLoaded() in the styledata event handler, it always resolves to false:
map.on('styledata', function (e) {
if (map.isStyleLoaded()){
// This never happens...
}
}
My solution is to create a new event called "style_finally_loaded" that gets fired only once, and only when the style has actually loaded:
var checking_style_status = false;
map.on('styledata', function (e) {
if (checking_style_status){
// If already checking style status, bail out
// (important because styledata event may fire multiple times)
return;
} else {
checking_style_status = true;
check_style_status();
}
});
function check_style_status() {
if (map.isStyleLoaded()) {
checking_style_status = false;
map._container.trigger('map_style_finally_loaded');
} else {
// If not yet loaded, repeat check after delay:
setTimeout(function() {check_style_status();}, 200);
return;
}
}
I had the same problem, when adding real estate markers to the map. For the first time addding the markers I wait till the map turns idle. After it was added once I save this in realEstateWasInitialLoaded and just add it afterwards without any waiting. But make sure to reset realEstateWasInitialLoaded to false when changing the base map or something similar.
checkIfRealEstateLayerCanBeAddedAndAdd() {
/* The map must exist and real estates must be ready */
if (this.map && this.realEstates) {
this.map.once('idle', () => {
if (!this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
this.realEstateWasInitialLoaded = true
}
})
if(this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
}
}
},
I ended up with :
map.once("idle", ()=>{ ... some function here});
In case you have a bunch of stuff you want to do , i would do something like this =>
add them to an array which looks like [{func: function, param: params}], then you have another function which does this:
executeActions(actions) {
actions.forEach((action) => {
action.func(action.params);
});
And at the end you have
this.map.once("idle", () => {
this.executeActions(actionsArray);
});
I have created simple solution. Give 1 second for mapbox to load the style after you set the style and you can draw the layer
map.setStyle(styleUrl);
setTimeout(function(){
reDrawMapSourceAndLayer(); /// your function layer
}, 1000);
when you use map.on('styledataloading') it will trigger couple of time when you changes the style
map.on('styledataloading', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});

Method clearLayers not clearing any markers

I am attempting to add a custom option to the Leaflet plugin MovingMarker so that, if truthy, each marker is removed at the end of the respective animation. This plugin extends the L.Marker class and employs the window.requestAnimationFrame method to animate the markers.
With this in mind, I've added a destroyedState: 4 line in the statics properties and a remove: false line in the options properties. I've also added the following code blocks:
Getter
isDestroyed: function() {
return this._state === L.Marker.MovingMarker.destroyedState;
}
Setter
destroy: function() {
if (this.isDestroyed()) {
return;
}
this._state = L.Marker.MovingMarker.destroyedState;
this._removeMarker();
},
onEnd: function(map) {
L.Marker.prototype.onEnd.call(this, map);
if (this.options.remove && (this.isDestroyed())) {
this.destroy();
return;
}
this._removeMarker();
},
_removeMarker: function() {
this._state = L.Marker.MovingMarker.destroyedState;
if (this._animRequested) {
L.Util.cancelAnimFrame(this._animId);
this._animRequested = false;
}
this.L.Marker.MovingMarker.clearLayers(this, map);
this.L.Marker.MovingMarker = null;
},
Unfortunately, for some reason the method clearLayers isn't doing the intended job when option remove is set to true. I've tried the method removeLayer at no avail either. I wonder what am I doing wrong? Here's a working example with the remove option set to true on line 232.

Update Leaflet GeoJson layer and maintain selected feature popup

I have a leaflet map which I am refreshing with new data from the server. You can click on the map feature and a popup will show for the point. Every time the refresh happens, I remove the layer using map.removeLayer, add the new data using L.geoJson, but the popup goes away. I want the popup to stay active with the new data. I know this probably won't work the way I'm doing it by removing the layer. Is there another way to do this that will refresh the layer data and maintain the selected feature popup?
This is the refresh function that I call after I get the new data from the server.
function refreshMapLocations() {
map.removeLayer(locationLayer);
locationLayer = L.geoJson(locations, {
onEachFeature: onEachFeature
}).addTo(map);
}
This creates the popup for each feature
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.UserName) {
layer.bindPopup(feature.properties.UserName);
}
}
This worked, I keep track of an id that I set in the popup content. After the layer is added I store the Popup that has the clickedId and do popupOpen on that.
var popupToOpen;
var clickedId;
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.UserName) {
if (feature.properties.MarkerId == clickedId) {
layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
} else {
layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
}
}
}
function refreshMapLocations() {
map.removeLayer(locationLayer);
locationLayer = L.geoJson(locations, {
onEachFeature: onEachFeature
}).addTo(map);
if (popupToOpen != null) {
popupToOpen.openPopup();
}
}
function initMap() {
...
map.on('popupopen', function (e) {
...
//clickedId = id from event popup
}
}

Detecting right click position on angular leaflet map

I have a mobile page showing a map using angular-leaflet-directive 0.7.11, and have declared my required events like so:
$scope.map = {
events: [
'mousedown',
'contextmenu'
],
...
}
$scope.$on('leafletDirectiveMap.mousedown', function (event) {
debugger;
});
Where the debugger statement is, the event variable contains no information about where the map was clicked. The same event format was provided by the directive when the contextmenu event is triggered.
In fact, if I inspect the entire event variable, it is just an Object, not an Event:
Are the docs wrong? Is the example missing something? How can I obtain the X/Y or Lat/Lng for the particular position that I have right-clicked (tap-hold)?
You need to use the 'leafletEvent'. Try this:
myApp.controller('YourController', ['$scope', 'leafletEvent', function($scope) {
$scope.$on('leafletDirectiveMap.mousedown', function (event, leafletEvent) {
leafletData.getMap().then(function(map) {
map.on('click', function(e) {
console.log('e');
console.log(e);
console.log('e.latlng:');
console.log(e.latlng); // L.LatLng {lat: 19.642587534013046, lng: -4.5703125}
});
});
});
}]);

Codemirror remote autcompletion

Codemirror has a nice example for autocompletion : link.
The idea is to have server side autocompletion (e.g. Ajax service that autocompletes Java). Does somebody has an example of a remote autocompletion with codemirror ?
I've been able to get async completions working with CodeMirror 5.3's show-hint.js by using the following (es6 flavoured, so for es3, replace let with var and the => with function)
While there's no actual ajax, it's hopefully obvious how to hook that in, just invoke callback in your ajax calls completion handler.
CodeMirror.registerHelper('hint', 'ajax', (mirror, callback) => {
let words = ['foo', 'bar', 'baz'];
let cur = mirror.getCursor();
let range = mirror.findWordAt(cur);
let fragment = mirror.getRange(range.anchor, range.head);
callback({
list: words.filter(w => w.indexOf(fragment) === 0),
from: range.anchor,
to: range.head
});
});
CodeMirror.hint.ajax.async = true;
CodeMirror.commands.autocomplete = function(mirror) {
mirror.showHint({ hint: CodeMirror.hint.ajax });
};
Key is to set the async property as the docs tells you to:
It is possible to set the async property on a hinting function to
true, in which case it will be called with arguments (cm, callback,
?options), and the completion interface will only be popped up when
the hinting function calls the callback
// javascript code
var editor;
function createEditor (data) {
editor = CodeMirror.fromTextArea(myTextarea, {
mode: "text/x-sql",
extraKeys: {"Ctrl-Q": "autocomplete"},
hint: CodeMirror.hint.sql,
hintOptions: {
tables: data ? data : {}
}
})
}
(function createEditorWithRemoteData () {
$.ajax({
type:'POST',
dataType:'json',
url:'data.json',
success:createEditor,
error:function () {}
})
})();
// data.json
{
"table1": [ "col_A", "col_B", "col_C" ],
"table2": [ "other_columns1", "other_columns2" ]
}