7

I have a array of markers named markersand i add those markers in map using LeafletJs

L.layerGroup(markers).addTo(map);

Now i want to focus on a viewport that covers all markers

var bounds = L.latLngBounds(markers);
 map.fitBounds(bounds, { padding: [20, 20] });

Why i get Cannot read property 'lat' of undefined error message in map.fitBounds(bounds, { padding: [20, 20] }); line.

Moshi
  • 1,385
  • 2
  • 17
  • 36

1 Answers1

9

The reason you're getting an error is because L.LatLngBounds expects two L.LatLng objects as parameter, not an array of markers, as you can see in the documentation. I would suggest using L.FeatureGroup, it's extended from L.LayerGroup but has some extras. It has a getBounds method, which will do exactly what you need, calculate the bounds according to all of the features added to the group. So you could do:

var featureGroup = L.featureGroup(markers).addTo(map);
map.fitBounds(featureGroup.getBounds());

Here's a working example on Plunker: http://plnkr.co/edit/EbzlaF05fLARDYbnXSSk

iH8
  • 27,722
  • 4
  • 67
  • 76
  • I changed as you said but still has same problem. – Moshi Dec 12 '14 at 21:00
  • Then you must be doing something else wrong, but can't see what based on the code you've given. Here's a working plunker, also added to my answer: [http://plnkr.co/edit/EbzlaF05fLARDYbnXSSk](http://plnkr.co/edit/EbzlaF05fLARDYbnXSSk) – iH8 Dec 12 '14 at 22:20
  • Working example required " – flywire Sep 16 '20 at 12:27