-1

I am using the Google Maps API Geocoder to try and get lat/lng from an address.

Here is my code:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    function geocodeAddress(address) {
        geocoder.geocode({address:address}, function (results,status){
            if (status == google.maps.GeocoderStatus.OK) {
                var p = results[0].geometry.location;
                var lat=p.lat();
                var lng=p.lng();
                var location = '{'+lat+','+lng+'}';
                // If I alert(location) here, I get the correct lat/lng
                return location;
                // The return isn't happening?
            } else {
                alert('GeoCoder problem');
            }
        });
    }

    var geocoder = new google.maps.Geocoder();
    var point = geocodeAddress('Cape Town Carnival, Somerset Road, Green Point, South Africa');
    alert(point);  // this returns "Undefined".
</script>

This is in FF. I am getting no JS errors. I am not a JS expert. can anyone see what I am doing wrong?

Thanks

J

Jacques
  • 1,649
  • 2
  • 14
  • 23

1 Answers1

3

You get undefined because geocode() is an async function. To get the result, you have to - for example - pass a callback function to your geocodeAddress() and call that when you have the location.

 function geocodeAddress(address, succCallback) {
        geocoder.geocode({address:address}, function (results,status){
            if (status == google.maps.GeocoderStatus.OK) {
                var p = results[0].geometry.location;
                var lat=p.lat();
                var lng=p.lng();
                var location = '{'+lat+','+lng+'}';

                succCallback(location);
            } else {
                alert('GeoCoder problem');
            }
        });
    }

var geocoder = new google.maps.Geocoder();
var point = geocodeAddress(
    'Cape Town Carnival, Somerset Road, Green Point, South Africa', 
    function(l) {
        alert(l);
    });
laszlokiss88
  • 4,001
  • 3
  • 20
  • 26