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

前端 未结 4 1327
面向向阳花
面向向阳花 2020-12-31 03:46

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 name

相关标签:
4条回答
  • 2020-12-31 03:54

    Here's a fully working function that does the job:

    // var map is an instance of a Leaflet map
    // this function assumes you have added markers as GeoJSON to the map
    // it will return an array of all features currently shown in the
    // active bounding region.
    
    function getFeaturesInView() {
      var features = [];
      map.eachLayer( function(layer) {
        if(layer instanceof L.Marker) {
          if(map.getBounds().contains(layer.getLatLng())) {
            features.push(layer.feature);
          }
        }
      });
      return features;
    }
    
    0 讨论(0)
  • 2020-12-31 03:55

    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);
    });
    
    0 讨论(0)
  • 2020-12-31 03:58

    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

    0 讨论(0)
  • 2020-12-31 04:02

    Regarding the last part of your question, if you want to iterate through visible layers, you can use eachLayer, e.g:

    map.eachLayer(function (layer) {
        // do something with the layer
    });
    

    API reference: http://leafletjs.com/reference.html#map-stuff-methods

    0 讨论(0)
提交回复
热议问题