Rich King Rich King - 10 months ago 77
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');

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:


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


...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 Source

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.on('ready', function() {