0

The user's longitude and latitude is stored in variables called currentLon and currentLat. When I use console.log() to output the values of these variables, it is shown as undefined even though the values are assigned to the variables. I did the same thing inside the function which assigns values to the variables (show()) and they outputted the correct values, but this only happens inside the function. Everywhere else, it returns undefined.

I think that this may be due to the callback function that is used to get and store the user's location because when I used multiple console.log(), the one inside the show() function was shown last so it could be because the values are assigned after the rest of the program has run.

How do I fix this?

navigator.geolocation.getCurrentPosition(show);

let currentLon;
let currentLat;

function show(position) {
  currentLon = position.coords.longitude;
  currentLat = position.coords.latitude;
  console.log(currentLon) // this works
}

console.log(currentLon) // returns undefined

Sidebar()


function Sidebar() {
  let lat = currentLat;
  let lon = currentLon;

  const setToCurrent = () => {
    lat = currentLat;
    lon = currentLon;
    console.log("set to current location");
    console.log(lon, lat, "lon and  lat"); // returns undefined
    console.log(currentLon); // returns undefined
  };
  
  setToCurrent()

  return null;
}
tices
  • 108
  • 8
  • 2
    Your first `console.log(currentLon)` happens before any functions are called; you haven't set the value of the variable yet. – mykaf Jan 26 '23 at 21:33
  • 1
    "*it is shown as undefined even though the values are assigned to the variables.*" - no they were not - yet. Call `Sidebar()` from within `show` and it'll work. – Bergi Jan 26 '23 at 21:34

0 Answers0