简体   繁体   中英

Automatically open popup on layer add

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>

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)

将折线添加到地图 ,运行openPopup()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM