How to trigger events on Leaflet map polygons?
So, quick update.
Just call fireEvent (or its alias fire
) on whatever layer you need.
You don't need to risk ._private[Vars], just get a reference to the target layer and fire away, e.g.
var vectorLayer = map.getLayer('myVectorLayer');
vectorLayer.fire('click');
OK, I've figured it out.
You need to create a click event for each polygon that opens the popup, and assign a unique ID to each polygon so you can reference it later and manually trigger its popup.
The following accomplishes this:
var polyindex = 0;
popup = new L.Popup();
geojsonLayer = new L.GeoJSON(null, {});
geojsonLayer.on("featureparse", function (e){
(function(layer, properties) {
//click event that triggers the popup and centres it on the polygon
layer.on("click", function (e) {
var bounds = layer.getBounds();
var popupContent = "popup content here";
popup.setLatLng(bounds.getCenter());
popup.setContent(popupContent);
map.openPopup(popup);
});
})(e.layer, e.properties);
//assign polygon id so we can reference it later
e.layer._leaflet_id = 'polyindex'+polyindex+'';
//increment polyindex used for unique polygon id's
polyindex++;
});
//add the polygon layer
map.addLayer(geojsonLayer);
geojsonLayer.addGeoJSON(neighbourhood_polygons);
Then to manually trigger a specific layers click event, simply call it like this:
map._layers['polyindex0'].fire('click');
Everything between the square brackets is the unique ID of the layer you want to trigger. In this case, I'm firing the click event of layer ID polyindex0.
Hope this info helps somebody else out!