gpt4 book ai didi

javascript - 使用传单 API 更新标记位置

转载 作者:行者123 更新时间:2023-12-02 23:44:06 25 4
gpt4 key购买 nike

我想使用 Leaflet API 构建 Web 应用程序。首先,我的用户使用 IP 进行地理定位,然后如果他接受,我会尝试使用 HTML5 地理定位更新他的位置(准确性更好)。

我的问题是 map 上的标记位置未更新,并且下面的代码失败且没有错误。我已经尝试了 leaflet documentation 中的数百种不同的语法和方法更新标记位置(即 setLatLng),但我没有成功。我想了解我的代码有什么问题。

<小时/>

我的问题是这样解决的:

    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);

最佳答案

您问题中的代码有点令人困惑,当您只发布片段时很难说出问题是什么。

事实上,这段代码:

    var lat = (e.latlng.lat);
var lng = (e.latlng.lng);
var newLatLng = new L.LatLng(lat, lng);
marker.setLatLng(newLatLng);

..应该在 onLocationFound() 内按预期工作。

你可以简化它:

marker.setLatLng(e.latlng);

但是,我想问题是范围问题,您的某些变量(例如标记)在 onLocationFound 内无法访问。

这里是如何实现它的示例:

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/

关于javascript - 使用传单 API 更新标记位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14173815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com