Google Maps API的困难

时间:2019-01-24 18:38:52

标签: javascript google-maps-api-3

我正在尝试创建一个简单的程序,该程序专门接收两个专门放置的目的地,并显示它们之间的方向。无论出于什么原因,我都无法获得显示的指示。

<script>
  var directionsService = new google.maps.directionsService();
  var directionsDisplay = new google.maps.directionsRenderer();

  var new_york = {lat: 40.7128, lng: -74.0060};
  var los_angeles = {lat: 34.0522, lng: -118.2437};

  function initMap() {
    var mapMarkers = [];
    var map = new google.maps.Map(
        document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
    );
    var marker1 = new google.maps.Marker({
      position: new_york, 
      map: map, 
      title: 'Home'
    });
    var marker2 = new google.maps.Marker({
      position: los_angeles, 
      map: map, 
      title: 'School'
    });
  }
  calculateAndDisplayRoute: function(directionsService, directionsDisplay, new_york, los_angeles) {
  directionsService.route({
    origin: new_york,
    destination: los_angeles,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
    directionsDisplay.setDirections(response);
    } else {
    alert('Directions request failed due to ' + status);
    }
  });
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDmA98U4We-2IAaHbxa354v_C91IktiSKM3&callback=calculateAndDisplayRoute"></script>

1 个答案:

答案 0 :(得分:0)

我认为您的代码存在一些问题,首先您需要了解,必须先加载google maps库,然后才能创建DirectionsServiceDirectionsRenderer的新实例,应该在CamelCase中:

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

由于您不是异步加载地图库,因此可以将脚本放置在页面顶部,并删除回调参数。我对您的代码进行了一些更改,请在下面进行检查(您需要添加api密钥):

var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};

function initMap() {
  var mapMarkers = [];

  var map = new google.maps.Map(
    document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
  );

  var marker1 = new google.maps.Marker({
    position: new_york, 
    map: map, 
    title: 'Home'
  });

  var marker2 = new google.maps.Marker({
    position: los_angeles, 
    map: map, 
    title: 'School'
  });
}
      
function calculateAndDisplayRoute() { 
  initMap();

  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();

  var route = {
    origin: new_york,
    destination: los_angeles,
    travelMode: 'DRIVING'
  };

  directionsService.route(route, function(response, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(response);
    } else {
      alert('Directions request failed due to ' + status);
    }
  });
}

calculateAndDisplayRoute();
<script src="https://maps.googleapis.com/maps/api/js?key=???"></script>
<div id="map" style="width: 100%; height: 500px;"></div>