【问题标题】:Google is not defined despite there already being an API keyed in尽管已经有一个 API 被键入,但 Google 没有被定义
【发布时间】:2019-02-09 12:58:50
【问题描述】:

我不知道为什么它一直说 google 没有定义。有谁知道这个问题吗?

我已经尝试将脚本移到头部,但这里仍然没有用。

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: new google.maps.LatLng(2.8,-187.3),
          mapTypeId: 'terrain'
        });
      }
      // Loop through the results array and place a marker for each
      // set of coordinates.
      function loop() {
        var lati=JSON.parse(localStorage.getItem("lat2"))
        console.log("Hi")
        console.log(lati)
        for (var i = 0; i < lati.length; i++) {
          var coords = lati[i]
          var latLng = {lat: (coords[0]), lng:(coords[1])};
          var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });
        }
      }
      loop()
    </script>
    <script async defer 
      src="https://maps.googleapis.com/maps/api/js?key=THEAPIKEY=initMap">
    </script>
  </body>
</html>

我希望它循环通过我在本地存储中的内容

【问题讨论】:

    标签: jquery html google-maps


    【解决方案1】:

    您正在异步加载 Google Maps Javascript API(使用async defer)。 API 在完成加载之前将不可用(google 将未定义)。届时它将运行您的回调函数 (initMap)。

    API 文档中的说明:

    loop 函数调用移动到initMap 中(或同步加载API)。

    proof of concept fiddle

    code sn-p:(注意不会读取 localStorage 由于沙盒)

    #map {
      height: 100%;
    }
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <script>
      var map;
    
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: new google.maps.LatLng(2.8, -187.3),
          mapTypeId: 'terrain'
        });
        loop()
      }
    
      // Loop through the results array and place a marker for each
      // set of coordinates.
      function loop() {
        var lati = JSON.parse(localStorage.getItem("lat2"))
        console.log("Hi")
        console.log(lati)
        for (var i = 0; i < lati.length; i++) {
          var coords = lati[i]
          var latLng = {
            lat: (coords[0]),
            lng: (coords[1])
          };
          var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });
        }
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
    </script>

    【讨论】:

      【解决方案2】:

      No.1) 您的浏览器不知道google 是什么,因为google 变量将在后面的脚本中定义。将您的&lt;script&gt;initMap 函数等放在一起。“google”脚本&lt;script async defer src="https://maps.googleapis.com/maps/api/js key=....&amp;callback=initMap"&gt; &lt;/script&gt; 之后。

      No.2) 在页面完全加载后运行代码可能会有所帮助。您可以使用document.addEventListener('DOMContentLoaded', function() { //your code here }) 或使用jQuery 之类的库来执行此操作。

      附:一般来说,要更加小心您的 API 密钥。不要发布它们

      【讨论】:

      • 我已添加到答案中。您基本上是在处理delayed execution of Google javascript,您自己的代码必须稍后运行。
      • 如果您使用callback=initMap,那么您(可能)不需要您在第 2 点中描述的内容)。如果密钥受到适当限制,则发布 API 密钥也不是问题。通过查看源代码,可以在任何使用 Google Maps API 的网站上找到它。这就是为什么您应该始终限制您的密钥。
      猜你喜欢
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2013-11-26
      • 2015-02-18
      • 1970-01-01
      • 2023-01-25
      相关资源
      最近更新 更多