简体   繁体   中英

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

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() takes your function as an argument, which I'm assuming it will call when it has finished running. Your function is a callback which updates your loc object.

The problem then is that you're expecting loc to be updated before getCurrentPosition has finished running.

What you should do instead is to let your function call the LatLng creation, like this:

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. That's what you are getting the (NaN,NaN) error. 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!!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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