I am trying to call directions API and showing the route on Map, but the route is not perfectly matching the road.
Here's how I am getting Directions:
suspend fun getGoogleDirections(
origin: LatLng,
destination: LatLng,
mapsApiKey: String
): Flow<DataState<List<LatLng>>> = flow {
try {
val apiResponse = apiInterface.getDirectionFromGoogle(
"${origin.latitude},${origin.longitude}",
"${destination.latitude},${destination.longitude}",
mapsApiKey
)
if (apiResponse.isSuccessful) {
val responseBody = apiResponse.body()!!
logD(TAG, "response = ${responseBody}")
val responseObject = JSONObject(responseBody)
val routes = responseObject.getJSONArray("routes")
val firstRoute = routes.getJSONObject(0)
val legs = firstRoute.getJSONArray("legs")
val firstLeg = legs.getJSONObject(0)
val steps = firstLeg.getJSONArray("steps")
val ovPolyline = firstRoute.getJSONObject("overview_polyline")
val polyline = ovPolyline.getString("points")
emit(DataState.Success(PolyUtil.decode(polyline)))
} else {
val error = apiResponse.errorBody()?.string()!!
logE(TAG,"", error)
emit(DataState.Error("error in fetching directions"))
}
} catch (e: Exception) {
logE(TAG,"",e.message ?: "Exception")
emit(DataState.Error("An unexpected error occurred"))
}
}
My API interface:
@GET("directions/json")
suspend fun getDirectionFromGoogle(
@Query("origin") origin: String,
@Query("destination") destination: String,
@Query("key") apiKey: String,
@Query("mode") mode: String = "driving"
): Response<String>
Adding Polyline on Map
val directionPolyline = mMap.addPolyline(
PolylineOptions()
.color(ContextCompat.getColor(requireContext(), R.color.colorPrimaryDark))
//.width(3f)
.geodesic(false)
.endCap(RoundCap())
.startCap(RoundCap())
.addAll(listOfPoints)
)
I face this problem specially if the distance is large. For nearby distance the results are still better.
Note: Earlier I have used MapBox and in that there is a key "overview=full" that Enables this but I am not able to find anything in Google Maps.