在地图谷歌上显示到同一目的地的多条路线,是否可能?

时间:2016-12-27 09:52:51

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

我正在尝试将多条路线发送到同一目的地,所以我试图循环这个函数,params的值不同* startLatLong

    AnimatingView animatingView = new AnimatingView(getContext());
    parentLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                animatingView.animate().x(animatingView.offsetX).setDuration(500).start();
            }
         });

但是,结果只显示了最后一个循环值。

有人可以解释,是否有可能在同一目的地创建多条路线?

1 个答案:

答案 0 :(得分:3)

如果您想同时显示多个路线,则每个路线都需要一个单独的DirectionsRenderer对象:

function displayRoute(startLatLong) {
  var start = startLatLong;
  var end = '-6.2451528, 106.7923695'; 
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  $scope.directionsService.route(request, function(response, status) {
     if (status == google.maps.DirectionsStatus.OK) {
       var directionsDisplay = new google.maps.DirectionsRenderer({map:map, preserveViewport: true});
       directionsDisplay.setDirections(response);
     } else alert("directions request failed: status:"+status)
  });
}

proof of concept fiddle

代码段

var geocoder;
var map;
var $scope = {};

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(-6.174465, 106.822745),
      zoom: 11,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  $scope.directionsService = new google.maps.DirectionsService();
  displayRoute(map.getCenter());
  displayRoute({
    lat: -6.225014,
    lng: 106.900447
  });
  displayRoute({
    lat: -6.202394,
    lng: 106.65271
  });

}
google.maps.event.addDomListener(window, "load", initialize);

function displayRoute(startLatLong) {
  var start = startLatLong;
  var end = '-6.2451528, 106.7923695';
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  $scope.directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      var directionsDisplay = new google.maps.DirectionsRenderer({
        map: map,
        preserveViewport: true
      });
      directionsDisplay.setDirections(response);
    } else alert("directions request failed: status:" + status)
  });
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>