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();
});
推荐答案
在上面的代码片段中,在添加事件处理程序时没有定义标记.在创建标记后立即添加 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
调用中将 position
放入了一个数组中,但它已经是一个 LatLng
对象.
You also put position
into an array in the call to setLatLng
but it is already a LatLng
object.
相关文章