javascript - Google Maps LatLng returning (NaN,NaN) -


i obtaining clients geographic coordinates following code:

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

i trying turn google map coordinate following code

var clientlocation = new google.maps.latlng(loc.lat, loc.lng); 

this returning

(nan,nan) 

can suggest may doing wrong?

it's because getcurrentposition() asynchronous you're expecting synchronous response.

getcurrentposition() takes function argument, i'm assuming call when has finished running. function callback updates loc object.

the problem you're expecting loc updated before getcurrentposition has finished running.

what should instead let function call latlng creation, this:

var loc={} // don't forget var declaration, or might mess 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);      // , whatever else need when have coordinate } 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -