Draw Routes between multiple points on map
Asked Answered
H

3

7

I am new to android. I want to draw routes between multiple markers. I a, getting latitude, longitude and datetime from server. Now i want to show route between the points. I have stored them in arraylist. Here is how i am getting the points in async task doInBackground().

  newLatt= new ArrayList<String>();
  newLongg= new ArrayList<String>();
  newdatTime= new ArrayList<String>();

  JSONArray arr = new JSONArray(strServerResponse);
  for (int i = 0; i < arr.length(); i++) {
        JSONObject jsonObj1 = arr.getJSONObject(i);
        String status = jsonObj1.optString("status");
        if (status!="false"){
          Pojo pojo = new Pojo();
          String latitude = jsonObj1.optString("Latitude");
          String longitude = jsonObj1.optString("Longitude");
          String date_time = jsonObj1.optString("date_time");
          newLatt.add(latitude);
          newLongg.add(longitude);
          newdatTime.add(date_time);
       }else {
              Handler handler = new Handler(Looper.getMainLooper());
              handler.post(new Runnable() {
              @Override
              public void run() {
                   AlertDialog alertDialog = new AlertDialog.Builder(
                   MapActivity.this).create();
                   alertDialog.setMessage("Locations Not Available");
                   alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                   }
                   });
                    alertDialog.show();
                  }
               }
       );
     }

and in postExecute() method i am showing markers

        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        map = supportMapFragment.getMap();
        map.setMyLocationEnabled(true);
        if (newLatt.size()>0){
            for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                String dattme = newdatTime.get(i);
                dest = new LatLng(lati, longi);
                if (map != null) {
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(dest);
                    map.moveCamera(CameraUpdateFactory.newLatLng(dest));
                    map.animateCamera(CameraUpdateFactory.zoomTo(15));

                    markerOptions.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    markerOptions.title("" + dattme);
                    map.addMarker(markerOptions);
                    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            marker.showInfoWindow();
                            return false;
                        }
                    });

UPDATE

 PolylineOptions rectOptions = new PolylineOptions();
        //this is the color of route
        rectOptions.color(Color.argb(255, 85, 166, 27));
        LatLng startLatLng = null;
        LatLng endLatLng = null;
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        map = supportMapFragment.getMap();
        map.setMyLocationEnabled(true);
        if (newLatt.size()>0){
            for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                String dattme = newdatTime.get(i);
                dest = new LatLng(lati, longi);
                if (map != null) {
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(dest);
                    map.moveCamera(CameraUpdateFactory.newLatLng(dest));
                    map.animateCamera(CameraUpdateFactory.zoomTo(15));

                    markerOptions.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    markerOptions.title("" + dattme);
                    map.addMarker(markerOptions);
                    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            marker.showInfoWindow();
                            return false;
                        }
                    });

                        LatLng latlng = new LatLng(lati,
                                longi);
                        if (i == 0) {
                            startLatLng = latlng;
                        }
                        if (i == newLatt.size() - 1) {
                            endLatLng = latlng;
                        }
                        rectOptions.add(latlng);
                    String url = getDirectionsUrl(startLatLng, endLatLng);
                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);
                }

            }
            map.addPolyline(rectOptions);

getDirections:

    private String getDirectionsUrl(LatLng origin, LatLng dest) {
    // Origin of route
    String str_origin = "origin=" + origin.latitude + ","
            + origin.longitude;

    // Destination of route
    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin + "&" + str_dest + "&" + sensor;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + parameters;

    return url;
}
Hanaper answered 8/10, 2015 at 9:53 Comment(0)
S
2

In your postExecute add the following code to add ploylines on the map.

                PolylineOptions rectOptions = new PolylineOptions();
                //this is the color of route
                rectOptions.color(Color.argb(255, 85, 166, 27));

                LatLng startLatLng = null;
                LatLng endLatLng = null;
                for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                    LatLng latlng = new LatLng(lati,
                            longi);
                    if (i == 0) {
                        startLatLng = latlng;
                    }
                    if (i == jArr.length() - 1) {
                        endLatLng = latlng;
                    }
                    rectOptions.add(latlng);
                }
                map.addPolyline(rectOptions);

Happy coding...

Schultz answered 8/10, 2015 at 10:20 Comment(5)
Log the size of newLatt. U are getting a straight line cuz u probably have only two lat lngs.Schultz
sorry that was my code piece. For u replace jArr.length() with newLatt.size()Schultz
Ya that should work fine. if u got what was expexted. Please upvoteSchultz
I am getting null pointer exception at String str_dest = "destination=" + dest.latitude + "," + dest.longitude; in getDirectionsurlHanaper
Let us continue this discussion in chat.Schultz
S
0
Android does not provide embedded direction service in google map api. To draw route between points you must use google direction services REST API .
You can get complete code and description from http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/


ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                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);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
            }

            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
Sihunn answered 8/10, 2015 at 10:6 Comment(2)
Yes i know this. but i have latitude and longitude in arraylist, How to access them to show route??Hanaper
your list have hash map ?Sihunn
S
0

In case anyone lands here like me, turns out you can use Google map's library to conveniently draw a route on the map using PolyUtil class.

Short Version

Add the google maps library - 'com.google.maps:google-maps-services:0.1.20'

Then,

val directionResponse = apiInterface.getDirection(fromLatLng, toLatLng)
val decodedPaths = PolyUtil.decode(directionResponse.routes.overviewPolyline.points)
map?.addPolyline(PolylineOptions().addAll(decodedPaths))

Long Version

First, add the library in your build.gradle file

implementation 'com.google.maps:google-maps-services:0.1.20'

Second, make the api call to direction url end point - https://maps.googleapis.com/maps/api/directions/json?query

The response has a property routes->overview_polyline->points

Third, pass the value in points field to utility method from google maps services method,

val decodedPaths = PolyUtil.decode(points)

Finally on your map, add it like this

map?.addPolyline(PolylineOptions().addAll(decodedPaths))

This will draw the path on the map. Hope this helps!

Schaffhausen answered 16/4 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.