Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw route and calculate distance between multiple markers on google map in android

In my app user can insert multiple location and show in map. How can i achieve this? I know how to draw route between two location but i want to draw route between multiple marker as like image. enter image description here

In image marker show location that is entered by user. I also want to calculate distance between marker like calculate distance between B to C and C to D.

How can I achieve this??

like image 567
Darshi Patel Avatar asked Oct 28 '22 18:10

Darshi Patel


1 Answers

Use direction api which return multi-part directions using a series of waypoints.

Direction api Documentation

private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

    private String getMapsApiDirectionsUrl() {
        String origin = "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude;
        String waypoints = "waypoints=optimize:true|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude + "|";
        String destination = "destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude;

        String sensor = "sensor=false";
        String params = origin + "&" + waypoints + "&"  + destination + "&" + sensor;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params;
        return url;
    }
}

When you get response from above request . you need to draw route from response

public void drawRoute(String result) {

    try {
        //Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        Polyline line = mMap.addPolyline(new PolylineOptions()
                .addAll(list)
                .width(12)
                .color(Color.parseColor("#05b1fb"))//Google maps blue color
                .geodesic(true)
        );

    } catch (JSONException e) {

    }
}  

You will get more detail of this from Draw-route-github

For Distance calculation you need to Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations

like image 109
Amkhan Avatar answered Nov 09 '22 05:11

Amkhan