как получить общее расстояние и продолжительность между двумя местоположениями вместе с путевой точкой на карте Google

Я хочу получить общую продолжительность и расстояние между двумя местоположениями вместе с путевыми точками. метод, который я использую, дает мне расстояние и продолжительность, но без путевых точек. так может ли кто-нибудь мне помочь? мой метод выглядит ниже ...

public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){


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&key="+getResources().getString(R.string.google_maps_server_key));
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
parsedDistance=distance.getString("text");
JSONObject duration= steps.getJSONObject("duration");
parsedDuration=duration.getString("text");
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});

thread.start();

try {
thread.join();
Toast.makeText(this, parsedDistance + " Distance", Toast.LENGTH_SHORT).show();
Toast.makeText(this, parsedDuration + " Duration", Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
e.printStackTrace();
}

return parsedDistance;
}

person Tushar Kotecha    schedule 28.04.2017    source источник


Ответы (3)


public void parseJson(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;
        long totalDistance = 0;
        int totalSeconds = 0;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /* Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");

                                /* Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");

                    totalDistance = totalDistance + Long.parseLong(jDistance.getString("value"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    totalSeconds = totalSeconds + Integer.parseInt(jDuration.getString("value"));

                }
            }

            double dist = totalDistance / 1000.0;
            Log.d("distance", "Calculated distance:" + dist);

            int days = totalSeconds / 86400;
            int hours = (totalSeconds - days * 86400) / 3600;
            int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
            int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;
            Log.d("duration", days + " days " + hours + " hours " + minutes + " mins" + seconds + " seconds");

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

JSONObject jObject = новый JSONObject (результат);

parseJson (jObject);

person gaurang    schedule 10.05.2017

Попробуйте приведенный ниже код, чтобы нарисовать точку пути на фрагменте карты и точках ArrayList = которые вы получаете из точек ответа api arrayList

PolylineOptions rectOptions = new PolylineOptions();
    LatLng polLatLng = null;
    if (points.size() > 0) {
        ArrayList<LatLng> pathPoint = new ArrayList<LatLng>();
        for (int k = 0; k < points.size(); k++) {
            double polLat = points.get(k).latitude;
            double polLng = points.get(k).longitude;
            pathPoint.add(new LatLng(polLat, polLng));
            polLatLng = new LatLng(polLat, polLng);
        }
        double startLatitude = points.get(0).latitude;
        double startLongitude = points.get(0).longitude;
        double endLatitude = points.get(points.size() - 1).latitude;
        double endLongitude = points.get(points.size() - 1).longitude;
        LatLng start = new LatLng(startLatitude, startLongitude);
        LatLng end = new LatLng(endLatitude, endLongitude);

        mMap.addMarker(new MarkerOptions().position(start).title("start"));
        mMap.addMarker(new MarkerOptions().position(end).title("end"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(polLatLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
        rectOptions.addAll(pathPoint);
        rectOptions.width(10);
        rectOptions.color(Color.BLUE);
        mMap.addPolyline(rectOptions);

mMap - это объект GoogleMap.

person Nikhil Sharma    schedule 28.04.2017
comment
я уже сделал это, вы не поняли мой вопрос ... я хочу продолжительность и расстояние, включая путевую точку - person Tushar Kotecha; 28.04.2017
comment
да, это то, что я написал в своем ответе - person Nikhil Sharma; 28.04.2017

Этот метод поможет вам определить расстояние от двух точек.

   Location.distanceBetween(double startLatitude, double startLongitude
                             ,double endLatitude, double endLongitude, float[] results);
person Ravi Varma    schedule 28.04.2017
comment
Вышеупомянутый метод дает мне тот же результат, но мне нужно расстояние и время, включая путевую точку - person Tushar Kotecha; 28.04.2017