Geographic Information Systems Asked on May 2, 2021
I’d like to click on a button in a sidebar outside a Leaflet map and remove a marker associated with that button. But when I bulk add data through L.geoJSON
, the function appears to not create individual variables for markers, making it impossible to simply use .remove(map)
on that variable / marker.
The geoJSON looks like this:
var places = {"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {"WIKIPEDIA": "Beni Department"}, "geometry": {"type": "Point", "coordinates": [-65.683972, -15.43334]}}, {"id": "1", "type": "Feature", "properties": {"WIKIPEDIA": "Bluefish Caves"}, "geometry": {"type": "Point", "coordinates": [-140.518611, 64.135278]}}]}
I’ve tried dynamically associating a variable with each marker by doing this:
geojson = L.geoJSON(places, {
pointToLayer: function (feature, latlng) {
var "_" + String(feature.id) + "_" = L.circleMarker(latlng, geojsonMarkerOptions);
return L.circleMarker(latlng, geojsonMarkerOptions);
}
}).addTo(map);
But that gives me a SyntaxError: missing variable name
.
All layers in leaflet have a unique "leaflet id" which is accessible via L.stamp(layer)
.
You can create an array/object that connects feature.id
and the unique L.stamp, and use it to interact with the markers from the sidebar, without using window
variables.
With such an object, you can remove/interact with specific layers, based on their unique leaflet id via the geojson featurefroup - use the geojson featuregroup to get the layer by it's stamp.
Example:
let mapIdObj = {};
let geojson = L.geoJSON(places, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, geojsonMarkerOptions);
},
onEachFeature: function (feature, layer) {
mapIdObj[feature.id] = L.stamp(layer);
}
}).addTo(map);
//Remove a specific layer based on external feature.id (as id)
map.removeLayer(geojson.getLayer(mapIdObj[id]))
Correct answer by NettaB on May 2, 2021
I'd like to know if there's a better way, but this works:
geojson = L.geoJSON(places, {
pointToLayer: function (feature, latlng) {
window["_" + String(feature.id) + "_"] = L.circleMarker(latlng, geojsonMarkerOptions);
return window["_" + String(feature.id) + "_"]
}
}).addTo(map);
This allow me to run window["_" + String(feature.id) + "_"].remove(map);
Code based on this answer.
Answered by zadrozny on May 2, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP