All CategoriesAndroid App Development

How to Draw a Path on Google Maps

As seen on Google Maps, once we enter directions the application plots the best path between those two locations. We can also do this in our Android applications by using Google Map Android API and Directions API.
It is actually pretty easy to draw paths between two or more points and locations on Google Map.
Here, in this example, we are going to create an Application that shows the current location of the user, and we choose two locations fed in by the user, one is the starting point, and the other is the destination. We then see that a marker is added and the path is drawn between these two points.
Let’s see by following some simple steps.

Example with Code

  1. Create an Application DrawPathOnGoogleMapExampleAndroid in Android Studio with the updated version.
  2. Choose GoogleMapsActivity when creating an Activity.
  3. After successfully creating the project, open the res/values/google_maps_api.xml
  4. Next, copy the link from this file and open it in the browser to obtain the API key by creating a project on the console.


Copy the link from this file as shown in the screenshot above.

  1. Create an API Key From the Console

  • From the screenshots shown above, we can see that the Google Maps key or API key is created
  • Now, copy the API key and paste it in the xml file.

2.Next, Enable the Google Maps Directions API from the Library on the Console

  • Click on Enable to activate this key
  • Open your project in Android Studio
  • Add permissions in AndroidManifest.xml file

AndroidManifest.xml

Add permissions here:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

build.gradle

After creating the GoogleMapsActivity, check that the Google Play services dependency is added or not with the updated version in this file.

dependencies {
    compile 'com.google.android.gms:play-services:9.8.0'
}

Create the Java class DataParser.java and do the implementation in MapsActivity.java.

activity_maps.xml

This is the layout of our MapsActivity. By default, it shows the Map fragment when we choose GoogleMapsActivity.
Add the code here:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.shriyanshu.drawpathongooglemapexampleandroid.MapsActivity" />

 

DataParser.java

Create this class in your project.

Add the code here:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.shriyanshu.drawpathongooglemapexampleandroid.MapsActivity" />

DataParser.java

Create this class in your project.

Add the code here:

public List<List<HashMap<String,String>>> parse(JSONObject jObject){
    List<List<HashMap<String, String>>> routes = new ArrayList<>() ;
    JSONArray jRoutes;
    JSONArray jLegs;
    JSONArray jSteps;
    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<>();
            /** 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<LatLng> list = decodePoly(polyline);
                    /** Traversing all points */
                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<>();
                        hm.put("lat", Double.toString((list.get(l)).latitude) );
                        hm.put("lng", Double.toString((list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

Here, it receives a JSON Object and returns a list which contains the latitude and longitude.

private List<LatLng> decodePoly(String encoded) {
    List<LatLng> 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;
}

This is a method which is used to decode polyline points from Google Maps Directions API with Java.

MapsActivity.java

This is our Map Activity which extends FragmentActivity and implements OnMapReadyCallback interface, its overridden method is onMapReady(..). Here, we will show the current location of the user and draw the path between two locations as we discussed above.

  1. Initialize

    private GoogleMap mMap;
    ArrayList<LatLng> MarkerPoints;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    
  2. Add the code in onMapReady(..) methodHere, it sets the click listener on Map, creates the MarkerOptions and sets the position of it. For the start position, a color of the marker is green and for the end position, the color is red. Also, get the URL and download the JSON data from Google Directions API.
    mMap = googleMap;
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
          MarkerOptions options = new MarkerOptions();
          options.position(point);
            if (MarkerPoints.size() == 1) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            } else if (MarkerPoints.size() == 2) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            mMap.addMarker(options);
            if (MarkerPoints.size() >= 2) {
                LatLng origin = MarkerPoints.get(0);
                LatLng dest = MarkerPoints.get(1);
                String url = getUrl(origin, dest);
                FetchUrl FetchUrl = new FetchUrl();
                FetchUrl.execute(url);
            }}
    });
    

    Now, build the URL by creating parameters inside the getURL() method.

    String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
    String sensor = "sensor=false";
    String parameters = str_origin + "&" + str_dest + "&" + sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
    

    Next, to create a method, download the JSON data from the URL by adding an HTTP connection which communicates with URL.
    After that, fetch the data from URL passed.

    ParserTask parserTask = new ParserTask();
    parserTask.execute(result);
    

    Create this class to parse the data in JSON format.
    Add the code in onPostExecute() method.
    Here, it will draw the path on Google Map by traversing through all routes and add all the points in the route to LineOptions by using Google Maps PolyLineOptions and its method addAll().

    ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();
            List<HashMap<String, String>> path = result.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(10);
            lineOptions.color(Color.RED);
           }
    }
    

    Add the code in onLocationChanged() to show the current location of the user.

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    

    Download Source Code: GitHub

  3. Output


 Keep visiting www.acadgild.com for more updates on the technical and certification courses.

Suggested Reading

JSON vs XML

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close