Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of markers/layers within current map bounds in Leaflet

Tags:

This is somewhat similar to the question asked here --

I'm writing a search box for a map application, which retrieves a whole set of search results (people's names & info) at once from a server and then pages through the list of results. So at any given point on the map there are two kinds of markers -- a background marker for points which are in the search results but not in the current page, and a foreground marker for points which are in the current page of search results.

All this works nicely.. what I'd like to do now is set it up so that if a user zooms or pans the map, the search results list updates to show only markers within the current map bounds.

Obviously there are server-side ways to do this, or I could also just run through the whole list of markers to see which fit within the current bounds; but does anybody know a built-in way to do this within leaflet? Something which would look like map.getVisibleLayers()?

like image 998
Tim S Avatar asked Feb 27 '14 22:02

Tim S


2 Answers

I think this may be of help: https://github.com/stefanocudini/leaflet-list-markers

as you can see from the demo, including all markers in a layer, this plugin shows a list of only those visible in the current viewport. Its usage is simple, in a row:

var markersLayer = new L.LayerGroup();
map.addControl( new L.Control.ListMarkers({layer: markersLayer}) );

The code for obtain it is like as:

var layers = L.LayerGroup(), //layers contains all markers..
    contained = [];          //makers in map boundingbox

layers.eachLayer(function(l) {
    if( l instanceof L.Marker && map.getBounds().contains(l.getLatLng()) )
        contained.push(l);
});
like image 154
stefcud Avatar answered Sep 20 '22 02:09

stefcud


You have to check the bounds of each layer versus the map's bounds. Because eachLayer() returns all layers regardless of whether they are in the visible extent.

if(map.getBounds().contains(layer.getLatLng())) { ... }

In Stefano's code, this is shown around this line:

https://github.com/stefanocudini/leaflet-list-markers/blob/master/src/leaflet-list-markers.js#L95

like image 42
Alex G Rice Avatar answered Sep 21 '22 02:09

Alex G Rice