0

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 ##
0

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for the link to the interface GeoLocation. Shows exactly why the final alerted value is undefined and not something arbitrary.
@Ray: I prefer to supply an authoritative reference rather than expect people to trust me as an authority.
hm. im trying to write a simple function i can call that gets handed back the latitude, but i want to avoid having to pass any arguments to that function. how could i internalize passing in a callback into the client_location function?
@brewster: That's not going to work very well since getCurrentPosition is asynchronous; so, you don't know when you'll get your result from getCurrentPosition. I suggest that you get used to the async callback approach, you have to deal with it all the time when using AJAX and a lot of other APIs.
0

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()); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.