Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

javascript - Uncaught referenceError google is not defined

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

Uncaught ReferenceError: google is not defined

I have moved the API script to the top, fail. I adjusted my own code to match Google's documentation, fail. Is it Chrome that is causing my problem?

<!DOCTYPE html>
<html>
<head>
    <title>weather map</title>
    <style type="text/css">
    html, body {
        margin: 0;
    }
    #map-canvas {
        width: 100%;
        height: 100%;
    }
    </style>
</head>
<body>
    <div id="container">
        <h1>Map Test</h1>
        <div id="map-canvas">
        </div>
    </div>

    <script type="text/javascript" src="/js/jquery-2.1.4.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            google.maps.event.addDomListener(window, 'load', initMap);
        });

        var map; 
        function initMap() {        
            map = new google.maps.Map(document.getElementById("map-    canvas"), {
                center: {lat: 29.423017, lng: -98.48527},
                zoom: 8,
            });
        }
    </script>
    <script async defer 
        src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_WAS_HERE_&callback=initMap">
    </script>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...