[英]Google Maps LatLng returning (NaN,NaN)
我正在使用以下代码获取客户的地理坐标:
loc={}
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
loc.lat = position.coords.latitude;
loc.lng = position.coords.longitude;
});
}
然后,我尝试使用以下代码将其转换为Google地图坐标
var clientLocation = new google.maps.LatLng(loc.lat, loc.lng);
然而这又回来了
(NaN,NaN)
谁能暗示我可能做错了什么?
这很可能是因为getCurrentPosition()是异步的,但是您希望获得同步响应。
getCurrentPosition()将您的函数作为参数,我假设它将在完成运行时调用。 您的函数是一个用于更新loc对象的回调。
然后的问题是,您希望loc在getCurrentPosition运行完成之前得到更新。
相反,您应该做的是让您的函数调用LatLng创建,如下所示:
var loc={} // Don't forget the var declaration, or you might mess with the global scope
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
loc.lat = position.coords.latitude;
loc.lng = position.coords.longitude;
createLatLng();
});
}
function createLatLng() {
var clientLocation = new google.maps.LatLng(loc.lat, loc.lng);
// and whatever else you need to do when you have the coordinate
}
实际上,它将loc.lat和loc.lng作为2个参数。 那就是您得到(NaN,NaN)错误的原因。 通过直接传递坐标值来使用以下代码,
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(pos) {
var myCenter = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
marker.setMap(map);
}
function onError(){
alert('error');
}
希望对您有帮助!!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.