简体   繁体   中英

general javascript

i havent written in js in awhile and am a bit rusty apparently. trying to understand the following problem. the alert in getCurrentPosition successCallback shows the latitude correctly, but the last line alerts undefined . why isnt my client_location function returning the latitude when call outside the function?

client_location = function() {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      alert(position.coords.latitude);  ## RETURNS LATITUDE CORRECTLY ##
      return position.coords.latitude;
    });
  }
};
alert(client_location());               ## RETURNS UNDEFINED ##

You're passing a callback to getCurrentPosition and your alert is inside that callback. Your return position.coords.latitude is also inside that callback. Your client_location function returns whatever getCurrentPosition returns and getCurrentPosition doesn't return anything .

If you want to do something with the latitude, you'll have to do it inside your callback; you could hand client_location a callback like this:

client_location = function(callback) {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      callback(position.coords.latitude);
    });
  }
};

client_location(function(lat) {
    alert(lat);
});

If the device does not return a geolocation it is undefined. Add an else statement to deal with no geolocation.

client_location = function() {
  if (navigator.geolocation) {
    return navigator.geolocation.getCurrentPosition(function(position) {
      alert("clientLocation: "+position.coords.latitude);
      return position.coords.latitude;
    });
  }else{
    return("no navigator.geolocation");  
  }
};
alert(client_location()); 

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