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.
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 MapsA 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.
Next step is to create the Google Maps API from Google Console and replaced it YOUR_API_KEY inside the AndroidManifext.xml
file.
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:
XML
file with view binding. You can read more about view binding here.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.
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.
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.
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.List<LatLng>
.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) } }
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!
Quick Links
Legal Stuff
Social Media