I am working on my project trying to add a waypoint in between of the route that I generated from my Location to Destination, short (point A to point B). I am not able to do this due to only a singular marker added to the calculateDirections() method and calculated. How program works: Location is added to the map, the first point is added when the user searches for the location in an autocomplete view and it gets calculated straight away showing the route to the user. Once this is done, user is able to click anywhere on the map to add an additional marker. The problem: Once the additional marker is added, the program just reroutes everything to the new point leaving the initial point. What can I do to fix this issue, here is the essential code for autocomplete method, calculate route and calculate popylines:
mSearchText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
Intent intent = new
Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY,
fields)
.build(MapsActivity.this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
hideSoftKeyboard();
return false;
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
String searchString = place.getName();
Geocoder geocoder = new Geocoder(MapsActivity.this,
Locale.getDefault());
List<Address> list;
try {
list = geocoder.getFromLocationName(searchString, 1);
if (list.size()> 0){
Address address = list.get(0);
LatLng latLng = new
LatLng(address.getLatitude(),address.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
MarkerOptions marker = new
MarkerOptions().position(latLng);
calculateDirections(marker);
//add on map click listener and add an additional marker
mMap.setOnMapClickListener(new
GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
List<LatLng> list = new ArrayList<>();
list.add(latLng);
// Add some markers to the map, and add a data
object to each marker
MarkerOptions marker2 = new
MarkerOptions().position(latLng);
calculateDirections(marker2);
}
});
}
} catch (IOException e) {
Log.e(TAG, "geoLocate: IOException: " + e.getMessage());
e.printStackTrace();
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void calculateDirections(MarkerOptions marker){
Log.d(TAG, "calculateDirections: calculating directions.");
ArrayList<MarkerOptions> markers = new ArrayList<>(2);
markers.add(marker);
for (int i = 0; i < markers.size(); i++) {
dest1 = markers.get(0);
com.google.maps.model.LatLng destination = new
com.google.maps.model.LatLng(
dest1.getPosition().latitude,
dest1.getPosition().longitude
);
if (markers.size() > 1){
dest2 = markers.get(1);
DirectionsApiRequest directions = new
DirectionsApiRequest(mGeoApiContext);
directions.alternatives(true);
directions.origin(
new com.google.maps.model.LatLng(
userPosition.getPosition().latitude,
userPosition.getPosition().longitude
)
);
directions.optimizeWaypoints(true);
directions.waypoints(
new com.google.maps.model.LatLng(
dest2.getPosition().latitude,
dest2.getPosition().longitude
)
);
Log.d(TAG, "calculateDirections: destination: " +
destination.toString());
directions.destination(destination).setCallback(new
PendingResult.Callback<DirectionsResult>() {
@Override
public void onResult(DirectionsResult result) {
Log.d(TAG, "calculateDirections: routes: " +
result.routes[0].toString());
Log.d(TAG, "calculateDirections: duration: " +
result.routes[0].legs[0].duration);
Log.d(TAG, "calculateDirections: distance: " +
result.routes[0].legs[0].distance);
Log.d(TAG, "calculateDirections: geocodedWayPoints: "
+ result.geocodedWaypoints[0].toString());
addPolylinesToMap(result);
}
@Override
public void onFailure(Throwable e) {
Log.e(TAG, "calculateDirections: Failed to get
directions: " + e.getMessage());
}
});
}
else {
DirectionsApiRequest directions = new
DirectionsApiRequest(mGeoApiContext);
directions.alternatives(true);
directions.origin(
new com.google.maps.model.LatLng(
userPosition.getPosition().latitude,
userPosition.getPosition().longitude
)
);
Log.d(TAG, "calculateDirections: destination: " +
destination.toString());
directions.destination(destination).setCallback(new
PendingResult.Callback<DirectionsResult>() {
@Override
public void onResult(DirectionsResult result) {
Log.d(TAG, "calculateDirections: routes: " +
result.routes[0].toString());
Log.d(TAG, "calculateDirections: duration: " +
result.routes[0].legs[0].duration);
Log.d(TAG, "calculateDirections: distance: " +
result.routes[0].legs[0].distance);
Log.d(TAG, "calculateDirections: geocodedWayPoints: "
+ result.geocodedWaypoints[0].toString());
addPolylinesToMap(result);
}
@Override
public void onFailure(Throwable e) {
Log.e(TAG, "calculateDirections: Failed to get
directions: " + e.getMessage());
}
});
}
}
}
private void addPolylinesToMap(final DirectionsResult result){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: result routes: " + result.routes.length);
//check if there are any polylines selected and remove the old
one before the new
//one is selected
if(mPolylinesData.size() > 0){
for (PolylineData polylineData: mPolylinesData){
polylineData.getPolyline().remove();
}
mPolylinesData.clear();
mPolylinesData = new ArrayList<>();
}
double duration = 999999;
for(DirectionsRoute route: result.routes){
Log.d(TAG, "run: leg: " + route.legs[0].toString());
// Get all the lines on checklist by calling decoder path
List<com.google.maps.model.LatLng> decodedPath =
PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
// Adding new array list by adding all the lines
List<LatLng> newDecodedPath = new ArrayList<>();
// This loops through all the LatLng coordinates of ONE
polyline.
for(com.google.maps.model.LatLng latLng: decodedPath){
newDecodedPath.add(new LatLng(
latLng.lat,
latLng.lng
));
}
Polyline polyline = mMap.addPolyline(new
PolylineOptions().addAll(newDecodedPath));
polyline.setColor(ContextCompat.getColor(getApplicationContext(),
R.color.darkGrey));
polyline.setClickable(true);
mPolylinesData.add(new PolylineData(polyline,
route.legs[0]));
// Measure time in seconds of all trip durations and
select the shortest duration
double tempDuration = route.legs[0].duration.inSeconds;
if(tempDuration < duration){
duration = tempDuration;
onPolylineClick(polyline);
}
}
}
});
}