java - 如何获取 Google 返回的 JSON 对象中的持续时间和距离?

标签 java android google-directions-api

例如,我想在此获取距离和持续时间 https://maps.googleapis.com/maps/api/directions/json?key=API_Key&sensor=true&language=en&origin=6.035507,116.1213559&destination=5.9699316,116.0665816 .我已经得到了这两个位置之间的路线。但我不知道如何显示距离和持续时间。需要一些帮助。我已经知道其他人已经发布了这个问题,但由于我被认为是 Android 的新手,它似乎无法使用我的代码。 下面是我的代码:

private void drawRoute(final LatLng yourLocation, final Request request) {

    //clear all polyline
    if (polyline != null)
        polyline.remove();

    if (request.getAddress() != null && !request.getAddress().isEmpty()) {
        mService.getGeoCode(request.getAddress()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());

                    String lat = ((JSONArray) jsonObject.get("results"))
                            .getJSONObject(0)
                            .getJSONObject("geometry")
                            .getJSONObject("location")
                            .get("lat").toString();

                     String lng = ((JSONArray) jsonObject.get("results"))
                            .getJSONObject(0)
                            .getJSONObject("geometry")
                            .getJSONObject("location")
                            .get("lng").toString();

                    final LatLng orderLocation = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));

                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.deliverybox);
                    bitmap = Common.scaleBitmap(bitmap, 70, 70);

                    MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                            .title("Order of " + Common.currentRequest.getPhone())
                            .position(orderLocation);

                    mMap.addMarker(marker);

                    //draw route

                    mService.getDirections(yourLocation.latitude + "," + yourLocation.longitude,
                            orderLocation.latitude + "," + orderLocation.longitude)
                            .enqueue(new Callback<String>() {
                                @Override
                                public void onResponse(Call<String> call, Response<String> response) {

                                    new ParserTask().execute(response.body().toString());

                                }

                                @Override
                                public void onFailure(Call<String> call, Throwable t) {

                                }
                            });

                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    } else {
        if (request.getLatLng() != null && !request.getLatLng().isEmpty()) {
            String[] latLng = request.getLatLng().split(",");
            LatLng orderLocation = new LatLng(Double.parseDouble(latLng[0]), Double.parseDouble(latLng[1]));
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.deliverybox);
            bitmap = Common.scaleBitmap(bitmap, 70, 70);

            MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                    .title("Order of " + Common.currentRequest.getPhone())
                    .position(orderLocation);

            mMap.addMarker(marker);
            mService.getDirections(mLastLocation.getLatitude() + "," + mLastLocation.getLongitude(),
                    orderLocation.latitude + "," + orderLocation.longitude)
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            new ParserTask().execute(response.body().toString());
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {

                        }
                    });
        }
    }
}

这里是我解析 Google 返回的 JSON 对象的地方

private class ParserTask extends AsyncTask<String, Integer, 
List<List<HashMap<String, String>>>> {

    ProgressDialog mDialog = new ProgressDialog(TrackingOrder.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mDialog.setMessage("Please waiting...");
        mDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... strings) {

        JSONObject jsonObject;
        List<List<HashMap<String, String>>> routes = null;
        try {
            jsonObject = new JSONObject(strings[0]);
            DirectionJSONParser parser = new DirectionJSONParser();

            routes = parser.parse(jsonObject);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return routes;

    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
        mDialog.dismiss();

        ArrayList points = null;
        PolylineOptions lineOptions = null;

        for (int i = 0; i < lists.size(); i++) {

            points = new ArrayList();
            lineOptions = new PolylineOptions();

            List<HashMap<String, String>> path = lists.get(i);

            for (int j = 0; j < path.size(); j++) {

                HashMap<String, String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));

                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            lineOptions.geodesic(true);
        }

        mMap.addPolyline(lineOptions);
    }
}

最后这是我的 DirectionJsonParser.java

public class DirectionJSONParser {

/**
 * Receives a JSONObject and returns a list of lists containing latitude and longitude
 */
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for (int i = 0; i < jRoutes.length(); i++) {
            jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {
                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for (int k = 0; k < jSteps.length(); k++) {
                    String polyline = "";
                    polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                    List list = decodePoly(polyline);

                    /** Traversing all points */
                    for (int l = 0; l < list.size(); l++) {
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
                        hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
    }

    return routes;
}

/**
 * Method to decode polyline points
 * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
 */
private List decodePoly(String encoded) {
    List poly = new ArrayList();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}
}

最佳答案

在你得到两点之间的路线后,你会得到这样的距离和持续时间

JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObjects = legs.getJSONObject(0);

//get the distance
JSONObject distance = legsObjects.getJSONObject("distance");
String distance = distance.getString("text");

//get the time
JSONObject time = legsObjects.getJSONObject("duration");
String duration = time.getString("text");

关于java - 如何获取 Google 返回的 JSON 对象中的持续时间和距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491798/

相关文章:

java - Android Studio(增加最终变量)

java - 将回调传递给 Java 中的特定函数

机器人 : Relative layout width wrap_content

java - 谷歌上次更新后方向 API 谷歌地图出现问题

java - 如何确定并更改用于执行的 Java Maven 版本?

android - 为什么我的 MediaPlayer 音频失真/削波?

java - 具有 unboundID 的 Ldap SASL

api - 如何在 Google Maps Directions api 中获取所有公交站?

javascript - 未处理的 promise 拒绝: TypeError: undefined is not a function evaluating 'departureloc.map' occurs when mapping for setState in react native

java - 在 Java 中将位 vector ( boolean 数组)转换为整数,并将整数转换为位 vector