我試圖用leaflet map來顯示用戶在地圖上的當前位置。就像現場的GPS跟蹤。傳單地圖:使用navigator.geolocation.watchPosition更新標記?
這是我當前的代碼:
var watchID;
var geoLoc;
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if(err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
var map = L.map('map_2385853')
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);
/*L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 18
}).addTo(map);*/
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var radius = e.accuracy/2;
L.marker(e.latlng).addTo(map)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
map.on('locationfound', onLocationFound);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
getLocationUpdate();
此代碼僅添加了標記一次,並沒有做任何其他與它(不刪除或添加其他)用戶的位置發生變化時。
我在移動設備上試過上面的代碼,我可以確認標記只添加一次並停留在那裏。
請問有人能提供這方面的建議嗎?
這裏是一個工作FIDDLE:
https://jsfiddle.net/31ws6z37/
編輯:
這是我到目前爲止所。但我得到以下錯誤:
錯誤:
TypeError: map.removeLayer(...).bindPopup is not a function
map.removeLayer(marker)
CODE:
function initializeMapAndLocator(){
var map = L.map('map_2385853');
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);
map.locate({setView: true,
maxZoom: 16,
watch:true,
timeout: 60000
});
function onLocationFound(e) {
var radius = e.accuracy/2;
//L.marker(e.latlng).addTo(map)
marker = new L.Marker(e.latlng, {draggable:true})
map.addLayer(marker)
map.removeLayer(marker)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
map.on('locationfound', onLocationFound);
}
initializeMapAndLocator();
您是否嘗試在geoLoc.watchPosition()回調中添加標記? – Manuel
@曼紐爾,這就是我在我的代碼中所做的!因此它會被添加一次,但標記的位置不會被更新! – Jackson
我只看到你打電話給「showLocation」 – Manuel