How to find optimal route to one of many markers?

2019-08-24 07:08发布

On a map I have to arrays of markers. One's are static, let's call station. Other's also static, but they are temporary, let's call them fire. When fire is clicked shortest route must be constructed to one of stations. I use TravelMode.DRIVING. I know that I can calculate route distance, but in order to calculate I must construct route first. Is there any library to find optimal route between one fixed marker and one of many other markers? Or can you help me telling logic? I can write code myself.

Here is I implemented optimal route to one of two markers, and to many markers can be calculated using loop. But is there any alternative way to do it?

    directionsService1.route(request1, function (response1, status1) {
        if (status1 == google.maps.DirectionsStatus.OK) {
            var myRoute1 = response1.routes[0].legs[0];
            distance1 = myRoute1.distance.value;
            directionsService2.route(request2, function (response2, status2) {
                if (status2 == google.maps.DirectionsStatus.OK) {
                    var myRoute2 = response2.routes[0].legs[0];
                    distance2 = myRoute2.distance.value;
                    if (distance1 > distance2) {
                        directionsDisplay2.setMap(map);
                        directionsDisplay2.setDirections(response2);
                        directionsDisplay1.setMap(null);
                    } else {
                        directionsDisplay1.setMap(map);
                        directionsDisplay1.setDirections(response1);
                        directionsDisplay2.setMap(null);
                    }
                }
            });
        }
    });

2条回答
Bombasti
2楼-- · 2019-08-24 07:53

DirectionsService has a method route to compute one or more routes between two points.

You could call this method for every fire-station pair and inspect the returned routes to determine the shortest one.

查看更多
戒情不戒烟
3楼-- · 2019-08-24 08:11

The directions service is rate limited and subject to a quota. If you have lots of points you are not going to be able to call it in a loop for all of them.

One suggestion would be to calculate the straight line distance to all the points, then the driving distance to the closest 8 of those result (assuming there were more than 8 to start with). I suggest 8 as that would be the maximum number of waypoints you ca put in a directions request, I think if you set optimize_waypoints to true and add all of those 8 as waypoints to a round trip (start and end points are the same), you will get the shortest driving distance between either the first or the last waypoint and the start point.

Another would be to use google's distance matrix api

查看更多
登录 后发表回答