我正在使用谷歌地图API,每当我从codeLatLng函数返回变量到初始化函数时,它声称未定义.如果我从codeLatLng打印变量,它显示正常.
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var addr = codeLatLng();
document.write(addr);
}
function codeLatLng() {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
return results[1].formatted_address;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
打印出undefined
如果我做:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var …Run Code Online (Sandbox Code Playgroud)