简体   繁体   English

第一次单击时不打开传单弹出窗口

[英]Leaflet popup doesnt open on the first click

I have a function which creates a marker and binds a popup to it. 我有一个创建标记并将其绑定到弹出窗口的函数。 I want the popup to open and close with a single mouse click. 我希望单击鼠标即可打开和关闭弹出窗口。 What happens is that the popup doesn't open on the first click. 发生的是,弹出窗口在第一次单击时没有打开。 Second click and all the subsequent clicks do the job. 第二次单击,随后的所有单击都会完成此工作。 No errors in the browser console. 浏览器控制台中没有错误。 What can be the problem? 可能是什么问题?

Here's the code: 这是代码:

function addPlace() {
    var myIcon = L.icon({
        iconUrl: 'images/store.png',
        iconSize: [45, 47],
        iconAnchor: [22, 94],
        popupAnchor: [-3, -76],
    });

    var popup1 = L.popup()
        .setLatLng([32.07753, 34.76988])
        .setContent("Best shop<br>Food, drinks and more")

    var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
        .on('click', function() { shop.bindPopup(popup1); })
        .addTo(mymap);
};

You aren't binding the pop up until you click the first time: 在第一次单击之前,您不需要绑定弹出窗口:

var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
    .on('click', function() { shop.bindPopup(popup1); })

The first click binds the pop up, as the pop up isn't bound before the first click, it won't trigger. 第一次单击将绑定弹出窗口,因为弹出窗口在第一次单击之前未绑定,因此不会触发。

The second click now can activate the popup, which is now bound to the marker. 现在,第二次单击可以激活弹出窗口,该弹出窗口现在已绑定到标记。 This is why it takes two clicks. 这就是为什么需要两次单击的原因。

You can bind the popup to the layer when you add it, from the API docs: 您可以从API文档将弹出窗口添加到图层上,然后将其绑定到该图层:

All layers share a set of methods convenient for binding popups to it. 所有层共享一组方便将弹出窗口绑定到其的方法。

 var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map); layer.openPopup(); layer.closePopup(); 

Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened. 单击该图层时,弹出窗口也将自动打开;从地图上删除该图层或打开另一个弹出窗口时,弹出窗口也将自动关闭。 ( api docs ) api docs

Therefore you don't need to actually use an event listener explicitly. 因此,您实际上不需要显式使用事件侦听器。

As a result, you should be able to do: 结果,您应该能够:

var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
    .bindPopup(popup1)
    .addTo(mymap);

You could keep the current implementation, if you open the popup when it is bound: .on('click', function() { shop.bindPopup(popup1).openPopup(); }) , but it seems unnecessary to rebind it each click 如果在绑定弹出窗口时打开它,则可以保留当前的实现: .on('click', function() { shop.bindPopup(popup1).openPopup(); }) ,但是似乎没有必要重新绑定每个.on('click', function() { shop.bindPopup(popup1).openPopup(); })点击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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