android - 如何使用实时导航在 Kotlin 的 Google 地图上绘制最短路径?
问题描述
任何人都可以帮助我使用 Kotlin 在地图上绘制最短路径并在导航时更新我的路径或更新我的 LatLng。我必须在类似 OLA 的出租车导航应用程序上实现这一点。但我可以在两点之间绘制最短路径,驱动程序和用户。
提前致谢
解决方案
试试这个代码:
在 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))
推荐阅读
- javascript - 当它是 CSV 文件时,如何使用 Chartjs 按年龄填充病例和死亡人数?
- spring - Spring响应式读取Web客户端响应
- android - 将 recyclerview 的改造结果与 MVVM 架构相结合
- c++ - 无限循环 C++ 逻辑错误
- python - 当我给它一个参数时,当它说它缺少一个必需的参数时,这里的错误是什么意思?
- c - Windows 中的 CreateThread API 是否会自动将线程分散到多个内核?
- reactjs - 如何键入此类数据
- python - 模型拟合错误 数据基数不明确
- google-bigquery - bigquery 的增量负载不适用于 dbt unique_key
- java - 混合应用程序不显示 WebView 上下文并且无法在应用程序中定位元素