0

I'm trying to make a website which shows the longitude and latitude using the browser's navigator feature. When i run the code below I get Latitude:undefined instead of Latitude:[My latitude]. Can anyone help me out?

$(document).ready(function() {
  var la;
  var lg;

  function getLocation() {
    if (navigator.geolocation)
      navigator.geolocation.getCurrentPosition(showPosition);

  }

  function showPosition(position) {
    la = position.coords.latitude;
    lg = position.coords.longitude;
  }
  document.getElementById("lat").innerHTML = "Latitude:" + la;
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Daniel
  • 509
  • 1
  • 4
  • 17
  • The `getCurrentPosition()` call is asynchronous, so the `document.getElementById(...` line *has* to go within the `showPosition()` function, after you define `la` and `lg`. I'd also advise that you move the `la` and `lg` definitions to a more local scope – Rory McCrossan Jul 13 '17 at 13:46
  • I tried that, and now it doesn't show anything. – Daniel Jul 13 '17 at 14:58
  • Yes it does. I presume you're calling `getLocation()` - even though your sample code doesn't show it? https://jsfiddle.net/smyy7e1m/ – Rory McCrossan Jul 13 '17 at 15:00
  • Yeah, I didn't call `getLocation()` because i thought that the `$(document).ready(function() {` line will do that for me automatically, once the page is loaded. It works now. Thank you! – Daniel Jul 13 '17 at 15:09

0 Answers0