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

对于我正在进行的一个小项目,我需要能够在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(); }); 

在上面的代码片段中,在添加事件处理程序时未定义标记。 在创建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); }; 

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

您还可以在调用setLatLngposition放入数组中,但它已经是LatLng对象。