Javascript bug in Google Maps integration
I am trying to get the following code to work (which looks really straightforward but it does not work like it is supposed to)
Please help me out here :
function findLocationAddress(myLatLng)
{
var formattedAddress='MY HOUSE ADDRESS';
geocoder.geocode({'latLng': myLatLng},function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[1])
{
formattedAddress = results[1].formatted_address;
}
}
});
alert(formattedAddress);
return formattedAddress;
}
The above function should return the new value of formattedAddress but it is still returning "MY HOUSE ADDRESS"
Any help is really appreciated开发者_JS百科.
The problem here is that the geocoder.geocode request is asynchronous, and you are returning your value synchronously. Try something like this:
function findLocationAddress(myLatLng)
{
var formattedAddress='MY HOUSE ADDRESS';
geocoder.geocode({'latLng': myLatLng},function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[1])
{
formattedAddress = results[1].formatted_address;
alert(formattedAddress);
// then do what you want (e.g. call a function) here
// e.g. doMyNextThing(formattedAddress);
}
}
});
}
Above code sample tested and working.
You can also use a callback function, if you like, to define what happens after the address is found (this will make the function much more reusable)
function findLocationAddress(myLatLng, callback)
{
var formattedAddress='MY HOUSE ADDRESS';
geocoder.geocode({'latLng': myLatLng},function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[1])
{
formattedAddress = results[1].formatted_address;
callback(formattedAddress);
}
}
});
}
findLocationAddress(myLatLng, function(formattedAddress){
// Do what you want with the result here
});
This may be obvious but note also results[1]
will give you the second result, as the array index starts at 0 (this may be intended behaviour)
精彩评论