有人能帮我使用Kotlin在地图上绘制最短路径,并在导航时更新我的路径或更新我的LatLng吗?我必须在类似 OLA 的出租车导航应用程序中实现此功能。但是我无法在司机和用户之间绘制最短路径。
提前感谢
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"))
}
val options = PolylineOptions()
options.color(Color.RED)
options.width(5f)
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))