問題描述
對于我正在處理的一個(gè)小項(xiàng)目,我需要能夠在 Leaflet.js 驅(qū)動(dòng)的圖像地圖上放置一個(gè)標(biāo)記,并在它被拖動(dòng)時(shí)更新該標(biāo)記的位置.我使用下面的代碼來嘗試這個(gè),但它失敗了.我收到錯(cuò)誤未定義標(biāo)記".我不知道為什么它不起作用 - 也許你們可以幫助我?;)
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();
});
推薦答案
在上面的代碼片段中,在添加事件處理程序時(shí)沒有定義標(biāo)記.在創(chuàng)建標(biāo)記后立即添加 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() 行末尾還缺少一個(gè)括號.
You were also missing a bracket at the end of your new L.Marker() line.
您還在 setLatLng
調(diào)用中將 position
放入了一個(gè)數(shù)組中,但它已經(jīng)是一個(gè) LatLng
對象.
You also put position
into an array in the call to setLatLng
but it is already a LatLng
object.
這篇關(guān)于Leaflet.js - 點(diǎn)擊時(shí)設(shè)置標(biāo)記,拖動(dòng)時(shí)更新位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!