google-mapsgeocode

Store result of Google Maps geocode function


I want to retrieve and store the result of Google Maps API function geocode() in order to use it later. I have put the code below on an OnClick event to reverse geocode the address of the point clicked on the map.

The problem is that it always contains the value of the previous point clicked. Example: the first time I click it is 'undefined', 2nd time it is the address of the point I clicked before and so on.

var address ;


my_listener = google.maps.event.addListener(map, 'click', function(event) {
   codeLatLng(event.latLng);
});

function codeLatLng(mylatLng) {
    
    geocoder = new google.maps.Geocoder();
    var latlng = mylatLng;

    geocoder.geocode({'latLng': latlng}, function(results, status) 
    {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            if (results[1]) 
            {
                address = results[1].formatted_address;
            }
        }
    });

    alert(address);
}

Solution

  • If you will move alert, inside of callback, you will see the new address:

    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            if (results[1]) 
            {
                address = results[1].formatted_address;
                alert(address);   //moved here
            }//   ^
        }//       |
    });//         |  
    //-------------
    

    Geocoding process is asyncronous, so in this case:

    geocoder.geocode({'latLng': latlng}, function(results, status) {
        //We be called after `alert(address);`
    });
    alert(address);
    

    alert will be executed before the geocoding data will be recieved from server and callback function(results, status){} will be called.