获取从当前位置到目的地的谷歌地图方向

时间:2015-11-04 16:27:48

标签: android google-maps google-maps-api-3 google-direction

我正在使用谷歌地图方向API获取方向json,但我的问题是我无法将当前位置传递给origin参数。有没有办法做到这一点?

http://maps.google.com/maps/api/directions/json?origin=41.393529,-72.811514&destination=41.311725,-72.740211

2 个答案:

答案 0 :(得分:0)

看看documentation。看起来你使用的是错误的网址。例如,文档将https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens列为正确的API。那么可以将maps.google.com更改为maps.googleapis.com?

编辑:

啊,现在我遇到了问题。 Google Maps API似乎不提供此功能。猜猜最好的方法是使用Android手机上的位置管理器获取纬度和经度,并在网址中对其进行格式化。

答案 1 :(得分:0)

如果您使用谷歌地图api,那么您必须在您的应用中使用googleapiclient。如果没有,那么请这样做。

使用google api客户端 -

googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .enableAutoManage(this, 0, this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

@Override
protected void onStart() {
    googleApiClient.connect();
    super.onStart();
}

@Override
protected void onStop() {
    if (googleApiClient != null && googleApiClient.isConnected()) {
        googleApiClient.disconnect();
    }
    super.onStop();
}

然后在连接到谷歌ai客户端之后你必须实现方法并在onConnected()方法内部(你必须覆盖这个方法)你可以获得当前位置。

获取当前位置onConnected -

Location loc = LocationServices
            .FusedLocationApi
            .getLastLocation(googleApiClient);

loc对象是当前位置,您可以在任何代码点使用该位置来获取该实例的位置,但仅在连接了googleapiclient之后。

您可以将其作为 -

应用到您的代码中
String url="http://maps.google.com/maps/api/directions/json?origin="+loc.getLatitude()+","+loc.getLongitude()+"&destination=41.311725,-72.740211";