对不起我的英语(谷歌翻译)。我试图在 Kotlin上使用 klaxon ( https://github.com/cbeust/klaxon )从答案谷歌方向得到两点之间的距离。
fun distanceDier (start: LatLng, end: LatLng, mode: String) {
val url = ("http://maps.googleapis.com/maps/api/directions/json?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=" + mode)
val result = URL("$url").readText()
val parser: Parser = Parser()
val stringBuilder: StringBuilder = StringBuilder(result)
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
println("distance : ${json.string("routes.legs.distance.text")},")
println("$url") //test
设定点
distanceDier(LatLng(53.402971, 91.083748),LatLng(53.529799, 91.410684),"TravelMode")
日志:
FATAL EXCEPTION: main
Process: ru.kbais.coal4, PID: 4494
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {ru.kbais.coal4/ru.kbais.coal4.MainActivity}: android.os.NetworkOnMainThreadException
放置错误
val result = URL("$url").readText()
如何从 Json 文件中获取距离以及错误代码是什么?