【发布时间】:2017-05-31 01:31:05
【问题描述】:
我已经实现了方向 API,以使用浏览器/JavaScript 中的 Google Maps V3 方向 API 找出从源到目的地的路线。
现在我只想在路线部分显示如下快照(来自谷歌地图的快照)所示的交通状况。
有没有办法针对不同级别的交通状况使用不同的折线描边颜色?
如果无法使用方向 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'
}
}
}
我希望这可以帮助您理解我的问题。让我知道是否需要其他任何内容来理解我的问题。
【问题讨论】:
标签: javascript google-maps google-maps-api-3