Pregunta

I have a problem with the below function:

function geo(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            return results[0].geometry.location;
        }
    });
}

It returns me "undefined". Any help would be approciated. Thanks a lot!

¿Fue útil?

Solución

Actually your geocoding code is correct. The problem is that "geocoder.geocode" is asynchronous, and the geo function finishes execution before the geocoding result is fetched. As a proof of concept just try this:

function geo(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            alert(results[0].geometry.location); //should have valid info
            return results[0].geometry.location;                    
        }
    });

    alert("I bet you were not expecting this alert to go first");                
}

So, you have two options. Either you handle the geocoding location inside the geo function or you supply a callback with the function that will handle the location.

I've updated your fiddle with an example of this. Check it here

Otros consejos

Ok, thanks.

I found other solution - It's better to save a value from results[0].geometry.location to cookie and use wherever I want. Thanks anyway!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top