简体   繁体   English

Google Maps LatLng返回(NaN,NaN)

[英]Google Maps LatLng returning (NaN,NaN)

I am obtaining my clients geographic coordinates with the following code: 我正在使用以下代码获取客户的地理坐标:

loc={}
if (navigator.geolocation)
{
   navigator.geolocation.getCurrentPosition(function(position){
      loc.lat = position.coords.latitude;
      loc.lng = position.coords.longitude;
                                                              });
}

I am then trying to turn this into a google map coordinate with the following code 然后,我尝试使用以下代码将其转换为Google地图坐标

var clientLocation = new google.maps.LatLng(loc.lat, loc.lng);

This however is returning 然而这又回来了

(NaN,NaN)

Can anyone suggest what I may be doing wrong? 谁能暗示我可能做错了什么?

It's most likely because getCurrentPosition() is asynchronous but you're expecting a synchronous response. 这很可能是因为getCurrentPosition()是异步的,但是您希望获得同步响应。

getCurrentPosition() takes your function as an argument, which I'm assuming it will call when it has finished running. getCurrentPosition()将您的函数作为参数,我假设它将在完成运行时调用。 Your function is a callback which updates your loc object. 您的函数是一个用于更新loc对象的回调。

The problem then is that you're expecting loc to be updated before getCurrentPosition has finished running. 然后的问题是,您希望loc在getCurrentPosition运行完成之前得到更新。

What you should do instead is to let your function call the LatLng creation, like this: 相反,您应该做的是让您的函数调用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
}

Actually, it will take loc.lat and loc.lng as a 2 arguments. 实际上,它将loc.lat和loc.lng作为2个参数。 That's what you are getting the (NaN,NaN) error. 那就是您得到(NaN,NaN)错误的原因。 Use the following code by passing coordinate values directly, 通过直接传递坐标值来使用以下代码,

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

Hope It will Help You!!!!! 希望对您有帮助!!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM