Search code examples
javascriptfunctionvariablesgeolocationnavigator

Javascript Navigator.geolocation


I am trying to return the position.coords.latitude and longitude as variables to use elsewhere in the code. How do I get the function to return usable variables?

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
     var lat = position.coords.latitude; 
     var lon = position.coords.longitude;
     var values = [lat, lon];

     return values;

  });
}   

console.log(values);

Solution

  • You should use the callback methods.

    Have a read of this:

    https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

    var options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };
    
    function success(pos) { // success callback
      var crd = pos.coords;
    
      console.log('Your current position is:');
      console.log('Latitude : ' + crd.latitude);
      console.log('Longitude: ' + crd.longitude);
      console.log('More or less ' + crd.accuracy + ' meters.');
    
      var values = [crd.latitude, crd.longitude];
      doSomethingWithCoordinateValues(values);
    };
    
    function doSomethingWithCoordinateValues(coords) {
      // do something with 'coords'
    }
    
    function error(err) { // error callback
      console.warn('ERROR(' + err.code + '): ' + err.message);
    };
    
    navigator.geolocation.getCurrentPosition(success, error, options);
    

    You could also have a read of this answer that states:

    If an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.