【发布时间】:2016-11-04 23:56:15
【问题描述】:
我正在尝试使用leaflet map 来显示用户在地图上的当前位置。类似于实时 GPS 跟踪。
这是我当前的代码:
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();
当用户的位置发生变化时,此代码仅添加一次标记,并且不会对其执行任何其他操作(不会删除或添加另一个)。
我在我的移动设备上尝试了上面的代码,我可以确认标记只被添加一次并停留在那里。
有人可以就此提出建议吗?
这是一个有效的小提琴:
https://jsfiddle.net/31ws6z37/
编辑:
这是我到目前为止所拥有的。但我收到以下错误:
错误:
TypeError: map.removeLayer(...).bindPopup is not a function
map.removeLayer(marker)
代码:
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,这就是我在我的代码中所做的!因此它被添加一次,但标记的位置没有得到更新!
-
我只看到你叫“showLocation”
-
请添加一个小提琴,使其更容易
-
@Manuel,我为我的问题添加了一个小提琴。 jsfiddle.net/31ws6z37
标签: javascript geolocation leaflet