Search code examples
javascriptruby-on-railsgoogle-mapsgoogle-maps-api-3geocode

unable to modify global variable in javascript


var address ="<%= params[:search] %>";
var lat;
var long;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
	lat = results[0].geometry.location.lat();
	long = results[0].geometry.location.lng();
}); 
alert(lat);
//wanna use lat and long here!

browser always alert "undefined" when called outside the function, works when called from within the function.


Solution

  • The geocoder.geocode function is asynchronous, and it receives latitude and longitude inside a callback function - after the asynchronous operation is complete. Only then the lat and long variables are defined.

    Your alert runs immediately after starting the asynchronous operation, meaning that it's still not complete by the time the alert is fired. So, lat and long are still undefined.

    You cannot use latitude and longitude outside of the callback block. Move it inside the callback block and it will work:

    var address ="<%= params[:search] %>";
    var lat;
    var long;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        lat = results[0].geometry.location.lat();
        long = results[0].geometry.location.lng();
        // you can use lat and lng inside here! :)
        alert(lat);
    });
    

    Read this post if you want to get a better understanding of asynchronous code in JavaScript: https://stackoverflow.com/a/14220323/2401947