Question

I'm trying to execute function after layer is added to map, this code does not work as expected.

var l = new L.GeoJSON(data);
l.on('layeradd', function(e) {
    console.log('layeradd', e);
});
map.addLayer(l);
Was it helpful?

Solution

If you're trying to get a layer add event of the GeoJSON layer, you should do .on('layeradd' on the map object, rather than the l object. If you want layeradd events within the GeoJSON layer, bind the layeradd event but add the data later - initialize as new L.GeoJSON(), then bind the event, then l.addData(data).

OTHER TIPS

In case someone wants to do this with react-leaflet, I was not able to listen to layeradd on the map as suggested by @tmcw. However, listening to add on the layer worked:

<GeoJSON data={jsonContent}
  eventHandlers={{
    add: (e) => e.target._map.fitBounds(e.target.getBounds())
  }} 
/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top