0

what am I missing here?

I am creating a simple map app and intend to use the lat/lon coords for some ajax/php calls to a couple of api's.

I cant seem access the value of an array (which I will then later use in the ajax call). I've had similar problem before and resorted to taking the values from the HTML element, which makes no sense.

window.addEventListener('load', () => {

  let latlon = []

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      document.getElementById("information").innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    let lat = position.coords.latitude;
    let long = position.coords.longitude;
    latlon.push(lat, long)
    document.getElementById("information").innerHTML = `lat: ${lat}, long: ${long}`
  }

  getLocation()

  console.log(latlon[0]) // returns undefined
  console.log(latlon) // returns array with the 2 coords

  //code continues......

in short my question is why does the first console log return undefined and how would I extract the value as string to allow me to insert in to the ajax call.

thanks in advance

VLAZ
  • 26,331
  • 9
  • 49
  • 67
trig79
  • 384
  • 3
  • 12
  • 4
    `navigator.geolocation.getCurrentPosition` is asynchronous in nature. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition – Taplar Sep 30 '20 at 21:43
  • Does this answer your question? [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – VLAZ Sep 30 '20 at 21:44
  • Hey, I'm not sure the asynchronous nature of the function should cause an issue, as i can console.log the information out as a whole, but its only when i try and grab 1 value i have an issues. Let pick this up later today and i'll do some more testing and read up on what VLAZ has said. I'll update with a jsfiddle if needed. cheers – trig79 Oct 01 '20 at 07:49

0 Answers0