谁能帮助我使用Kotlin在地图上绘制最短路径,并在导航时更新我的路径或更新我的LatLng。我必须在类似OLA的应用程序上实现此功能,以进行出租车导航。 但我可以在驾驶员和用户两点之间画出最短路径。
预先感谢
答案 0 :(得分: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 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))