Today I come with an issue which can be certainly uncommon but i've been working entire days in it without having any result.
What I want: I want to draw a polyline between multiple points, taking into account that the route has to be the one with the LESS DISTANCE in it, not as the way the user selects his destinations.
Context: I've got a LatLng ArrayList, which is filled as the user clicks on the map, the clicked LatLng is stored into the ArrayList automatically. Than, I convert it into a Position arraylist in order to use the setCoordinates() method. Also, i've got an 'origin' point, which is going to be the users' current location. I've established an ordinary one to make tests.
Problem: As the user clicks the destinations, the ArrayList is filled in the way he clicks, without taking into account what is the nearest destination, and that's the thing I want to achieve, to trace the route only taking into account that the distance between the points has to be the shortest.
Here is my sample code (please note that if the "al" ArrayList could be ordered taking distance into account, probably the route would be successful):
for (int i=0; i<= direcciones.size() - 1; i++) {
LatLng tri = direcciones.get(i);
Position p = Position.fromCoordinates(tri.getLongitude(), tri.getLatitude());
al.add(i, p);
}
MapboxDirections client = new MapboxDirections.Builder()
.setAccessToken(Mapbox.getAccessToken())
.setOrigin(Position.fromCoordinates(-56.1645, -34.9011))
.setCoordinates(al)
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.build();
Thank you in advance!
Sounds like you want to use Optimized trips which I just added in this pull request. It solves the issue of the traveling salesman. It is very similar to the directions API but the request is a bit different:
MapboxOptimizedTrips.Builder builder = new MapboxOptimizedTrips.Builder()
.setAccessToken(Mapbox.getAccessToken())
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.setSource(DirectionsCriteria.SOURCE_FIRST)
.setOverview(DirectionsCriteria.OVERVIEW_FULL);
MapboxOptimizedTrips client = builder.setCoordinates(coords).build();
client.enqueueCall(new Callback<OptimizedTripsResponse>() {
@Override
public void onResponse(Call<OptimizedTripsResponse> call, Response<OptimizedTripsResponse> response) {
drawLine(response.body().getTrips().get(0).getGeometry());
}
@Override
public void onFailure(Call<OptimizedTripsResponse> call, Throwable throwable) {
Timber.e("Calling optimize trips failed: ", throwable);
}
});
}