-1

I have the following function.

 function geocodePosition(pos, inputField) {
     var retvalue = "";
     geocoder = new google.maps.Geocoder();
     geocoder.geocode({latLng: pos}, function (results, status) {

          if (status == google.maps.GeocoderStatus.OK) {
              retvalue = results[0].formatted_address;
              inputField.value = retvalue;
          } else {
             alert('Cannot determine address at this location status [' + status + "]");
          }

     });
     alert ("retvalue : " + retvalue);
     return retvalue;
 }

I know that I am missing something fundamental here. But retvalue in the alert Statement is allways blank. How do I set it in the function block of the call to geocode.

Kind regards

Michael

mbieren
  • 1,034
  • 8
  • 31

1 Answers1

0

This is because the Geocoding process is async. Which means that your alert is executed, before the data are there. You could use a callback function like this:

reverseGeocoder: function (lat, lng, callback) {

    var geocoder = new google.maps.Geocoder;
    var addressComponents = {};
    geocoder.geocode({
        'location': {
            lat:lat,
            lng: lng
        }
    }, function (results, status){
        if(status === google.maps.GeocoderStatus.OK){

                callback(results);
            } else {
                alert('No information found.');
            }

        }else {
            alert("Error "+status);
        }
    });

Usage:

doGeocode (lat, lng, function (response){
 //here are your data
)};
el solo lobo
  • 973
  • 11
  • 23
  • Thanks a lot. I modified the code in order to pass the MapMarker to the function reversegeocode and set title of the marker with the geocode result. – mbieren Feb 07 '17 at 10:13