如何在Kotlin中使用实时导航在Google地图上绘制最短路径?

3

有人能帮我使用Kotlin在地图上绘制最短路径,并在导航时更新我的路径或更新我的LatLng吗?我必须在类似 OLA 的出租车导航应用程序中实现此功能。但是我无法在司机和用户之间绘制最短路径。

提前感谢

1个回答

2
尝试这段代码:
在 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))

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接