简体   繁体   English

使用谷歌地图 API 渲染到地图上时无法获得替代路线

[英]Unable to get Alternatives Routes while using google maps API to render onto the map

I'm developing a project for my college and I'm stuck while trying to get route alternatives.我正在为我的大学开发一个项目,但在尝试获取替代路线时遇到了困难。 The drawMainRoute function plots a route from a given source and destination without a problem, but I want the directions service to give me alternate routes as well. drawMainRoute 函数可以毫无问题地绘制来自给定源和目的地的路线,但我希望路线服务也为我提供备用路线。

According to the Google maps API, it said, if I set provideRouteAlternatives to true then that should allow me to get all the routes from a source to destination.根据谷歌地图 API,它说,如果我将 provideRouteAlternatives 设置为 true,那么这应该允许我获取从源到目的地的所有路线。

Here's the link to the same [ https://developers.google.com/maps/documentation/javascript/reference/3.exp/directions#DirectionsRequest.provideRouteAlternatives]这是相同 [ https://developers.google.com/maps/documentation/javascript/reference/3.exp/directions#DirectionsRequest.provideRouteAlternatives]的链接

I also tried changing it to just "alternatives: true" in the JS file, but when I did that, it never plotted a route.我还尝试在 JS 文件中将其更改为“alternatives: true”,但是当我这样做时,它从未绘制过路线。 And found an exception on the console.并在控制台上发现异常。

Here's my JS code for reference.这是我的 JS 代码以供参考。

 function drawHeatMap() { heatmap = new google.maps.visualization.HeatmapLayer({ data: getPoints(), map: map, radius: 15 }); } function drawMainRoute() { //disableMap(); drawHeatMap(); var dirRenderer = new google.maps.DirectionsRenderer({ suppressMarkers: true }); var request = { origin: setStart(), destination: setEnd(), provideRouteAlternatives: true, travelMode: google.maps.TravelMode.DRIVING }; dirService.route(request, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { dirRenderer.setDirections(result); } }); dirRenderer.setMap(map); }

Found a way to do this.找到了一种方法来做到这一点。 We have to iterate over the routes found and use the DirectionsRenderer to set the directions individually.我们必须遍历找到的路线并使用 DirectionsRenderer 单独设置方向。

Here's the code for the same.这是相同的代码。

 function drawMainRoute() { //disableMap(); drawHeatMap(); var dirRenderer = new google.maps.DirectionsRenderer({ suppressMarkers: true }); dirService.route({ origin: setStart(), //yaha start kuch bhi daal sakte, direct string. lat lng ya google.map.place object destination: setEnd(), //yaha stop provideRouteAlternatives: true, travelMode: 'DRIVING' }, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { for (var i = 0; i < response.routes.length; i++) { var dr = new google.maps.DirectionsRenderer(); dr.setDirections(response); // Tell the DirectionsRenderer which route to display dr.setRouteIndex(i); dr.setMap(map); } } }); dirRenderer.setMap(map); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM