我已经在浏览器/ JavaScript中使用Google Maps V3指向API实现了方向API,以找出从源到目的地的路线。
现在我想在路线部分显示下面的快照(来自谷歌地图的快照)中显示的交通情况。
对于不同的交通状况,是否有办法使用不同的折线strokeColor?
如果无法使用方向API或流量层,我是否可以使用方向矩阵或道路API的高级版本来实现此目的?
以下是我到目前为止所做的事情以及相应的输出:
var map;
var directionsService;
var polyline;
var directionsDisplay;
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions:{
strokeOpacity:1,
strokeWeight:5,
strokeColor: 'green'
},
draggable: true
});
directionsService = new google.maps.DirectionsService;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: 37.77, lng: -122.447}
});
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
directionsDisplay.addListener('directions_changed', function() {
DistanceOut(directionsDisplay.getDirections());
});
polyline = new google.maps.Polyline({
map:map
});
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: 'Whitefield, Bangalore',
destination: 'Indira nagar, Bangalore',
provideRouteAlternatives: true,
travelMode: 'DRIVING',
drivingOptions: {
departureTime: new Date(Date.now()),
trafficModel: 'bestguess'
},
unitSystem: google.maps.UnitSystem.METRIC
}, function(response, status) { console.log(response);
if (status == 'OK') {
directionsDisplay.setDirections(response);
DistanceOut(response);
changeStepColor(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function DistanceOut(response){
document.getElementById("travelDetail").innerHTML = "Distance:"+response.routes[0].legs[0].distance.text+
"<br> Duration::"+response.routes[0].legs[0].duration.text+
"<br> Duration in traffic::"+response.routes[0].legs[0].duration_in_traffic.text;
}
// Here I want to change the polyline color according to the traffic condition.
// Can I? Or if any other way to do so?!
function changeStepColor(res){
var steps = res.routes[0].legs[0].steps;
for(i=0; i<steps.length; i++){
if((steps[i].distance.value/steps[i].duration_in_traffic.value) > 5) {
//steps[i].polyline.strokeColor='blue';
//directionsDisplay.setOptions({polylineOptions: {path: steps[i].path ,strokeColor: 'red'}});
} else {
//directionsDisplay.setOptions({polylineOptions: {path: steps[i].path ,strokeColor: 'yellow'}});
//steps[i].polyline.strokeColor='red'
}
}
}
我希望这可以帮助您理解我的问题。如果需要了解我的问题,请告诉我。
答案 0 :(得分:6)
目前,无法仅使用Google Maps JavaScript API路线服务显示路线的流量。您可以通过交通图层显示整个城市的流量,但不能显示单个街道的流量。
高级计划许可无关紧要,您将获得相同的路线输出。 Roads API和Distance Matrix API等其他API不会在响应中提供任何与流量相关的信息。
功能请求已在Google问题跟踪器中提交:
https://issuetracker.google.com/issues/36537583
随意添加功能请求,以添加您的投票并订阅来自Google的通知。
<强>已更新强>
看起来Embed API显示路线的交通信息。尝试在directions mode中使用Embed API。这会给你类似的东西
答案 1 :(得分:2)
如果我正确理解您的问题,您希望向已构建的路线提供实时路况数据。首先,为此,您需要一个Google Maps Premium Plan客户端ID。为了向路线显示交通信息,您需要实施Directions Request。以前您可以使用durationInTraffic
,但此后已被弃用。您现在必须使用drivingOptions
,然后可以将其应用于自定义折线。
答案 2 :(得分:0)
import Polyline from '@mapbox/polyline';
const origin = `${currentPosition.latitude}, ${currentPosition.longitude}`;
const destination = `${User.latitude}, ${User.longitude}`;
try {
const waypoints = this.outletCoordinates.map(waypoint =>
`${waypoint.latitude},${waypoint.longitude}`).join('|');
const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&waypoints=optimize:true|${waypoints}&key=${Config.GOOGLE_MAPS_API_KEY}&mode=DRIVING`;
const mapUrl = await fetch(url);
const respJson = await mapUrl.json();
const routes = _.get(respJson, 'routes', []);
if (routes.length > 0 && routes[0]) {
const routeDescrip = routes[0];
const [summaryLeg] = routeDescrip.legs || [];
const points = Polyline.decode(routeDescrip.overview_polyline.points);
const optimizedRoutes = points.map(point => ({
latitude: point[0],
longitude: point[1],
}));
}
}