Google maps 在谷歌地图API v3中找到最短最快路线的优雅方式?

Google maps 在谷歌地图API v3中找到最短最快路线的优雅方式?,google-maps,google-maps-api-3,Google Maps,Google Maps Api 3,我正在做一个计程车车费计算器。其中一个业务要求是,公司希望选择最短、最快的路线。我知道Google directionService默认搜索最快的路线。为了得到最短的路线,我将request参数中的“avoidhighways”选项设置为true,但我对结果不太满意 有人有比这更好的解决方案吗 Use optimizeWaypoints: true in Request perameter. See below code snippet var request ={

我正在做一个计程车车费计算器。其中一个业务要求是,公司希望选择最短、最快的路线。我知道Google directionService默认搜索最快的路线。为了得到最短的路线,我将request参数中的“avoidhighways”选项设置为true,但我对结果不太满意

有人有比这更好的解决方案吗

Use optimizeWaypoints: true in Request perameter. See below code snippet var request ={ origin: sStartLatLng, destination: sStartLatLng, waypoints: waypts, optimizeWaypoints: true, travelMode: google.maps.DirectionsTravelMode.DRIVING }; 在请求参数中使用optimizeWaypoints:true。请参阅下面的代码片段 var请求={ 产地:sStartLatLng, 目的地:sStartLatLng, 航路点:航路点, 航路点:对, travelMode:google.maps.Directions travelMode.DRIVING };
使用
alternations=true
选项集,可以获得三个选项。然后,您可以搜索返回的路线中最短和最快的路线。

要获得从A到B的最短路线,我建议使用“alternatives=true”参数进行不同的查询,在avoid=toll、avoid=highways之间使用“avoid”参数,然后我会比较所有的结果来选择最短的路线

 directionsService = new google.maps.DirectionsService;
//avoiding tolls
            directionsService.route({
                origin: {
                    'placeId': originId
                },
                destination: {
                    'placeId': destinationId
                },
                provideRouteAlternatives: true,
                avoidTolls: true,
                travelMode: google.maps.TravelMode.DRIVING
            }, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    routesResponses.push(response);
                }
                else {
                    window.alert('Directions request failed due to ' + status);
                }
            });
            //avoiding highways
            directionsService.route({
                origin: {
                    'placeId': originId
                },
                destination: {
                    'placeId': destinationId
                },
                provideRouteAlternatives: true,
                avoidHighways: true,
                travelMode: google.maps.TravelMode.DRIVING
            }, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    routesResponses.push(response);
                }
                else {
                    window.alert('Directions request failed due to ' + status);
                }

                //Results analysis and drawing of routes
                var fastest = Number.MAX_VALUE,
                    shortest = Number.MAX_VALUE;

                routesResponses.forEach(function(res) {
                    res.routes.forEach(function(rou, index) {
                        console.log("distance of route " +index+": " , rou.legs[0].distance.value);
                        console.log("duration of route " +index+": " , rou.legs[0].duration.value);
                        if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value  ;
                        if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value  ;

                    })
                })
                console.log("shortest: ", shortest);
                console.log("fastest: ", fastest);
//painting the routes in green blue and red
                 routesResponses.forEach(function(res) {
                    res.routes.forEach(function(rou, index) {
                        new google.maps.DirectionsRenderer({
                            map:map,
                            directions:res,
                            routeIndex:index,
                            polylineOptions:{
                                strokeColor: rou.legs[0].duration.value == fastest? "red":rou.legs[0].distance.value == shortest?"darkgreen":"blue",
                                strokeOpacity: rou.legs[0].duration.value == fastest? 0.8:rou.legs[0].distance.value == shortest? 0.9: 0.5,
                                strokeWeight: rou.legs[0].duration.value == fastest? 9:rou.legs[0].distance.value == shortest? 8: 3,
                            }
                        })
                    })
                })   
            });
        }

    }
