leaflet.js - 单击时设置标记,拖动时更新位置 [英] leaflet.js - Set marker on click, update position on drag

查看:1475
本文介绍了leaflet.js - 单击时设置标记,拖动时更新位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

在上面的代码片段中,在添加事件处理程序时未定义marker 。在创建标记后立即添加dragend侦听器,尝试以下操作:

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:

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

您在新的L.Marker()行末尾也错过了一个括号。

You were also missing a bracket at the end of your new L.Marker() line.

您还可以在 setLatLng 位置放入数组中>但它已经是 LatLng 对象。

这篇关于leaflet.js - 单击时设置标记,拖动时更新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