0

I am using navigator.geolocation.getCurrentPosition(success, error); to get the user's location in an https web page. I have also defined var map; ...as a global var.

The success function gets called, but inside that function it doesn't seem to recognize "map" as a global variable. I can initialize the map and set the location of the map inside the success function, but after the success function ends, "map" is undefined again. That causes any other events with map to fail.

How can I get the map variable to be recognized inside of the success function, or return position.coords.latitude ...and position.coords.longitude

...from the success function so I can initialize the map?

2
  • 1
    Which GIS software?
    – Midavalo
    Commented Mar 9, 2017 at 5:39
  • The map is Leaflet, but no global variables are recognized within the success function().
    – Jim
    Commented Mar 9, 2017 at 14:03

1 Answer 1

3

To answer my own question, the best solution is to pass the lat/lng in the success function to a second function. The second function sees the global scope and you can initialize the map there. Something like this:

if (!navigator.geolocation)
{
    initMapWithoutLocation();
}
function success(position)
{
    lat = position.coords.latitude;
    lng = position.coords.longitude;
    initMapWithGeolocation(lat,lng);      
}// end success  
function failure()
{
  initMapWithoutGeolocation();
}// end failure

// Call the function with the function names for success or failure
navigator.geolocation.getCurrentPosition(success,failure);

Your second function, initMapWithGeolocation() in this case cannot be in an instance of a class, because the success() function cannot see the instance. Just send it to a function outside of the success() function.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.