Reputation: 5217
I have a polyline that needs to have a popup automatically open when the user selects the polyline layer in the layers control menu.
This method did not work for me:
var polyline = L.geoJson(myData).bindPopup("<h1>Some Text goes here</h1>").openPopup();
How can I do the auto popup?
Here's my current setup:
var polyline = L.geoJson(myData).bindPopup("<h1>Some Text goes here</h1>");
var overlaysMenuCtrl = L.Control.extend({ ... blah blah... });
map.addControl(new overlaysMenuCtrl)());
I extend the control and add a custom function to check for layers that are toggled on/off by the user:
function toggleLayer(checked, layer){
if(checked){
map.addLayer(layer);
} else {
map.removeLayer(layer);
}
}
$(".check").change(function(){
var layerClicked = $(this).attr("id");
//Turn layers on and off based on the ID of the radio checked
switch(layerClicked){
case "polyline": toggleLayer(this.checked, polyline);
break;
...and other layers ...
}
});
HTML:
<label><input id="polyline" type="checkbox" class="check">Polyline layer</label>
Upvotes: 1
Views: 2315
Reputation: 53205
There is very probably a delay between the moment you request to add your layer to the map, and when that layer is actually on map / ready to open its popup.
You could simply add an event listener (use the "add"
event) that will automatically open the popup whenever the layer is added to the map:
layer.on("add", function (event) {
event.target.openPopup();
});
Demo: https://jsfiddle.net/3v7hd2vx/101/ (use the Layers Control to add the layer to the map)
Upvotes: 1
Reputation: 19069
Run openPopup()
after the polyline has been added to the map.
Upvotes: 0