Rich King Rich King - 1 month ago 11
Javascript Question

Leaflet: retrieving bounds for a KML polygon

I'm inserting polygons into a Leaflet map using a Leaflet plugin called leaflet-omnivore. The syntax I'm using is:

var polygon = omnivore.kml('placeName.kml');
polygon.addTo(map);


This works great; the polygon appears on my map. However, once it's added I want to then zoom/pan the map to fit the shape as best as possible. I've been trying this:

polygon.addTo(map).fitBounds();


...but that throws an error:
'fitBounds is not a function'
. I've also tried to find the coordinates using this:

polygon.addTo(map).getBounds().getNorthEast();


...but that comes back with
'cannot read property 'lat' of undefined'
.

Anyone have any ideas? I'm stumped. Documentation is here and I'm using Leaflet 1.0.0.

Answer

You have to wait till the .kml has loaded. So do your stuff after the 'ready' event has fired, stated in the docs HERE:

var polygon = omnivore.kml('yourKML.kml');
polygon.addTo(map);

polygon.on('ready', function() {
    map.fitBounds(polygon.getBounds())
});
Comments