问题
I have the following function:
$(function() {
var address = $("#address").text();
var r;
function encodeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[0].geometry.location
r = results[0].geometry.location
console.log("inside:" + r);
} else {
alert("Google Maps had some trouble finding" + address + status);
}
});
}
encodeAddress()
console.log("outside:" + r);
});
I am trying to return the geocoded address for use with Street View as well as Gmap. Inside returns the correct value and the outside returns underfined.
All help is greatly appreciated, I did read somewhere else that it is not possible to return the value this way but had to check with the trusty StackOverflow community.
Thank you in advance.
回答1:
You can do it this way, and call the outputGeo function within the Geocode's callback function. Basically, you are accessing r before the Geocode callback and thus r is still undefined:
$(function() {
var address = $("address").text();
var r;
function encodeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[0].geometry.location;
r = results[0].geometry.location;
outputGeo(r);
} else {
alert("Google Maps had some trouble finding" + address + status);
}
});
}
encodeAddress();
function outputGeo(result){
console.log("outside:" + result);
}
});
Here is an explanation of how Geocoding service works.
Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.
来源:https://stackoverflow.com/questions/5517120/return-address-from-google-maps-geocoder-v3