更改航点之间的颜色并使路线适合移动的地图标记

时间:2018-01-11 07:20:55

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

我使用google maps api在嵌入式谷歌地图中绘制路线。我改变了航线的颜色,但我也想改变航点之间的颜色,例如:

开始 - 输入 - > firstWP --red--> secondWP --orange - > firstWP --red - > secondWp --orange - >目标

firstWP与seceondWP之间的颜色应该改变,但是第二个WP到FirstWP的颜色应该与路线的其他部分颜色相同。

此外,我还需要移动地图标记,并且路线应该移动/更改 适合地图标记的新位置,但保持不同的颜色。

这是一个带有可拖动地图标记并在航点之间更改颜色的最小示例,但路线不适应地图标记的新位置



var map;
var directionsService;
var directionsDisplay;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    suppressPolylines: true
  });


  calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);

function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
  console.log("Entrée CALC ROUTE");

  var origin = new google.maps.LatLng(origin_lat, origin_lng);
  var destination = new google.maps.LatLng(destination_lat, destination_lng);
  var waypointsArray = document.getElementById('waypoints').value.split("|");

  var waypts = [];

  for (i = 0; i < waypointsArray.length; i++) {
    if (waypointsArray[i] != "") {
      var waypoint = waypointsArray[i];
      var waypointArray = waypoint.split(",");
      var waypointLat = waypointArray[0];
      var waypointLng = waypointArray[1];
      console.log("waypts lat " + waypointLat);
      console.log("waypts lng " + waypointLng);

      waypts.push({
        location: new google.maps.LatLng(waypointLat, waypointLng),
        stopover: true
      })
    }
  }
  console.log("waypts " + waypts.length);

  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: waypts,
    provideRouteAlternatives: true
  };
  console.log("Calc request " + JSON.stringify(request));

  directionsService.route(request, customDirectionsRenderer);
}

function customDirectionsRenderer(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
    var bounds = new google.maps.LatLngBounds();
    var route = response.routes[0];
    var path = response.routes[0].overview_path;
    var legs = response.routes[0].legs;
    for (i = 0; i < legs.length; i++) {
      var polyline = new google.maps.Polyline({map:map, strokeColor: "blue", path:[]})
      if (i == 1) {
        polyline.setOptions({strokeColor: "red"});
        }
      var steps = legs[i].steps;
      for (j = 0; j < steps.length; j++) {
        var nextSegment = steps[j].path;
        for (k = 0; k < nextSegment.length; k++) {
          polyline.getPath().push(nextSegment[k]);
          bounds.extend(nextSegment[k]);
        }
      }
    }

    polyline.setMap(map);
    map.fitBounds(bounds);
  }
};
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
&#13;
&#13;
&#13;

http://jsfiddle.net/westify/vop9o1n5/1/

有可能吗?或者只有在移动一个航点后重新渲染整条路线才有可能吗?

1 个答案:

答案 0 :(得分:2)

一种选择是在directions_changed上监听DirectionsRenderer事件,当它触发时,重绘方向折线。

var firstTime = true;
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
  console.log("directions changed firstTime=" + firstTime);
  // prevent infinite loop
  if (firstTime) {
    google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
      console.log("directions changed"); 
      customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
    });
  }
  firstTime = !firstTime;
});

proof of concept fiddle

代码段

var map;
var directionsService;
var directionsDisplay;
var firstTime = true;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    suppressPolylines: true
  });
  google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
    console.log("directions changed firstTime=" + firstTime);
    if (firstTime) {
      google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
        console.log("directions changed"); //+JSON.stringify(directionsDisplay.getDirections()));
        customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
      });
    }
    firstTime = !firstTime;
  });


  calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);

function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
  console.log("Entrée CALC ROUTE");

  var origin = new google.maps.LatLng(origin_lat, origin_lng);
  var destination = new google.maps.LatLng(destination_lat, destination_lng);
  var waypointsArray = document.getElementById('waypoints').value.split("|");

  var waypts = [];

  for (i = 0; i < waypointsArray.length; i++) {
    if (waypointsArray[i] != "") {
      var waypoint = waypointsArray[i];
      var waypointArray = waypoint.split(",");
      var waypointLat = waypointArray[0];
      var waypointLng = waypointArray[1];
      console.log("waypts lat " + waypointLat);
      console.log("waypts lng " + waypointLng);

      waypts.push({
        location: new google.maps.LatLng(waypointLat, waypointLng),
        stopover: true
      })
    }
  }
  console.log("waypts " + waypts.length);

  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: waypts,
    provideRouteAlternatives: true
  };
  console.log("Calc request " + JSON.stringify(request));

  directionsService.route(request, customDirectionsRenderer);
}
var polylines = [];

function customDirectionsRenderer(response, status) {
  for (var i = 0; i < polylines.length; i++) {
    polylines[i].setMap(null);
  }
  polylines = [];
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    var bounds = new google.maps.LatLngBounds();
    var route = response.routes[0];
    var path = response.routes[0].overview_path;
    var legs = response.routes[0].legs;
    for (i = 0; i < legs.length; i++) {
      var polyline = new google.maps.Polyline({
        map: map,
        strokeColor: "blue",
        path: []
      });
      polylines.push(polyline);
      if (i == 1) {
        polyline.setOptions({
          strokeColor: "red"
        });
      }
      var steps = legs[i].steps;
      for (j = 0; j < steps.length; j++) {
        var nextSegment = steps[j].path;
        for (k = 0; k < nextSegment.length; k++) {
          polyline.getPath().push(nextSegment[k]);
          bounds.extend(nextSegment[k]);
        }
      }
    }

    polyline.setMap(map);
    map.fitBounds(bounds);
  }
};
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>