-2

I'm trying to store the location value out of the function's scope. The HTML5 geolocation API is what I need. Here is my code:

var location={};
navigator.geolocation.getCurrentPosition(function maPosition(position) {

          location.latitude = position.coords.latitude;
          location.longitude = position.coords.longitude;
    });

console.log(position.latitude);
console.log(position.longitude);

When I run this, I get the error variable undefined. This is due to the fact that it might not be available in in the scope of maPosition. Since I'm a rookie in JavaScript I was wondering what is the way around it. How can I access the value of position.coords out of the scope it's declared in? Can anyone help?

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
skip87
  • 529
  • 1
  • 7
  • 27

1 Answers1

1

The position variable is passed to the callback function in getCurrentPosition. it's only available inside that function

try:

var location={};
navigator.geolocation.getCurrentPosition(function maPosition(position) {

      location.latitude = position.coords.latitude;
      location.longitude = position.coords.longitude;
      console.log(position.latitude);
      console.log(position.longitude);
      // or you could call another function and pass the value
      //someFunction(position):
});

The call to the geolocation services are asyc, so if you want to use the value of position you need to either do it in the callback or pass it to another function.

atmd
  • 7,430
  • 2
  • 33
  • 64
  • 1
    That's not what i'm trying to do. im' trying to get the value out of the scope the console log is here to show that it's not working . but thank you! – skip87 Jun 22 '15 at 14:37
  • It still needs to read `location.*` when logging, otherwise it will log undefined – m90 Jun 22 '15 at 14:37
  • 1
    as you'll see from my answer, the call is asyc, you'll need to use the value inside the function or pass it to another function to deal with – atmd Jun 22 '15 at 14:39