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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18575722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:59:24  来源:igfitidea点击:

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

javascriptjquerymapsmarkerleaflet

提问by kirijanker

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. 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? ;)

对于我正在处理的一个小项目,我需要能够在leaflet.js 驱动的图像地图上放置一个标记,并在它被拖动时更新该标记的位置。我使用下面的代码来尝试这个,但它失败了。我收到错误“标记未定义”。我不知道为什么它不起作用 - 也许你们可以帮助我?;)

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();
});

回答by user2680198

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:

在上面的代码片段中,在添加事件处理程序时没有定义标记。尝试以下操作,在创建标记后立即添加 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 positioninto an array in the call to setLatLngbut it is already a LatLngobject.

您还在position调用中放入了一个数组,setLatLng但它已经是一个LatLng对象。