Martin Dvoracek
Martin Dvoracek

Reputation: 1738

Storing value in javascript vars

This might be a lame question, but for me as a javascript newbie it's really a mystery. Here is a short sample of my code that handles geolocation:

  if (navigator.geolocation)
        {
            var latitude, longitude;
            navigator.geolocation.getCurrentPosition(
                    function(position) {
                        latitude = position.coords.latitude;
                        longitude = position.coords.longitude;
                        // Here I get user's coordinates
                        alert("Latitude : " + latitude + " Longitude : " + longitude);

                    },
                    function() {
                        alert("Geo Location not supported");
                    }
            );
            // Here I don't get anything
            alert("Latitude : " + latitude + " Longitude : " + longitude);
            new google.maps.Geocoder().geocode({
                location: new google.maps.LatLng(latitude ,longitude)
            }, this.getCallback());
        }
        else {
            error("Geolocation is not supported by this browser.");
        }

As I've already mentioned in the comments - I the first case, I get coordinates, but in the second one, the values of those vars are undefined and thus I can't get the location on the map... What may cause this and how to pass those values to the Geocoder ?

Upvotes: 0

Views: 50

Answers (1)

thescientist
thescientist

Reputation: 2948

That is how asynchronous requests work. You have to wait till the request completes and then execute the next block of code as callback to the success function. Executing it all in line will cause problems as you are experiencing.

function(position) {
  latitude = position.coords.latitude;
  longitude = position.coords.longitude;

  // Here I get user's coordinates
  alert("Latitude : " + latitude + " Longitude : " + longitude);

  new google.maps.Geocoder().geocode({
    location: new google.maps.LatLng(latitude ,longitude)
  }, this.getCallback());
}

note: you'll probably need to change the context of this, for this.callback

Upvotes: 1

Related Questions