問題描述
我想使用 Leaflet API 構建 Web 應用程序.首先,我的用戶使用 IP 進行地理定位,然后如果他接受,我嘗試使用 HTML5 地理定位更新他的位置(準確性更好).
I want to build web app with the Leaflet API. First my user is geolocated with IP then if he accepts I try to update his position with HTML5 geolocation (accuracy is better).
我的問題是地圖上的標記位置未更新,并且下面的代碼失敗且沒有錯誤.我從 leaflet 文檔 嘗試了數百種不同的語法和方法來更新標記位置(即 setLatLng),但我沒有成功.我想了解我的代碼有什么問題.
My problem is that the marker position is not updated on the map and the code bellow fails with no error. I have try hundred of different syntax and methods from leaflet documentation to update marker position (ie. setLatLng) but I did not succeed. I would like to understand what's wrong with my code.
我的問題通過這樣做解決了:
My problem is solved by doing like this :
var lat = (e.latlng.lat);
var lng = (e.latlng.lng);
var newLatLng = new L.LatLng(lat, lng);
marker.setLatLng(newLatLng);
舊代碼是:
//initial IP based geolocation
var lat = google.loader.ClientLocation.latitude;
var lng = google.loader.ClientLocation.longitude;
//place marker on the map
var marker = L.marker([lat,lng]).addTo(map);
//start HTML5 geolocation
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var marker = L.marker([e.latlng.lat,e.latlng.lng]).update(marker);
alert ('New latitude is ' + e.latlng.lat)
}
map.on('locationfound', onLocationFound);
推薦答案
你的問題里面的代碼有點混亂,你只貼片段很難說是什么問題.
The code inside your question is a little bit confusing, it's hard to say what the issue is when you only post snippets.
事實上,這段代碼:
var lat = (e.latlng.lat);
var lng = (e.latlng.lng);
var newLatLng = new L.LatLng(lat, lng);
marker.setLatLng(newLatLng);
..應該在 onLocationFound()
中按預期工作.
..should work as expected inside onLocationFound()
.
你可以簡化它:
marker.setLatLng(e.latlng);
但是,我想問題是范圍問題,您的某些變量(例如標記)在 onLocationFound 中無法訪問.
However, I guess the problem is a scope-issue, some of your variables (e.g. marker) is not accessible inside onLocationFound.
這里是一個如何實現的例子:
Here an example how to achieve it:
function init(){
var map = L.map('map', {center: [51.505, -0.09], zoom: 13}),
marker = L.marker(map.getCenter()).addTo(map),
glcl = google.loader.ClientLocation,
onLocationfound = function(e){
marker.setLatLng(e.latlng);
map.setView(marker.getLatLng(),map.getZoom());
alert('Marker has been set to position :'+marker.getLatLng().toString());
};
L.tileLayer('http://{s}.tile.cloudmade.com/[yourCloudmadeKey]/997/256/{z}/{x}/{y}.png').addTo(map);
map.on('locationfound', onLocationfound);
if(glcl){//when google.loader.ClientLocation contains result
onLocationfound({latlng:[glcl.latitude,glcl.longitude]});
}else{alert('google.loader.ClientLocation fails');}
map.locate();
}
演示:http://jsfiddle.net/doktormolle/6ftGz/一個>
這篇關于使用傳單 API 更新標記位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!