0

This is from a tutorial, so see me as a noob, in this matter.

Can't return a value from a function. must be blind!
I keep getting undefined! Why is that? If I log inside the function it return the value. I placed the variables as global.

Here's the code:

var latitude = 0;
var longitude = 0;

function getPosition() {
  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function (position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      // console.log(latitude);
    })
    return latitude;
  } else {
    alert("Can't retrieve your location. Please enable it in your browser")
  }
}


$(document).ready(function () {
  var x = getPosition()
  $('body').click(function () {
    alert(x);
  });
});
body {
  font-family: helvetica, sans-serif;
  background-color: black;
  color: white;
  text-align: center;
}

footer p {
  font-size: 14px;
}

section p {
}

#header {
  font-size: 66px;
}

#header-1 {
  margin-bottom: 10px;
}

#header-2 {
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <header id="header">
      <p id="header-1">XPTO</p>
      <p id="header-2">Weather App</p>
    </header>
    <section>
      <p id="location"></p>
      <p id="temperature"></p>
    </section>
    <div class="footer">
      <footer>
        <p> Inspired by me</p>
      </footer>
    </div>
  </div>
Luís Alves
  • 463
  • 1
  • 5
  • 20
  • getCurrentLocation is asynchronous, it can still be running in the background when your function returns and you alert the result. See [unable to cope with the asynchronous nature of navigator.geolocation](https://stackoverflow.com/questions/2707191/unable-to-cope-with-the-asynchronous-nature-of-navigator-geolocation) – Alex K. Jun 16 '17 at 10:59
  • function `getPosition()` doesn't return anything at all ... and `geolocation.getCurrentPosition()` is **asynchronous** – charlietfl Jun 16 '17 at 11:00
  • Oh ok. Didi not see that. Will read further. Thanks. – Luís Alves Jun 16 '17 at 11:01
  • @charlietfl, your are right the return statement is misplaced [corrected], and I must read further on asynchronous calls – Luís Alves Jun 16 '17 at 11:05

0 Answers0