我是StackOverflow的新手,所以,如果我犯了一个错误,请宽容我。
我有个问题。当我尝试从另一个函数访问变量时,结果为“ null”。
function initAutocomplete() {
var latitude = 0;
var longitude = 0;
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("geocode").value;
geocoder.geocode({ 'address': address },
function getCoordinates(results, status) {
//if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
}
//}
);
var uluru = {lat: latitude,
lng: longitude};
var map = new google.maps.Map
(document.getElementById('map'),
{
center: uluru,
zoom: 17,
mapTypeId: 'roadmap'
});
}
最佳答案
uluru
的纬度和经度已在地理编码回调函数中完全填充,这不一定会在加载函数时使它们可用,因此,当这些值可用时,您可以使用回调来设置地图中心。
function initAutocomplete() {
var latitude = 0;
var longitude = 0;
var uluru = {lat: latitude, lng: longitude };
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("geocode").value;
geocoder.geocode({'address':address}, function getCoordinates( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
map.setCenter( new google.maps.LatLng( latitude,longitude ) ;
}
});
var map = new google.maps.Map(document.getElementById('map'), {
center: uluru,
zoom: 17,
mapTypeId: 'roadmap'
});
}