I’m writing this post to demystify how to render interactive polylines along with the Google Map routes to show origin and destination addresses. Before we get started, we need to install the following libraries into our android application.

  1. Google Maps Play Service
  2. Google Maps Service

After setting-up the above dependencies hit the sync button and we are good to go. You guys must be thinking about why do we add the

Google Maps Service dependency into ourbuild.gradle file. Later in the article, you guys will see it’ll help us to get the direction of polylines path with source and destination coordinates.

Here’s our final version of the App.

.

Rendering Android Google Native Maps

A simple way to render the Google maps is to create a new project from Android Studio. From pre-installed templates select the Google Maps Activity and you’ll get the basic setup.

maps direction api 1

Next step is to create the Google Maps API from Google Console and replaced it YOUR_API_KEY inside the AndroidManifext.xml file.

maps direction api 2

Now when all the prerequisites are done. Let’s get down to the real fun.

We’ll begin by showing Google Maps on Android Activity and for that add the following FramentContainerView tag inside your activity XML file.

<androidx.fragment.app.FragmentContainerView xmlns:android=“http://schemas.android.com/apk/res/android”
    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=“.MapsActivity” />

The SupportMapFragment class is for showing Google Maps. Now we’ll get the reference and map fragment and initialize the map like below.

val binding = ActivityMapsBinding.inflate(layoutInflater)  // 1
        setContentView(binding.root)
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment // 2
        mapFragment.getMapAsync {  // 3
        }

Here is the summary of the above code:

  1. Inflate the activity XML file with view binding. You can read more about view binding here.
  2. Obtain the SupportMapFragment and get notified when the map is ready to used.
  3. The getMapAsync callback will be called when the map is ready to used.

When you build and run the above code you’ll see the default Google Maps on screen.

Google Maps Direction API

Once we have rendered a map we can now proceed to mapping a route via Google Maps, but first we need Direction API. It calculate directions between locations and then we gonna show the polylines of route path on Google Maps. For calculating routes, fetches the direction data, and decoding polylines from Google we are gonna use the Google Map Service API. In order to use the maps service API we first need to GeoApiContext like following.

private val geoApiContext = GeoApiContext.Builder()
        .apiKey(“ALZ*********************apomh”)
        .build()

Replace the API KEY with the Google Direction API key.

Draw Polylines On Map

Now we can draw polylines on the map. Scroll down a bit copy and paste the following code inside the Activity onCreate method.

lifecycleScope.launch {    // 1
            val directionResult : DirectionResult? = withContext(Dispatchers.IO) {
                DirectionsApi.newRequest(geoApiContext)
                    .origin(SOURCE_COORDINATES).destination(DESTINATION_ADDRESS).suspendableAwait()
             }    // 2
            if (directionResult == null) {    // 3
                Toast.makeText([email protected], “Network error occurred”, Toast.LENGTH_SHORT)
                    .show()
                [email protected]
            }
            with(mMap) {  // 4
                addMarker(    // 5
                    MarkerOptions().position(
                        com.google.android.gms.maps.model.LatLng(
                            SOURCE_COORDINATES.lat, SOURCE_COORDINATES.lng
                        )
                    )
                )
                addMarker(   // 6
                    MarkerOptions().position(
                        com.google.android.gms.maps.model.LatLng(
                            DESTINATION_ADDRESS.lat, DESTINATION_ADDRESS.lng
                        )
                    )
                )
                val polylines = directionResult.routes.flatMap {   // 7
                    it.overviewPolyline.decodePath()
                }.map { com.google.android.gms.maps.model.LatLng(it.lat, it.lng) }
                mMap.addPolyline(PolylineOptions().addAll(polylines))   // 8
            }
        }

The above code is all we need to draw a line with several points on the UI.

  1. A coroutineScope confines new coroutines by providing a lifecycle-bound component that binds to a coroutine. Launch a new coroutine so that our main thread does not get blocked.
  2. The suspend functions can then call withContext(Dispatchers.IO) to delegate work to background threads, keeping the initial thread tied to the main thread. Requesting the DirectionResult with source and destination coordinates from the DirectionAPI.
  3. Show a toast if the user device is not connected to internet to some internal error occurred.
  4. Calls the Google Maps instance as receiver on the with block.
  5. Add the source marker on the map.
  6. Same as source added the destination marker on the map.
  7. Getting all routes from Direction API and merged them into a single List<LatLng>.
  8. Final in the last step add all the routes on the Google Maps and show polylines.

Well, not quite. There’s one more step to take. We just need to see the implementation of suspendableAwait .

suspend fun DirectionsApiRequest.suspendableAwait() =
    suspendCancellableCoroutine {
        try {
            val directionResult = await()
            it.resume(directionResult)
        } catch (e: Exception) {
            it.resume(null)
        }
    }

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.

PolylineOptions polylineOptions = new PolylineOptions()
                .color(Color.BLUE)
                .pattern(PATTERN_DOTTED);

It’ll show dotted polylines with the color blue. You can change any color you want.

To improve the app further, try allowing the user to select different transportation types or add different destination.

I hope you enjoyed this tutorial. If you have any questions or comments, please join the discussion below!