directionsService=new google.maps.directionsService;
//避免通行费
方向服务.路线({
来源:{
“placeId”:原始ID
},
目的地:{
“placeId”:destinationId
},
ProviderRouteAlternatives:正确,
避免:是的,
travelMode:google.maps.travelMode.DRIVING
},功能(响应、状态){
if(status==google.maps.directionstatus.OK){
路由响应推送(响应);
}
否则{
window.alert('由于'+状态,指示请求失败);
}
});
//避开公路
方向服务.路线({
来源:{
“placeId”:原始ID
},
目的地:{
“placeId”:destinationId
},
ProviderRouteAlternatives:正确,
避免:是的,
travelMode:google.maps.travelMode.DRIVING
},功能(响应、状态){
if(status==google.maps.directionstatus.OK){
路由响应推送(响应);
}
否则{
window.alert('由于'+状态,指示请求失败);
}
//结果分析和路线图绘制
var faster=Number.MAX_值,
最短=数字。最大值;
路由响应forEach(函数(res){
res.routes.forEach(函数(rou,索引){
console.log(“路由距离”+索引+“:”,rou.legs[0].distance.value);
console.log(“路由持续时间”+索引+“:”,rou.legs[0].duration.value);
如果(rou.legs[0].distance.value
请参阅

var shortestDistance=function(){
var方向显示;
var directionsService=new google.maps.directionsService();
var映射;
变量大小=0;
无功电流位置;
//一系列我们想去的有趣的地方。
var利息场所=[
{'title':'Regents Park','latLng':新的google.maps.latLng(51.530686,-0.154753)},
{'title':'Hyde Park','latLng':新的google.maps.latLng(51.507293,-0.164022)},
{'title':'greenpark','latLng':新的google.maps.latLng(51.504088,-0.141706)},
{'title':'Regents Park','latLng':新的google.maps.latLng(51.479185,-0.159903)}
];
//存储Google路由API结果的数组。
var RouterResults=[];
//在页面加载时调用此选项,以使所有内容都处于运动状态!
函数初始化(currentLat、currentLng){
currentPosition=new google.maps.LatLng(currentLat,currentLng);
directionsDisplay=new google.maps.DirectionsRenderer();
变量映射选项={
缩放:13,
中心:当前位置
};
map=new google.maps.map(document.getElementById('map-canvas'),mapOptions);
方向显示.setMap(地图);
var marker=new google.maps.marker({
职位:当前职位,
地图:地图,
标题:“当前位置”
});
var i=兴趣地点。长度;
而(我--){
interestingPlaces[i].marker=new google.maps.marker({
职位:兴趣地点[i].拉丁语,
var shortestDistance = function() {  
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var size = 0;
    var currentPosition;

    // An array of interesting places we want to potentially visit.
    var interestingPlaces = [
    {'title': 'Regents Park', 'latLng': new google.maps.LatLng(51.530686, -0.154753)},
    {'title': 'Hyde Park', 'latLng': new google.maps.LatLng(51.507293, -0.164022)},
    {'title': 'Green Park', 'latLng': new google.maps.LatLng(51.504088, -0.141706)},
    {'title': 'Regents Park', 'latLng': new google.maps.LatLng(51.479185, -0.159903)}
    ];

    // An array to store results from Google routing API.
    var routeResults = [];


    // Call this upon page load to set everything in motion!
    function initialize(currentLat, currentLng) {
    currentPosition = new google.maps.LatLng(currentLat, currentLng);
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
        zoom: 13,
        center: currentPosition
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    directionsDisplay.setMap(map);

    var marker = new google.maps.Marker({
            position: currentPosition,
            map: map,
            title: 'Currrently location.'
    });

    var i = interestingPlaces.length;
        while (i--) {
        interestingPlaces[i].marker = new google.maps.Marker({
        position: interestingPlaces[i].latLng,
        map: map,
        title: interestingPlaces[i].title,
        icon: 'http://maps.google.com/mapfiles/ms/icons/green.png'
        });
    }

    findNearestPlace();
    }


    // Loops through all inteesting places to calculate route between our current position
    // and that place.
    function findNearestPlace() {
    var i = interestingPlaces.length;
    size = interestingPlaces.length;
    routeResults = [];
    while (i--) {
        calcRoute(interestingPlaces[i].latLng, storeResult);
    }
    }


    // A function to calculate the route between our current position and some desired end point.
    function calcRoute(end, callback) {
    var request = {
        origin: currentPosition,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
        callback(response);
        } else {
        size--;
        }
    });
    }


    // Stores a routing result from the API in our global array for routes.
    function storeResult(data) {
    routeResults.push(data);
    if (routeResults.length === size) {
        findShortest();
    }
    }


    // Goes through all routes stored and finds which one is the shortest. It then
    // sets the shortest route on the map for the user to see.
    function findShortest() {
    var i = routeResults.length;
    var shortestIndex = 0;
    var shortestLength = routeResults[0].routes[0].legs[0].distance.value;

    while (i--) {
        if (routeResults[i].routes[0].legs[0].distance.value < shortestLength) {
        shortestIndex = i;
        shortestLength = routeResults[i].routes[0].legs[0].distance.value;
        }
    }
    directionsDisplay.setDirections(routeResults[shortestIndex]);
    }

    // Expose the initialize function publicly as "init".
    return {
    init: initialize
    };
}();

// Upon page load, lets start the process!
google.maps.event.addDomListener(window, 'load', shortestDistance.init(51.489554, -0.12969));
directionsService.route({
            [...]
            provideRouteAlternatives: true
            [...]
         }, (response, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                var shortest: google.maps.DirectionsResult = this.shortestRoute(response);
                this.directionsDisplay.setDirections(shortest);
                [...]
    shortestRoute = (routeResults: google.maps.DirectionsResult): google.maps.DirectionsResult => {
        var shortestRoute: google.maps.DirectionsRoute = routeResults.routes[0];
        var shortestLength = shortestRoute.legs[0].distance.value;
        for (var i = 1; i < routeResults.routes.length; i++) {
            if (routeResults.routes[i].legs[0].distance.value < shortestLength) {
                shortestRoute = routeResults.routes[i];
                shortestLength = routeResults.routes[i].legs[0].distance.value;
            }
        }
        routeResults.routes = [shortestRoute];
        return routeResults;
    }
shortestRoute(origin, destination, map); 
function shortestRoute(origin, destination, map) {

  directionsService = new google.maps.DirectionsService();
  var routesResponses = [];
  //avoiding tolls
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidTolls: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
  //avoiding highways
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidHighways: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }

    //Results analysis and drawing of routes
    var fastest = Number.MAX_VALUE,
      shortest = Number.MAX_VALUE;

    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        console.log("distance of route " + index + ": ", rou.legs[0].distance.value);
        console.log("duration of route " + index + ": ", rou.legs[0].duration.value);
        if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value;
        if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value;

      })
    })
    console.log("shortest: ", shortest);
    console.log("fastest: ", fastest);
    //painting the routes in green blue and red
    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        new google.maps.DirectionsRenderer({
          map: map,
          directions: res,
          routeIndex: index,
          polylineOptions: {
            strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
            strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
            strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
          }
        });
      });
    });
  });
}