简体   繁体   中英

How to draw route from A to B through multiple points on GoogleMaps?

Imagine I want to go from A to B through 3 waypoints. I have this code, which forms the Google Maps direction URL:

fun getMapsApiDirectionsUrl(): String {
    val origin = "origin=" + currentLocation.latitude + "," + currentLocation.longitude;
    val waypoints = "waypoints=optimize:true|" + loc1.latitude + "," + loc1.longitude + "|" + loc2.latitude + "," + loc2.longitude + "|" + loc3.latitude + "," + loc3.longitude
    val destination = "destination=" + loc4.latitude + "," + loc4.longitude
    val sensor = "sensor=false"
    val key = "key="+API_KEY;
    val params = "$origin&$waypoints&$destination&$sensor&$key"
    val output = "json"

    val url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params
    System.out.println("map url: "+url)
    return url
}

Opening the URL on browser gave this:

{ "routes" : [], "status" : "ZERO_RESULTS" }

But if I only use 1 waypoint (instead of 3 like shown above), the direction will be displayed in 1 big JSON correctly, like this:

{ "geocoded_waypoints" : [ { "geocoder_status" : "OK", "place_id" : "ChIJH87yjIXxaS4R5_ww8ZCufeo", "types" : [ "clothing_store", "establishment", "point_of_interest", "store" ] }, { "geocoder_status" : "OK", "place_id" : "ChIJ1wVXzIDxaS4RkyUYgf3ZV0c", "types" : [ "street_address" ] }, { "geocoder_status" : "OK", "place_id" : "ChIJrfOSGBXxaS4Ro595K_5ClCg", "types" : [ "establishment", "hospital", "point_of_interest" ] } ], "routes" : [ { "bounds" : { "northeast" : { "lat" : -6.2399232, "lng" : 106.8161445 }, "southwest" : { "lat" : -6.2684858, "lng" : 106.7929824 } }, "copyrights" : "Map data ©2019 Google", "legs" : [ { "distance" : { "text" : "1.2 km", "value" : 1205 }, "duration" : { "text" : "4 mins", "value" : 254 }, "end_address" : "Jl. Kemang Raya No.54, RT.8/RW.2, Bangka, Kec. Mampang Prpt., Kota Jakarta Selatan, Daerah Khusus Ibukota Jakarta 12730, Indonesia", "end_location" : { "lat" : -6.263443499999999, "lng" : 106.8160131....

So does it mean I can only use 1 waypoint?

There is no way from origin to destination via waypoints set. The second URL:

https://maps.googleapis.com/maps/api/directions/json?origin=-6.2684059,106.8103103&waypoints=optimize:true%7C-6.263459,106.815903%7C-6.240607,106.792831%7C-6.240607,106.792831&destination=-6.235759,6.823277&sensor=false&key=<YOUR_KEY>

contains unreachable destination destination=-6.235759,6.823277 in Atlantic Ocean. Probably destination should be 106.823277 instead of 6.823277 : destination=-6.235759,106.823277 if all the positions should refer to valid locations in Jakarta. So, double check code, that compose URL for Directions API request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM