简体   繁体   English

leaflet.js - 单击时设置标记,拖动时更新位置

[英]leaflet.js - Set marker on click, update position on drag

for a small project I am working on, I need to be able to place a marker on a leaflet.js powered image-map and update the position of this marker, if it gets dragged. 对于我正在进行的一个小项目,我需要能够在leaflet.js驱动的图像映射上放置一个标记并更新该标记的位置(如果它被拖动)。 I use the following code to try this, but it fails. 我使用以下代码试试这个,但它失败了。 I get the error 'marker not defined'. 我收到错误'标记未定义'。 I don't know why it's not working - maybe you guys could help me out? 我不知道为什么它不起作用 - 也许你们可以帮助我? ;) ;)

function onMapClick(e) {
    gib_uni();
    marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'};
    map.addLayer(marker);
};

marker.on('dragend', function(event){
    var marker = event.target;
    var position = marker.getLatLng();
    alert(position);
    marker.setLatLng([position],{id:uni,draggable:'true'}).bindPopup(position).update();
});

In the code snippet above, marker is not defined at the time the event handler is added. 在上面的代码片段中,在添加事件处理程序时未定义标记。 Try the following where the dragend listener is added immediately following the creation of the Marker: 在创建Marker之后立即添加dragend侦听器,请尝试以下操作:

function onMapClick(e) {
    gib_uni();
    marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'});
    marker.on('dragend', function(event){
            var marker = event.target;
            var position = marker.getLatLng();
            console.log(position);
            marker.setLatLng(position,{id:uni,draggable:'true'}).bindPopup(position).update();
    });
    map.addLayer(marker);
};

You were also missing a bracket at the end of your new L.Marker() line. 您在新的L.Marker()行末尾也错过了一个括号。

You also put position into an array in the call to setLatLng but it is already a LatLng object. 您还可以在调用setLatLngposition放入数组中,但它已经是LatLng对象。

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

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