为什么全局设置的 JS 变量在使用 Google 地图 API 时显示为未定义?

Why is a globally set JS variable showing as undefined while using Google Maps API?

我正在尝试使用 Google 地图 API 地理编码。完整的代码在下面,我第一次尝试时它起作用了,但现在它没有显示地图,我不明白为什么。

我什至尝试添加 "alert(data.status);",它返回 "OK" 的状态。

当我检查时,控制台显示 "latitude" 未在此处定义:

 var myLatLng = {lat: latitude, lng: longitude};

加载 DOM 时设置的变量 "latitude" 不应该延续到上面那一行,还是我对变量范围做错了什么?

  <style>
        #map {
        height:200px;
        width: 200px;
        }
    </style>
    <script>
        $(function() {
            var jsonLatLng ='https://maps.googleapis.com/maps/api/geocode/json?address=Indianapolis&sensor=false';
            $.getJSON(jsonLatLng, function (data) {
                if (data.status="OK") {
                latitude = data.results[0].geometry.location.lat;
                longitude = data.results[0].geometry.location.lng;
                } else { //A default lat/long so SOMETHING shows
                latitude = 38.99;
                longitude = -74.80;
                }
            });
        });
    </script>

然后是这个:

<div id="map"></div>
    <script>
      function initMap() {
        var myLatLng = {lat: latitude, lng: longitude};

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: myLatLng
        });

        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: ''
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD98yPUHrWE8QZkSxWR1Fno3_yd70cPQbA&callback=initMap">
    </script>

您没有在代码中的任何地方声明变量经度和纬度。所以你可以这样做:

var longitude, latitude;
$(function() {
  var jsonLatLng ='https://maps.googleapis.com/maps/api/geocode/json?address=Indianapolis&sensor=false';
  $.getJSON(jsonLatLng, function (data) {
      if (data.status="OK") {
      latitude = data.results[0].geometry.location.lat;
      longitude = data.results[0].geometry.location.lng;
      } else { //A default lat/long so SOMETHING shows
      latitude = 38.99;
      longitude = -74.80;
      }
  });
});

此外,如果将 var 放入函数中,变量将具有函数作用域,这意味着它只能在函数内部使用。

您在两个异步函数之间存在竞争条件:

  1. ajax 地理编码器调用
  2. Google Maps Javascript API v3 (async defer &callback=initMap)
  3. 的异步加载

解决它的最简单方法是在 initMap 函数中调用地理编码器(在 API 加载后)。

function initMap() {
  var jsonLatLng = 'https://maps.googleapis.com/maps/api/geocode/json?address=Indianapolis';
  $.getJSON(jsonLatLng, function(data) {
    if (data.status == "OK") { // <======= fixed typo on this line
      latitude = data.results[0].geometry.location.lat;
      longitude = data.results[0].geometry.location.lng;
    } else { //A default lat/long so SOMETHING shows
      latitude = 38.99;
      longitude = -74.80;
    }
    var myLatLng = {
      lat: latitude,
      lng: longitude
    };

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: ''
    });
  });
}

proof of concept fiddle

代码片段:

function initMap() {
  var jsonLatLng = 'https://maps.googleapis.com/maps/api/geocode/json?address=Indianapolis';
  $.getJSON(jsonLatLng, function(data) {
    if (data.status == "OK") {
      latitude = data.results[0].geometry.location.lat;
      longitude = data.results[0].geometry.location.lng;
    } else { //A default lat/long so SOMETHING shows
      latitude = 38.99;
      longitude = -74.80;
    }
    var myLatLng = {
      lat: latitude,
      lng: longitude
    };

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: ''
    });
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='map'></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry&callback=initMap"></script>