Skip to content
Advertisement

Get Bounds with Leaflet

I have a DC.JSc Charts which are filtering my icons on my Leaflet Map. Basically, when I’m filtering I want my map to zoom on my selected icons.

var onFilt = function(chart, filter) {
  updateMap(locations.top(Infinity));
};

// Updates the displayed map markers to reflect the crossfilter dimension passed in
var updateMap = function(locs) {
  // clear the existing markers from the map
  markersLayer.clearLayers();
  clusterLayer.clearLayers();

  locs.forEach(function(d, i) {

    if (d.latitude != null && d.latitude != undefined) {
      // add a Leaflet marker for the lat lng and insert the application's stated purpose in popup

      var mark = L.marker([d.latitude, d.longitude]);
      markersLayer.addLayer(mark);
      clusterLayer.addLayer(mark);

      map.getBounds();
    }
  });
};

I’ve tried:

map.getBounds(); //No response

L.markersLayer.getBounds(); //SCRIPT5007: Unable to get property 'getBounds' of undefined or null reference

map.fitBounds(markersLayer.getBounds()); // Object doesn't support property or method 'getBounds'

Also tried :

if (d.latitude != null && d.latitude != undefined) {
  d.ll = L.latLng(d.latitude, d.longitude);
  var mark = L.marker([d.latitude, d.longitude]);
  markersLayer.addLayer(mark);
  clusterLayer.addLayer(mark);
};
map.addLayer(markersLayer);
map.fitBounds(markersLayer.getBounds());
});

Error: Object doesn’t support property or method ‘getBounds’

Any ideas?

Found my own solution: map.fitBounds(clusterLayer.getBounds());

Advertisement

Answer

You’re almost there, but have several mistakes: you’re trying to getBounds within forEach loop, you’re trying to getBounds from the wrong object.

Please see and run the snippet below click FILTER button, read comments in JS code.

I omitted the filtering part, left zooming only:

// add a map
var map = L.map('mapid').setView([51.505, -0.09], 12);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1
    }).addTo(map);

// Assuming that locations are filtered already:
var locations = [
  {latitude: 51.5, longitude: -0.09},
  {latitude: 51.53, longitude: -0.19},
  {latitude: 51.45, longitude: 0},
  {latitude: 51.56, longitude: 0.09}
];

// Updates the displayed map markers to reflect the crossfilter dimension passed in
var updateMap = function(locs) {
  // clear the existing markers from the map
  //markersLayer.clearLayers();
  //clusterLayer.clearLayers();
  
  var minlat = 200, minlon = 200, maxlat = -200, maxlon = -200;
  
  locs.forEach(function(d, i) {

    if (d.latitude != null && d.latitude != undefined) {
      // add a Leaflet marker for the lat lng and insert the application's stated purpose in popup
      //var mark = L.marker([d.latitude, d.longitude]);
      //markersLayer.addLayer(mark);
      //clusterLayer.addLayer(mark);
      
      // find corners
      if (minlat > d.latitude) minlat = d.latitude;
      if (minlon > d.longitude) minlon = d.longitude;
      if (maxlat < d.latitude) maxlat = d.latitude;
      if (maxlon < d.longitude) maxlon = d.longitude;
      
      // set markers
      L.marker([d.latitude, d.longitude]).addTo(map);
    }
  });
  
  c1 = L.latLng(minlat, minlon);
  c2 = L.latLng(maxlat, maxlon);

  // fit bounds
  map.fitBounds(L.latLngBounds(c1, c2));
  
  // correct zoom to fit markers
  setTimeout(function() {
    map.setZoom(map.getZoom() - 1);
  }, 500);

};

function filtr() {
  updateMap(locations);
};
#mapid {
  height: 180px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />

<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>

<button onclick="filtr()">FILTER</button>

<div id="mapid"></div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement