如何通过GoogleMaps上的多个点绘制从A到B的路线?

时间:2019-06-04 06:38:58

标签: android google-maps kotlin

想象一下我想通过3个航点从A到B。我有这段代码,形成了Google Maps方向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
    }

在浏览器上打开URL即可:

  

{“路线”:[],“状态”:“零结果”}

但是,如果我仅使用1个航路点(而不是上面显示的3个航路点),那么方向将正确显示在1个大JSON中,如下所示:

  

{“ geocoded_waypoints”:[         {            “ geocoder_status”:“确定”,            “ place_id”:“ ChIJH87yjIXxaS4R5_ww8ZCufeo”,            “类型”:[“服装店”,“机构”,“兴趣点”,“商店”]         },         {            “ geocoder_status”:“确定”,            “ place_id”:“ ChIJ1wVXzIDxaS4RkyUYgf3ZV0c”,            “ types”:[“ street_address”]         },         {            “ geocoder_status”:“确定”,            “ place_id”:“ ChIJrfOSGBXxaS4Ro595K_5ClCg”,            “类型”:[“机构”,“医院”,“兴趣点”]         }],“路线”:[         {            “界限”:{               “东北”:{                  “ lat”:-6.2399232,                  “ lng”:106.8161445               },               “西南”:{                  “ lat”:-6.2684858,                  “ lng”:106.7929824               }            },            “ copyrights”:“地图数据©2019 Google”,            “腿”:[               {                  “距离”:{                     “文字”:“ 1.2公里”,                     “值”:1205                  },                  “持续时间”:{                     “ text”:“ 4分钟”,                     “值”:254                  },                  “ end_address”:“ Jl。Kemang Raya No.54,RT.8 / RW.2,Bangka,Kec。Mampang Prpt。,哥打雅加达Selatan,Daerah Khusus   印度尼西亚雅加达Ibukota 12730”,                  “ end_location”:{                     “ lat”:-6.263443499999999,                     “ lng”:106.8160131 ....

那么这是否意味着我只能使用1个航路点?

1 个答案:

答案 0 :(得分:0)

无法通过设置的航点从起点到目的地。第二个网址:

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>

在大西洋中包含无法到达的目的地destination=-6.235759,6.823277。如果所有位置均应引用雅加达的有效位置,则可能的目的地应该是106.823277而不是6.823277destination=-6.235759,106.823277。因此,请仔细检查代码,该代码构成了Directions API请求的URL。