Android 在安卓系统中,如何获取谷歌地图上两个地点之间的旅行时间?

Android 在安卓系统中,如何获取谷歌地图上两个地点之间的旅行时间?,android,google-maps,Android,Google Maps,我可以使用方向api和此方法获得两个位置之间的距离 我的代码用于获取距离: @Override public void onDirectionSuccess(Direction direction, String rawBody) { if (getActivity() != null) { if (direction.isOK()) { ArrayList<LatLng> directionPositionList = d

我可以使用方向api和此方法获得两个位置之间的距离

我的代码用于获取距离:

 @Override
  public void onDirectionSuccess(Direction direction, String rawBody) {
    if (getActivity() != null) {
        if (direction.isOK()) {
            ArrayList<LatLng> directionPositionList = 
  direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();

 myMap.addPolyline(DirectionConverter.createPolyline(getActivity(), 
 directionPositionList, 5, Color.RED));
            myMap.addMarker(new MarkerOptions().position(new 
 LatLng(origin.latitude, origin.longitude)).title("Pickup 
 Location").snippet(pickup_address).
 icon(BitmapDescriptorFactory.defaultMarker
 (BitmapDescriptorFactory.HUE_RED)));
  myMap.addMarker(new MarkerOptions().position(new 
 LatLng(destination.latitude, destination.longitude))
.title("Drop Location").snippet(drop_address).icon
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 
10));

  calculateDistance(Double.valueOf(direction.getRouteList()
 .get(0).getLegList().get(0).getDistance().getValue()) / 1000);
@覆盖
public void onDirectionSuccess(方向、字符串主体){
如果(getActivity()!=null){
if(direction.isOK()){
ArrayList方向位置列表=
direction.getRouteList().get(0.getLegList().get(0.getDirectionPoint();
myMap.addPolyline(DirectionConverter.createPolyline(getActivity()),
方向位置列表,5,颜色为红色);
myMap.addMarker(新标记选项().position(新
LatLng(原点.纬度,原点.经度)).标题(“拾取
位置“)。代码段(取货地址)。
图标(BitmapDescriptorFactory.defaultMarker
(BitmapDescriptorFactory.HUE_RED));
myMap.addMarker(新标记选项().position(新
LatLng(目的地.纬度,目的地.经度))
.title(“放置位置”).snippet(放置地址)。图标
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(原点,
10));
CalculateInstance(Double.valueOf(direction.getRouteList())
.get(0.getLegList().get(0.getDistance().getValue())/1000);
如何在android中使用google地图中的direction api获取行程时间?

我建议使用google提供的。使用此方法可以设置交通方式以获得最准确的行程时间

try{
        val context = GeoApiContext.Builder()
                .apiKey(Constants.GOOGLE_API_KEY)
                .build()

        val req = DistanceMatrixApi.newRequest(context)
        val origin = LatLng(fromlocation.getLatitude(), fromlocation.getLongitude())
        val destination = LatLng(tolocation.getLatitude(), tolocation.getLongitude())

        val trix = req.origins(origin)
                .destinations(destination)
                .mode(TravelMode.DRIVING)
                .await()

        eta = trix.rows[0].elements[0].duration.humanReadable

    }catch (ex:Exception){
        Log.e("ETA", ex.message)
    }

可以使用方向api查找起点和终点之间的距离

 public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2) {
    final String[] parsedDistance = new String[1];
    final String[] response = new String[1];
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL("https://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                Log.v("urldirection", url.toString());
                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                InputStream in = new BufferedInputStream(conn.getInputStream());
                response[0] = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

                JSONObject jsonObject = new JSONObject(response[0]);
                JSONArray array = jsonObject.getJSONArray("routes");
                JSONObject routes = array.getJSONObject(0);
                JSONArray legs = routes.getJSONArray("legs");
                JSONObject steps = legs.getJSONObject(1);
                JSONObject distance = steps.getJSONObject("duration");
                parsedDistance[0] = distance.getString("text");

            } catch (JSONException | IOException e) {
                Log.v(TAG, e.toString());
            }
        }
    });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        Log.v("DistanceGoogleAPi", "Interrupted!" + e);
        Thread.currentThread().interrupt();
    }
    return parsedDistance[0];
}

调用此方法将返回距离。请根据您的要求更改url中的查询参数。

您能给我一些此api的示例吗?我可以尝试一下,但无法获得旅行时间get error E/E:org.json.JSONException:索引0超出范围[0..0)在google cloud平台中启用方向和url的键i change url,也启用方向api,但其stll获取错误索引0超出范围您是否将api键添加为url中的参数之一?类似于“+lat1+”、“+lon1+”&destination=“+lat2+”、“+lon2+”“&sensor=false&units=metric&mode=driving&key=YOUR_key”让我们来看看。