Context:
I've made a map, and populated it with around 300 random markers. I can 'select' the markers by clicking on a link in the popup and activate a selection to display data from. I also have the Leaflet.draw plugin to draw shapes like circles, rectangles and custom shapes, and I would like to use it to 'select' a couple of markers.
The issue
How can I grab the leaflet marker object of the markers that fall inside a drawn leaflet.draw shape so I can edit them? I cannot seem to make a selection, It either selects none of the markers, or all of them.
Code snippet, stripped from unnecessary code:
const drawControl = new L.Control.Draw({
draw: {
marker : false,
polygon : true,
polyline : false,
rectangle: true,
circle : {
metric: 'metric'
}
},
edit: false
});
const map = L.map('map', {
layers: [streets, light]
}).setView([CONFIG.MAP.LATITUDE, CONFIG.MAP.LONGITUDE], CONFIG.MAP.ZOOMLEVEL)
map.addControl(drawControl);
map.on(L.Draw.Event.DRAWSTOP, e => {
const hello = e.target;
console.log(hello);
e.target.eachLayer(layer => {
if (layer.options.icon) {
console.log(layer);
}
});
});
Thanks @iH8 for the cool example. I went further to avoid some repetition with
and extended the wrappers with additionnal methods using arrays of markers instead:
First I noticed that a
LayerGroup
has an object with key-values containing all the markers. I simply use that object to create an array of markers :I then re-use the wrappers with modified
contains()
methods :and finally on the draw event, I check whether my markers are contained within or not :
Most of what you want can quite easily be done using Leaflet's utility methods. If you want to do this with a complex shape like
L.Polygon
you're going to need something like TurfJSFor
L.Circle
you need to calculate the distance between the circle's center and compare it to the radius:For
L.Rectangle
you need to fetch it's bounds object and use the contains method:As said for complex polygons i'de use Turf but there are more libraries and plugins out there. Here's an example using Turf's
inside
method. It take a GeoJSON point and polygon feature as parameters so mind the conversion:You could wrap those into convenience methods for each respective class:
Note that if you implement the polygon method that there is no need for the rectangle method. Since rectangle is extended from polygon it will inherit the method. I left it in there to be complete.
Now iterating your markers and comparing them is easy:
Hope that helps, here's a working snippet:
I used it:
Points that are on the edge but not in the circle are also judged.