【发布时间】:2020-06-23 16:28:11
【问题描述】:
function placeDistanceMarkers(
coordinates,
in_between_distance,
unit,
departure_time
) {
if (coordinates.length < 2) {
throw new Error("Invalid length of marker coordinates");
}
// the elements are the functions to be called with lat() and lng()
let start_coord = coordinates[0],
end_coord = coordinates[coordinates.length - 1];
let distances = [];
distances.push(0); // init
let marker_index = 0;
// start marker
addMarker(
new google.maps.LatLng(start_coord.lat(), start_coord.lng()),
{ lat: start_coord.lat(), lng: start_coord.lng() },
++marker_index,
departure_time
);
//end marker
addMarker(
new google.maps.LatLng(end_coord.lat(), end_coord.lng()),
{ lat: end_coord.lat(), lng: end_coord.lng() },
++marker_index,
departure_time
);
// calculate distances with the starting coord coordinates[0]
for (let i = 1; i < coordinates.length; i++) {
let d = distance(
{ lat: start_coord.lat(), lng: start_coord.lng() },
{ lat: coordinates[i].lat(), lng: coordinates[i].lng() },
"miles"
);
distances.push(d);
}
let start_distance = 0;
for (let i = 0; i < coordinates.length; i++) {
if (distances[i] - start_distance >= 20) {
start_distance = distances[i];
addMarker(
new google.maps.LatLng(coordinates[i].lat(), coordinates[i].lng()),
{ lat: coordinates[i].lat(), lng: coordinates[i].lng() },
++marker_index,
departure_time
);
}
}
}
function displayRoute2(start, end, departure_time) {
directionsService = new google.maps.DirectionsService();
var request = {
origin: start,
destination: end,
travelMode: "DRIVING",
provideRouteAlternatives: true,
};
directionsService.route(request, function (result, status) {
if (status == "OK") {
console.log(result);
try {
//the directions result which contains multiple routes
directionsResult = result;
let n = directionsResult.routes.length;
//by default , the map displays the first result directions
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setDirections(result);
directionsDisplay.setMap(map);
// place markers
for (let i = 0; i < n; i++) {
placeDistanceMarkers(
[
result.routes[0].legs[0].start_location,
...result["routes"][i]["overview_path"],
result.routes[0].legs[0].end_location,
],
20,
"miles",
departure_time
);
}
fillRouteOptions();
} catch (e) {
console.log(e.toString());
}
}
});
}
我使用上面的两个函数来创建下面的地图。 现在它只显示路线 0 的蓝线,我希望所有路线都有蓝线。 我正在尝试使用方向Display.setRouteIndex(i);在 for 循环中,但这只会显示最后一条路线的蓝线。感谢您的帮助!
【问题讨论】:
标签: google-maps google-maps-api-3