2013-02-22 32 views
2

每次位置更新時,都會放置一個新標記,而不是移動現有標記。我只是希望在屏幕上有一個標記,而不是每次應用程序更新其位置時放置一個新標記(忽略最大年齡和頻率,我正在測試某些東西,並且我知道它們不是問題)。提前致謝。更新地理位置標記,而不是使用傳單api添加新標記

(代碼加載地圖)

function onLocationFound(e) { 

           var marker= L.icon({iconUrl: 'greendot.png'}); 
    var radius = e.accuracy /2; 

    L.marker(e.latlng, {icon: marker}).addTo(map).bindPopup("You are within " + radius + " meters from this point").openPopup(); 



            } 

    function onLocationError(e) { 
     alert(e.message); 
    } 


    map.on('locationfound', onLocationFound); 
    map.on('locationerror', onLocationError); 

    map.locate({watch: true, setView: true, maxZoom: 16, enableHighAccuracy: true, maximumAge:10000, frequency: 1}); 

編輯:我嘗試了好幾種解決方案,並標記仍犯規的舉動,它只是增加了一個新的。有任何想法嗎?

回答

2

不是每次都創建一個新的標記,你可以更新現有的:

var marker = L.icon({iconUrl: 'greendot.png'}); 
var movingMarker = L.marker([0,0], 0, {icon: marker}).addTo(map); 

function onLocationFound(e) { 
    var radius = e.accuracy /2; 
    movingMarker.setLatLng(e.latlng); 
    movingMarker.unbindPopup(); 
    movingMarker.bindPopup("You are within " + radius + " meters from this point") 
    movingMarker.redraw(); 
} 

function onLocationError(e) { 
    alert(e.message); 
} 

map.on('locationfound', onLocationFound); 
map.on('locationerror', onLocationError); 

map.locate({watch: true, setView: true, maxZoom: 16, enableHighAccuracy: true, maximumAge: 10000}); 

我剛剛發現了類似的問題(一個類似的答案):update marker location with leaflet API