[英]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.