【问题标题】:Android Google map - fallback if destination direction route not foundAndroid Google map - 如果找不到目的地方向路线,则回退
【发布时间】:2019-05-20 14:42:01
【问题描述】:

我发现按经纬度打开地图路线的方法很少:

String uri = "http://maps.google.com/maps?daddr=" + destLat + "," + destLong + " (" + safeURLString + ")"; //first way
//String uri = "https://www.google.com/maps/search/?api=1&query=" + destLat + "," + destLong; //second way
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
if (intent.resolveActivity(getPackageManager()) != null) {
    startChildActivity(intent);
}

问题是有时第一种方式能够找到路线,或者有时只有第二种方式能够在没有路线时标记目的地。

是否可以检查是否找不到路由然后回退/回调以尝试第二个 url 或至少标记目的地?

【问题讨论】:

    标签: android google-maps android-intent google-maps-android-api-2 android-location


    【解决方案1】:

    您可以使用HttpUrlConnectionDirections API 来测试路由是否存在:

    https://maps.googleapis.com/maps/api/directions/json?origin=<originLat>,<originLon>&destination=<destLat>,<destLon>&key=<YOUR_DIRECTIONS_API_KEY>
    

    如果HttpUrlConnection 响应如下:

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

    那么该路线不存在,您应该在没有路线时使用第二种方式标记目的地。否则,当HttpUrlConnection 响应时喜欢

    {
       "geocoded_waypoints" : [
    
       <lines of response here> 
       ...
    
       ],
       "status" : "OK"
    }
    ...
    

    路线存在,您可以使用第一种方式找到路线。因此,通过HttpUrlConnection 使用Directions API 并检查"status" 标签:如果"status" : "OK" - 路由存在。

    【讨论】: