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

时间:2019-04-03 09:33:29

标签: java android google-maps-direction-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;
}
}

1 个答案:

答案 0 :(得分:1)

获得两点之间的路线后,您将得到如下距离和持续时间

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");