0

I'm trying to use the getCurrentPosition's values (new_lat, new_lon) in the main code of the script. A piece of my code:

var rememberLat = document.getElementById('id_latitude').value;
var rememberLong = document.getElementById('id_longitude').value;

function success(position) {
  var lat = document.getElementById('id_latitude');
  var lon = document.getElementById('id_longitude');
  lat.value = position.coords.latitude;
  lon.value = position.coords.longitude;
  var new_lat = lat.value;
  var new_lon = lon.value;
  return {
    new_lat: new_lat,
    new_lon: new_lon
  }
};

navigator.geolocation.getCurrentPosition(success);
if (!rememberLat || !rememberLong) {
  rememberLat = new_lat;
  rememberLong = new_lon;
}

var tileLayer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}    /{y}.png', {
  attribution: '&copy; <a href="http://www.openstreetmap.org    /copyright">OpenStreetMap</a> Contributors'
});
var map = new L.Map('map', {
  'center': [rememberLat, rememberLong],
  'zoom': 8,
  'layers': [tileLayer]
});

but I can return and assign them out of the callback function. It raises the following error:

Uncaught ReferenceError: new_lat is not defined

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Capdi
  • 247
  • 2
  • 14
  • you can add the error here in your OP so that troubleshooting becomes more efficient, since we donot know what is `undefined` – Muhammad Omer Aslam Nov 21 '17 at 10:37
  • 1
    Your issue is because `getCurrentPosition()` is asynchronous, so you're attempting to use `new_lat` and `new_lon` *before* they are assigned. You're already using the `success` callback properly, you just need to add all code which relies on the retrieve lat/lng *inside* that callback. – Rory McCrossan Nov 21 '17 at 10:39
  • Thank you @Roy McCrossan ! I added all my code in the callback function and it worked ! – Capdi Nov 21 '17 at 11:16

0 Answers0