【问题标题】:Why is a globally set JS variable showing as undefined while using Google Maps API?为什么在使用 Google Maps API 时全局设置的 JS 变量显示为未定义?
【发布时间】:2018-08-05 12:52:11
【问题描述】:

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

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

当我检查时,控制台显示“纬度”未在此处定义:

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

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

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

【问题讨论】:

  • 你没有声明变量经纬度
  • 您说latitude 是一个全局变量,但根据您发布的代码,它不是全局变量。

标签: javascript jquery google-maps-api-3 google-maps-markers


【解决方案1】:

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

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

解决它的最简单方法是在 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

代码 sn-p:

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>

【讨论】:

    【解决方案2】:

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

    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 放在你的函数里面,这个变量就会有一个函数作用域,这意味着它只能在函数里面使用。

    【讨论】:

    • 谢谢。快速跟进。即使我在上面声明了它,我也无法在另一个函数中使用纬度或经度。换句话说,我输入了“console.log(latitude);”在“如果”部分,它显示一个正确的数字,但如果我移动“console.log(纬度);”在 $.getJSON 函数之外,它显示为未定义。既然我在主函数之外声明了它,不应该在任何地方定义它吗?
    • 它应该在任何地方声明。你能设置一个小提琴吗?
    • 我在这里设置了一个:jsfiddle.net/v1nt9r65/3,但我很困惑如何将这部分合并到小提琴&lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD98yPUHrWE8QZkSxWR1Fno3_yd70cPQbA&amp;callback=initMap"&gt; &lt;/script&gt; 中。我将其添加为外部资源 URL,但不认为这是正确的
    猜你喜欢
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多