谷歌地图API -谷歌没有定义,异步加载的API

Google maps API - google is not defined, asynchronous load of API

本文关键字:API 异步 定义 加载 谷歌 谷歌地图      更新时间:2023-09-26

我正在尝试使用多个路点的谷歌地图API制作路线。

当我运行该页时,会引发以下错误:

Uncaught ReferenceError: google is not defined(anonymous function) @ test.html:25 Uncaught TypeError: Cannot read property 'route' of undefined test.html:91

<!DOCTYPE html>
    <html>
          <head>
            <style type="text/css">
              html, body { height: 100%; margin: 0; padding: 0; }
              #map { height: 100%; }
            </style>
          </head>
          <body>
            <div id="map"></div>
            <script>
             function loadScript()
             {
             var myKey = "****************-**************-*******";
             var script = document.createElement("script");
             script.type = "text/javascript";
             script.src = "http://maps.googleapis.com/maps/api/js?key="+myKey+"&sensor=false&callback=initialize";
             document.body.appendChild(script);
             }
             window.onload = loadScript;
           </script>
            <script type="text/javascript">
            var directionDisplay;
            var directionsService = new google.maps.DirectionsService();
            var map;
            function initialize() {
                directionsDisplay = new google.maps.DirectionsRenderer({
                    suppressMarkers: true
                });
                var myOptions = {
                    zoom: 3,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                }
                map = new google.maps.Map(document.getElementById("map"), myOptions);
                directionsDisplay.setMap(map);
                calcRoute();
            }
            function calcRoute() {
                var waypts = [];
                stop = new google.maps.LatLng(51.943571, 6.463856)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                stop = new google.maps.LatLng(51.945032, 6.465776)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                stop = new google.maps.LatLng(51.945538, 6.469413)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                stop = new google.maps.LatLng(51.947462, 6.467941)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                stop = new google.maps.LatLng(51.945409, 6.465562)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                stop = new google.maps.LatLng(51.943700, 6.462096)
                waypts.push({
                    location: stop,
                    stopover: true
                });
                start = new google.maps.LatLng(51.943382, 6.463116);
                end = new google.maps.LatLng(51.943382, 6.463116);
                createMarker(start);
                var request = {
                    origin: start,
                    destination: end,
                    waypoints: waypts,
                    optimizeWaypoints: true,
                    travelMode: google.maps.DirectionsTravelMode.WALKING
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        var route = response.routes[0];
                    }
                });
            }
            function createMarker(latlng) {
                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map
                });
            }
            initialize();
            </script>
          </body>
        </html>
  1. 你正在异步加载API,只有当你知道你在做什么时才应该这样做。所有依赖于API的代码都需要在回调函数中(在你的例子中是initialize)。
  2. 你不应该在加载API之前调用initialize函数。
工作小提琴

代码片段:

// global variables
var directionDisplay;
var directionsService;
var map;
function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?callback=initialize";
  document.body.appendChild(script);
}
window.onload = loadScript;
function initialize() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });
  var myOptions = {
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }
  map = new google.maps.Map(document.getElementById("map"), myOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}
function calcRoute() {
  var waypts = [];
  stop = new google.maps.LatLng(51.943571, 6.463856)
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945032, 6.465776)
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945538, 6.469413)
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.947462, 6.467941)
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945409, 6.465562)
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.943700, 6.462096)
  waypts.push({
    location: stop,
    stopover: true
  });
  start = new google.maps.LatLng(51.943382, 6.463116);
  end = new google.maps.LatLng(51.943382, 6.463116);
  createMarker(start);
  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
    }
  });
}
function createMarker(latlng) {
  var marker = new google.maps.Marker({
    position: latlng,
    map: map
  });
}
// initialize();
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<div id="map"></div>

我刚刚为下面的脚本更改了导入Google Maps API的脚本:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="https://raw.github.com/HPNeo/gmaps/master/gmaps.js"></script>