Google Maps API v3 - 具有可拖动备用路线的路线

时间:2017-02-02 10:32:20

标签: javascript google-maps google-maps-api-3 google-maps-markers

我已经成功实施了谷歌地图方向服务api:https://developers.google.com/maps/documentation/javascript/directions,其中包括' draggble'选项已启用。如果两个地点之间有多条路线,是否可以一起显示所有路线?

当前代码类似于:https://developers.google.com/maps/documentation/javascript/examples/directions-draggable,我在响应代码中有可用的替代路由,因为我已启用provideRouteAlternatives: true

我尝试了How to display alternative route using google map api中提供的解决方案。但是当我使用该代码时,我发现它使用独立标记绘制多个路径。也就是说,如果有4条路线可用,那么将有4条路线可供选择。地点和4' B'位置和拖动时 - 只选择其中一个。请查看以下截图。

初始视图:

Initial View

拖动初始位置(重复位置问题)

After dragging initial locations

我需要拖动这样一种方式,当拖动位置A或B时,不应该有任何重复,并且应该自动显示备用路线。

我目前的代码如下(此处未添加API密钥):

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Draggable directions</title>
    <style>
      #right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        float: left;
        width: 63%;
        height: 100%;
      }
      #right-panel {
        float: right;
        width: 34%;
        height: 100%;
      }
      .panel {
        height: 100%;
        overflow: auto;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <div id="right-panel">
      <p>Total Distance: <span id="total"></span></p>
    </div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: {lat: -24.345, lng: 134.46}  // Australia.
        });

        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer({
          draggable: true,
          map: map,
          panel: document.getElementById('right-panel')
        });

        directionsDisplay.addListener('directions_changed', function() {
          computeTotalDistance(directionsDisplay.getDirections());
        });

        displayRoute('Rosedale, MD, USA', 'Savage, MD, USA', directionsService,
            directionsDisplay);
      }

      function displayRoute(origin, destination, service, display) {
        service.route({
          origin: origin,
          destination: destination,
          travelMode: 'DRIVING',
          avoidTolls: true,
          provideRouteAlternatives: true,
        }, function(response, status) {
          if (status === 'OK') {
            for (var i = 0, len = response.routes.length; i < len; i++) {
                new google.maps.DirectionsRenderer({
                    map: map,
                    directions: response,
                    routeIndex: i,
                    draggable : true,
                });
            }
            display.setDirections(response);
          } else {
            alert('Could not display directions due to: ' + status);
          }
        });
      }

      function computeTotalDistance(result) {
        var total = 0;
        var myroute = result.routes[0];
        for (var i = 0; i < myroute.legs.length; i++) {
          total += myroute.legs[i].distance.value;
        }
        total = total / 1000;
        document.getElementById('total').innerHTML = total + ' km';
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API-KEY&callback=initMap">
    </script>
  </body>
</html>

请帮帮我。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您绘制的每条路线都是可编辑的,并且有一个开始和结束标记,这意味着您将始终拖动其中一条路线标记,而不是一次拖动。您可以使用suppressMarkers选项从备用路由中删除标记,但这不会改变行为。

问题在于,由于每条路线都是独立的,如果您移动起点或终点位置,则应重新绘制每条路线,否则只会更新一条路线。

也就是说,如果您编辑路线(除了通过更改其开始或结束位置),您不应该重绘您的路线。如果您更新开始或结束位置,您当然会丢失您添加的任何路线航点。除非你对此做些什么......这听起来很痛苦。

var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {

  var center = new google.maps.LatLng(0, 0);
  var myOptions = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: center
  }

  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

  var start = "Sadulpur, India";
  var end = "New Delhi, India";

  plotDirections(start, end);
}

function plotDirections(start, end) {

  var method = 'DRIVING';

  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode[method],
    provideRouteAlternatives: true
  };

  directionsService.route(request, function(response, status) {

    if (status == google.maps.DirectionsStatus.OK) {

      var routes = response.routes;
      var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];
      var directionsDisplays = [];

      // Reset the start and end variables to the actual coordinates
      start = response.routes[0].legs[0].start_location;
      end = response.routes[0].legs[0].end_location;

      // Loop through each route
      for (var i = 0; i < routes.length; i++) {

        var directionsDisplay = new google.maps.DirectionsRenderer({
          map: map,
          directions: response,
          routeIndex: i,
          draggable: true,
          polylineOptions: {

            strokeColor: colors[i],
            strokeWeight: 4,
            strokeOpacity: .3
          }
        });

        // Push the current renderer to an array
        directionsDisplays.push(directionsDisplay);

        // Listen for the directions_changed event for each route
        google.maps.event.addListener(directionsDisplay, 'directions_changed', (function(directionsDisplay, i) {

          return function() {

            var directions = directionsDisplay.getDirections();
            var new_start = directions.routes[0].legs[0].start_location;
            var new_end = directions.routes[0].legs[0].end_location;

            if ((new_start.toString() !== start.toString()) || (new_end.toString() !== end.toString())) {

              // Remove every route from map
              for (var j = 0; j < directionsDisplays.length; j++) {

                directionsDisplays[j].setMap(null);
              }

              // Redraw routes with new start/end coordinates
              plotDirections(new_start, new_end);
            }
          }
        })(directionsDisplay, i)); // End listener
      } // End route loop
    }
  });
}

initialize();
#map-canvas {
  height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

JSFiddle demo