0

我试图编译谷歌的示例代码并找出总距离,我相信脚本没有错..如果是的话。谷歌地图不会显示...有一些东西丢失了..任何人都可以请帮助..

    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
      var directionDisplay;
      var directionsService = new google.maps.DirectionsService();

      function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var mapOptions = {
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: new google.maps.LatLng(41.850033, -87.6500523)
        };
        var map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions-panel'));

        var control = document.getElementById('control');
        control.style.display = 'block';
        map.controls[google.maps.ControlPosition.TOP].push(control);
      }

      function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var request = {
          origin: start,
          destination: end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          }
        });
      }
      function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000.
      document.getElementById("total").innerHTML = total + " km";
      }


      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="control">
      <strong>Start:</strong>
      <select id="start" onchange="calcRoute();">
       <option value="san bernardino, ca">San Bernardino</option>
        <option value="los angeles, ca">Los Angeles</option>
      </select>
      <strong>End:</strong>
      <select id="end" onchange="calcRoute();">
        <option value="san bernardino, ca">San Bernardino</option>
        <option value="los angeles, ca">Los Angeles</option>
      </select>

    </div>
    <div id="total"></div>
    <div id="directions-panel"></div>
    <div id="map_canvas"></div>
  </body>
4

2 回答 2

0

尝试

computeTotalDistance(response)

代替

computeTotalDistance(result)`
于 2012-09-24T20:32:38.343 回答
0

你永远不会调用你的 computeTotalDistance 函数。您需要在 DirectionsService.route 回调函数中调用它。

     directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        computeTotalDistance(response);
      }

工作示例

于 2012-09-24T20:45:38.207 回答