网站集成Google Maps Directions:如何获取含实时路况的预估行驶时间
在Google Maps Directions中获取考虑交通路况的预估行驶时间
嘿,我来帮你搞定这个问题!你当前的代码获取的是常规无路况参考的预估行驶时间,要拿到结合实时/历史交通状况的时间,只需要对请求参数和结果读取字段做两处关键调整就行:
关键修改点
- 添加
departureTime参数:告诉API基于哪个时间点的路况计算时间——传new Date()就是用实时路况,传具体时间戳则会用该时间的历史/预测路况数据。 - 改用
duration_in_traffic字段:原来的duration是理想路况下的时间,考虑交通的预估时间存在duration_in_traffic属性里。
修改后的完整代码
function direction(){ var directionsService = new google.maps.DirectionsService(); var directionsRenderer = new google.maps.DirectionsRenderer(); var nmap = new google.maps.Map(document.getElementById('direction-map'), mapOptions); directionsRenderer.setMap(nmap); calcRoute(); } function calcRoute() { var blng = parseFloat($("#beginning-lng").val()); var blat = parseFloat($("#beginning-lat").val()); var dlng = parseFloat($("#destination-lng").val()); var dlat = parseFloat($("#destination-lat").val()); var start = new google.maps.LatLng(blat, blng); var end = new google.maps.LatLng(dlat, dlng); var request = { origin: start, destination: end, travelMode: 'DRIVING', avoidTolls: true, // 新增:指定出发时间,这里用当前时间获取实时路况 departureTime: new Date() }; directionsService.route(request, function (result, status) { if (status == 'OK') { directionsRenderer.setDirections(result); console.log(result); var distance = result.routes[0].legs[0].distance.value / 1000; // 替换成考虑交通的时间字段 var timeInTraffic = result.routes[0].legs[0].duration_in_traffic.value / 60; console.log("考虑交通的预估行驶时间(分钟):", timeInTraffic); } }); }
额外注意事项
- 确保你的Google Cloud项目已经启用了Maps JavaScript API,并且所用的API密钥拥有正确的调用权限。
departureTime支持两种格式:Date对象(用于实时路况计算),或者Unix时间戳(比如Date.now() + 3600000表示1小时后的路况预测)。- 如果不传入
departureTime,API不会返回duration_in_traffic字段,所以这个参数是获取路况时间的必要条件。
内容的提问来源于stack exchange,提问作者user16829612
相关产品推荐
相关产品推荐

