0

I want to store the geolocation but when I go and store the latitude and longitude in variables outside the scope they won't store. Does anybody know why this is the case? I've tried with undefined variables too but that hasn't worked either.

Here's my code:

$(document).ready(function(){
var location = {lat:'', lon:''};

function updateLocation(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position){
            location.lat = position.coords.latitude;
            location.lon = position.coords.longitude;
        });
    }
}

updateLocation();

$("#data").html("lat: " + location.lat + " lon: " + location.lon);

});
jhpratt
  • 6,841
  • 16
  • 40
  • 50
agutier2
  • 35
  • 1
  • 7

1 Answers1

0

2 big issues with your code:

  1. You try to call updateLocationbefore the function is defined. updateLocation is defined inside $(document).ready, while the calling happens outside. Please execute everything only when the document is ready.

  2. location is a name preserved for window.location. While using that name is ok, it is highly recommended to change that variable name to avoid confusion and wrong behaviors.

blaz
  • 3,981
  • 22
  • 37