Javascript 无法从方法内部为变量赋值
我正在使用谷歌地图JSAPI。我正试着在我的地图中心设置一个标记。我正在使用Javascript 无法从方法内部为变量赋值,javascript,google-maps,google-maps-markers,Javascript,Google Maps,Google Maps Markers,我正在使用谷歌地图JSAPI。我正试着在我的地图中心设置一个标记。我正在使用currLocation变量保存当前位置。currLocation变量在内联私有方法(第1节)中有值,但当我想设置标记(第2节)时,它是空的 Stackoverflow有很多“无法将值设置为全局变量”的解决方案,但我无法用它们的引用来解决我的问题 任何帮助都将不胜感激 function initMap() { var currLocation = null; var defaultCenter = {
currLocation
变量保存当前位置。currLocation
变量在内联私有方法(第1节)中有值,但当我想设置标记(第2节)时,它是空的
Stackoverflow有很多“无法将值设置为全局变量”的解决方案,但我无法用它们的引用来解决我的问题
任何帮助都将不胜感激
function initMap() {
var currLocation = null;
var defaultCenter = { lat: 34.397, lng: 150.644 };
//Set Map properties
var map = new google.maps.Map(document.getElementById('gmap'), {
scrollwheel: true,
zoom: 10
});
//Get Current Location - Section 1
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(currLocation);
});
}
else {
map.setCenter(defaultCenter);
}
//Put marker on the current location - Section 2
var marker = new google.maps.Marker({
position: currLocation,
map: map
});
}
问题在于你的控制流逻辑。如果第一个功能检测失败(即,
If(navigator.geolocation)
)(根据您的描述,听起来与此完全相同),则currLocation
的值将保持为空。如果不希望在没有currLocation
的情况下继续,则:
else
块引发异常,因为导航器没有地理位置null
您应该将标记函数放在getCurrentPosition的成功回调中。因为它是一个异步函数。在调用成功回调函数之前,currLocation将为null