You can't return a value from that function via the callback to the Google code. It makes no sense; the "geocode()" function is asynchronous. The outer function will have returned by the time that your callback runs.
The proper way to do this is to mimic the Google API itself: give your function a callback parameter, and perform your "afterwards" work from there:
function geocodeAddress(address, callback) {
var latlng = new Array(2);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng[0] = results[0].geometry.location.lat();
latlng[1] = results[0].geometry.location.lng();
callback(latlng); // call the callback function here
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
edit — as an example of how you'd use this:
geocodeAddress(search_location, function(search_latlng) {
console.log(search_latlng);
$.getJSON('/main/get_places', {search_location: search_latlng}, function(json){
$("#result_listing").html('');
// ...
});
});
It's like your original code, but instead of having the geocode result returned to your code, it's passed as the parameter to the callback function you provide.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…