0

i have the following code:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(posi) {
    var lat = posi.coords.latitude;
    var lon = posi.coords.longitude;
    console.log(lat);
  }, showError);
} else {
  $(".position").html("Geolocation is not supported by this browser");
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      alert("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      alert("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");
      break;
  }
}

alert(lat);
$(".weather").html("<p>" + lat + "</p>");

the problem is that at the alert(lat) at te bottom it says that it is undefined and at the start at the if condition the console.log(lat) works perfectly fine! what is wrong at the bottom? i have tried making global variables lon, lat before if but the same thing happens.

5
  • 2
    geolocation is asynchronous. You are trying to alert it before the data is returned. Consume it in the callback. Notice that the alert fires before the console.log() Commented Oct 1, 2015 at 23:14
  • thanks i'll try that!!! Commented Oct 1, 2015 at 23:18
  • 1
    Yes...alert fires before the log(). That's how asynchronous operations work ... it takes time to send and receive the request Commented Oct 1, 2015 at 23:18
  • 1
    The second problem is with the scope of variable lat. You are defining it in anonymous function so it will always be undefined in the alert. Try moving variable definition before if statement. Commented Oct 1, 2015 at 23:56
  • even when i defined it as global outside i had the same problem.. and it must have been the asychronous concept that was the conflict. Commented Oct 2, 2015 at 13:40

1 Answer 1

1

For reference, here is the corrected code, based on the earlier comments:

function showError(error) {
  [...] // No change.
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(posi) {
    var lat = posi.coords.latitude;
    var lon = posi.coords.longitude;
    console.log(lat);
    alert(lat);
    $(".weather").html("<p>" + lat + "</p>");
  }, showError);
} else {
  $(".position").html("Geolocation is not supported by this browser");
}
Sign up to request clarification or add additional context in comments.

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.