Can anyone help me to drawing a shortest path on map using Kotlin and update my path while navigation or update my LatLng. I have to implement this on a OLA like app for cab navigation. but i'm enable to draw shortest path between two points, Driver and user.
Thanks in Advance
Try This Code:
in gradle file add dependency
compile 'org.jetbrains.anko:anko-sdk15:0.8.2'
compile 'com.beust:klaxon:0.30'
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
val sydney = LatLng(-34.0, 151.0)
val opera = LatLng(-33.9320447,151.1597271)
mMap!!.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap!!.addMarker(MarkerOptions().position(opera).title("Opera House"))
}
The next step is to create a PolylineOptions object, set up the color and width. We will use this object to add the points later.
val options = PolylineOptions()
options.color(Color.RED)
options.width(5f)
Now, we need to build the URL we will use to make the API call. We can put it in a separate function to get it out of the way:
private fun getURL(from : LatLng, to : LatLng) : String {
val origin = "origin=" + from.latitude + "," + from.longitude
val dest = "destination=" + to.latitude + "," + to.longitude
val sensor = "sensor=false"
val params = "$origin&$dest&$sensor"
return "https://maps.googleapis.com/maps/api/directions/json?$params"
}
And, of course, we call it by doing:
val url = getURL(sydney, opera)
async {
val result = URL(url).readText()
uiThread {
// this will execute in the main thread, after the async call is done }
}
Once we have our string stored and ready, the uiThread part of the code will execute and there is where the rest of the code goes. Now we are ready to extract the JSON object from the string, and we will use klaxon for that. This is also pretty simple:
val parser: Parser = Parser()
val stringBuilder: StringBuilder = StringBuilder(result)
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
Actually traversing the JSON object to get the points is fairly easy. klaxon is simple to use and its JSON arrays can be used just like any Kotlin List.
val routes = json.array<JsonObject>("routes")
val points = routes!!["legs"]["steps"][0] as JsonArray<JsonObject>
val polypts = points.map { it.obj("polyline")?.string("points")!! }
val polypts = points.flatMap { decodePoly(it.obj("polyline")?.string("points")!!)
}
//polyline
options.add(sydney)
for (point in polypts) options.add(point)
options.add(opera)
mMap!!.addPolyline(options)
mMap!!.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100))
Refer:https://medium.com/@irenenaya/drawing-path-between-two-points-in-google-maps-with-kotlin-in-android-app-af2f08992877
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With