I’m writing this post to demystify how to render polylines along with Google Map routes. Also, I’ll walk through you how to show interactive Polylines on Google Maps, when the user adds origin and destination address. We’re going to use GoogleMaps SDK for displaying maps. Google Direction API for getting the routes from a source address to final address.

This is how our application looks after the completion of this post.

For the full code go to end of this post 👇.

Prerequisite

Before we get started, we’ll need to get the Google Maps and Google Direction API key, instructions on how to get keys can be found here and here respectively.

Get Started

In Android Studio after creating an Empty Activity project, we first need to add the following dependency in our app-level build.gradle file.

// Google dependencies implementation 'com.google.android.gms:play-services-maps:16.0.0' .... ....

Hit the Sync button, so the Studio will download the dependency for your project.

Show Google Maps

The Google Maps SDK has the complete set of features that you would need to display the Markers, Current Location, Polylines, etc. You can check the complete set of features and documentation on their developer’s page.

Code

We’ll begin by showing the Google Maps on Android Activity. First, we need to add the following fragment tag inside the activity.xml file.

<fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mapFragment" class="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/>

Line 4 added the class of SupportMapFragment for showing Google Maps. Retrieve the reference of mapFragment inside the Activity class and initialize the map like below.

class MyActivity extends AppCompatActivity { private GoogleMap googleMap; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment); mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; } }); } }

The default Google Maps will be shown after adding the above code.

Google Direction API

Google provides API that calculates direction between locations and shows the route path of how to travel from source to destination address. You can even use various transportation modes (public transportation, walking, or cycling, driving — this is the default mode).

Complete documentaion can be found here.

The Json returned by Google Direction API would look like this. Also, if you want to look at the Encoded Polyline Algorithm see this link.

Therefore, we need something to decode the above Json response in order to show the route in our app. So, I’ve already added the directionModule inside my GitHub repo you can follow me by looking at the code.

Download Directions

Next, we need to execute a network request to download the directions from origin to destination coordinates.

private void fetchDirections(String origin, String destination) { try { new DirectionFinder(this, origin, destination).execute(); // 1 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override // 2 public void onDirectionFinderSuccess(List<Route> routes) { if (routes.isEmpty()) return; // 3 try { for (Route route : routes) { PolylineOptions polylineOptions = getDefaultPolyLines(route.points); // 4 polyline = googleMap.addPolyline(polylineOptions); // 5 } } catch (Exception e) { Toast.makeText(this, "Error occurred on finding the directions...", Toast.LENGTH_SHORT).show(); } }

Understanding the above code step-by-step.

Passing the origin and destination address to DirectionFinder utility class. The execute method will simply download the Json data synchronously. The overriding onDirectionFinderSuccess method will be called when the direction routes are ready. Simply return if the collection of route is empty. You’ll find the getDefaultPolylines method inside the GoogleMapHelper util class. This method simply creates the PolylineOptions with the provided LatLng. Draw a route on the map by adding the PolylineOptions on the googleMap instance.

Styling the Google Maps Polylines

Once we’ve finished with showing the route on the map with blue plain Polyline between source and destination address. We can easily style our route when constructing the PolylineOptions. Let’s see an example of how to create dotted polylines on the map.

private static final int PATTERN_GAP_LENGTH_PX = 10; // 1 private static final Gap GAP = new Gap(PATTERN_GAP_LENGTH_PX); private static final Dot DOT = new Dot(); private static final List<PatternItem> PATTERN_DOTTED = Arrays.asList(DOT, GAP); // 2 static PolylineOptions getDottedPolylines(List<LatLng> points) { PolylineOptions polylineOptions = new PolylineOptions() .color(Color.BLUE) // 3 .pattern(PATTERN_DOTTED); // 4 for (LatLng point : points) polylineOptions.add(point); // 5 return polylineOptions; }

Taking each commented section in turn.

Space between every dot in polylines. Creating a collection of PatternItem with Dot and Gap. Setting the blue color for dotted polylines. This method only accepts 32-bit ARGB color. Registering the pattern for polylines. Finally, adds every point to the end of the route.

Next, if you want to show a simple Plain route instead of Dotted just remove the pattern method from the above code.

You can get the complete code of above application from GitHub. Here’s the link.

And that’s all for now! Thank you for being here and keep reading…