首页 > 解决方案 > 如何使用实时导航在 Kotlin 的 Google 地图上绘制最短路径?

问题描述

任何人都可以帮助我使用 Kotlin 在地图上绘制最短路径并在导航时更新我的​​路径或更新我的 LatLng。我必须在类似 OLA 的出租车导航应用程序上实现这一点。但我可以在两点之间绘制最短路径,驱动程序和用户。

提前致谢

标签: androidkotlin

解决方案


试试这个代码:

在 gradle 文件中添加依赖

 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"))        
}

下一步是创建一个 PolylineOptions 对象,设置颜色和宽度。稍后我们将使用此对象添加点。

val options = PolylineOptions()
options.color(Color.RED)
options.width(5f)

现在,我们需要构建用于进行 API 调用的 URL。我们可以将它放在一个单独的函数中以将其排除在外:

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 }
 }

一旦我们存储并准备好我们的字符串,代码的 uiThread 部分将执行,其余代码将执行。现在我们准备好从字符串中提取 JSON 对象,我们将使用 klaxon。这也很简单:

 val parser: Parser = Parser()
 val stringBuilder: StringBuilder = StringBuilder(result)
 val json: JsonObject = parser.parse(stringBuilder) as JsonObject

实际上遍历 JSON 对象来获取分数是相当容易的。klaxon 使用简单,它的 JSON 数组可以像任何 Kotlin 列表一样使用。

 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))

参考:https ://medium.com/@irenenaya/drawing-path-between-two-points-in-google-maps-with-kotlin-in-android-app-af2f08992877


推荐阅读