mazenqp
mazenqp

Reputation: 355

how to calculate Distance between two coordinates using Mapbox Kotlin

how can I get the Distance out of Mapbox Navigation Route? in Double Format, I don't want to draw the route I just need to calculate the distance between two Points, I have been able to calculate the distance using Truf

Storelocation = Point.fromLngLat(Stores.latitude, Stores.longitude)
Userlocation = Point.fromLngLat(UserLocation.Latitude, UserLocation.Longitude)
Distance = TurfMeasurement.distance(Storelocation, Userlocation, TurfConstants.UNIT_KILOMETERS)

but the problem is with this method above it doesn't calculate distance within the route, it is just calculate straight line from point to point for example in Google map the distance is 9 Km, but with this method above the distance is 6 Km

private fun getRout(){
        NavigationRoute.builder(this)
            .accessToken(Mapbox.getAccessToken()!!)
            .origin(Userlocation)
            .destination(Storelocation).build().getRoute(object :Callback<DirectionsResponse> {
                override fun onResponse(call: Call<DirectionsResponse>, response: Response<DirectionsResponse>) {
                    val rout = response ?: return
                    val body = rout.body() ?: return
                    if (body.routes().count() == 0 ){
                        return
                    }
                    navigationMapRoute = NavigationMapRoute(null, mapView, map)
                    // Get Distance
                    Distance = ??

                }

                override fun onFailure(call: Call<DirectionsResponse>, t: Throwable) {

                }
            })
    }

Upvotes: 2

Views: 1856

Answers (1)

David Wasser
David Wasser

Reputation: 95588

Instead of this:

navigationMapRoute = NavigationMapRoute(null, mapView, map)
                // Get Distance
                Distance = ??

Do this:

val route = response.body().routes().get(0)
val distance = route.distance()

Upvotes: 1

Related Questions