Marker in leaflet, click event

后端 未结 5 1292
北海茫月
北海茫月 2020-12-04 19:12
var map = L.map(\'map\');
var marker = L.marker([10.496093,-66.881935]).on(\'click\', onClick);
function onClick(e) {alert(e.latlng);}
marker.addTo(map)
5条回答
  •  一向
    一向 (楼主)
    2020-12-04 19:34

    The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:

    Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.

    So you could create a marker as suggested by the question above:

    L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);
    

    Then create the onClick function:

    function onClick(e) {
        alert(this.getLatLng());
    }
    

    Now anytime you mouseover that marker it will fire an alert of the current lat/long.

    However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:

    L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
        console.log(e.latlng);
    });
    

    Here is the documentation: http://leafletjs.com/reference.html#events

提交回复
热议问题