Uncaught referenceError google is not defined

前端 未结 2 623
逝去的感伤
逝去的感伤 2020-12-12 03:34

Please help me debug why Chrome is not recognizing google. I get this error:

Uncaught ReferenceError: google is not defined

相关标签:
2条回答
  • 2020-12-12 03:43

    You are loading the Google Maps Javascript API asynchronously. You can't use any of its methods until the initMap (callback) function runs.

    working fiddle

    code snippet:

    var map;
    
    function initMap() {
      map = new google.maps.Map(document.getElementById("map-canvas"), {
        center: {
          lat: 29.423017,
          lng: -98.48527
        },
        zoom: 8
      });
    }
    html,
    body {
      margin: 0;
      width: 100%;
      height: 100%;
    }
    #map-canvas {
      width: 100%;
      height: 100%;
    }
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
    </script>
    <div id="container" style="height:100%; width:100%;">
      <h1>Map Test</h1>
      <div id="map-canvas"></div>
    </div>

    0 讨论(0)
  • 2020-12-12 03:46

    You shouldn't put your google maps event in $(document).ready(); since window.load already registers an event listener and that should be enough.

    Your google maps script tag should also be above your JavaScript code and the event listener should also be moved beneath the function.

    <script async defer 
        src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_WAS_HERE_&callback=initMap">
    </script>
    
    <script type="text/javascript">
        var map; 
        function initMap() {        
            map = new google.maps.Map(document.getElementById("map-    canvas"), {
                center: {lat: 29.423017, lng: -98.48527},
                zoom: 8,
                });
            }
    
        google.maps.event.addDomListener(window, 'load', initMap);
    </script>
    

    Next time you should read the documentation more thoroughly.

    0 讨论(0)
提交回复
热议问题