5

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??

Rajat Mittal
  • 413
  • 5
  • 19
Darshi Patel
  • 294
  • 3
  • 11

4 Answers4

3

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

Amkhan
  • 340
  • 1
  • 3
  • 12
0

Using direction api you can achieve this. you just have to pass user inserted marker as waypoints as follow

https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY

you will get list of route which have the distance between to points

//retrofit

  @GET("https://maps.googleapis.com/maps/api/directions/json")
    Observable<DirectionResults> getDirectionWithWayPoints(@Query("origin") String origin, @Query("destination") String destination, @Query("waypoints") String wayPoints, @Query("key") String key);

// plotting logic

 api.getDirectionWithWayPoints(startPoint, endPoint, stringBuilder.toString(), getString(R.string.API_KEY))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeWith(new Observer<DirectionResults>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(DirectionResults directionResults) {
                                    hideDialog();
                                    if (null == directionResults) {
                                        return;
                                    }


                                    ArrayList<LatLng> routelist = new ArrayList<>();
                                    routelist.add(latLngStart);
                                    if (directionResults.getRoutes().size() > 0) {
                                        List<LatLng> decodelist;
                                        RoutesItem routeA = directionResults.getRoutes().get(0);

                                        if (routeA.getLegs().size() > 0) {

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


                                            List<StepsItem> steps = routeA.getLegs().get(j).getSteps();

                                            StepsItem step;
                                            Location location;
                                            String polyline;
                                            for (int i = 0; i < steps.size(); i++) {
                                                step = steps.get(i);


                                                polyline = step.getPolyline().getPoints();
                                                decodelist = DirectionsJSONParser.decodePoly(polyline);
                                                routelist.addAll(decodelist);


                                            }
                                        }
                                        }
                                    }

                                    if (routelist.size() > 0) {


                                        routelist.add(latLngEnd);

                                        rectLine = new PolylineOptions().width(12).color(
                                                Color.CYAN);

                                        for (int i = 0; i < routelist.size(); i++) {
                                            rectLine.add(routelist.get(i));
                                        }
                                        // Adding route on the map

                                        if (null != mMap) {
                                            mMap.addPolyline(rectLine);

                                            fixZoom(rectLine, mMap);
                                            getVehicleId();

                                        }
                                    }

                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideDialog();
                                    e.printStackTrace();
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }


            }
akshay_shahane
  • 4,423
  • 2
  • 17
  • 30
0

Google provides libraries out of the box for solving this kind of issues.

I would structure my application in following manner.

  1. Use Retrofit 2 for connecting to network. (https://square.github.io/retrofit/)
  2. Use google API's, you will need more than 1 API to achieve both of the tasks.

    2.a To find out distances between two points use Google Distance Matrix API (https://developers.google.com/maps/documentation/distance-matrix/start).

    2.b To add multiple markers you can refer to following answer Google Maps JS API v3 - Simple Multiple Marker Example

AbdulMueed
  • 1,327
  • 12
  • 19
0
For draw route you can use :

PolylineOptions options = new 
      PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
      for (int z = 0; z < list.size(); z++) {
      LatLng point = list.get(z);
      options.add(point);
    }
   line = myMap.addPolyline(options);

And calculating distance for usimg **Google Maps Direction API**