Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法从方法内部为变量赋值_Javascript_Google Maps_Google Maps Markers - Fatal编程技术网

Javascript 无法从方法内部为变量赋值

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 = {

我正在使用谷歌地图JSAPI。我正试着在我的地图中心设置一个标记。我正在使用
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