How to Generate Route Between Two Locations in Google Map in Android?
Google Map or any other such applications have methods to generate a route between two locations. Generally, there are a lot of parameters like closest distance, the fastest distance, alternative routes, etc to suffice the needs. These apps are really appealing, but the developer knows the pain behind developing such beautiful applications.
Through this article, we will show you how you can generate a route between two locations in a Google Map in Android. Follow the below steps to begin.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add these dependencies and sync the project
// For Map fragment
// To make a call to for getting Coordinates response from a Web URL
Step 3: Add this permission in AndroidManifest.xml file
<uses-permission android:name=”android.permission.INTERNET” />
Step 4: Add this Google Map fragment in the activity_main.xml file
Step 5: Get and store your Places API Key
- Our application utilizes Google’s Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.
- Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?
Step 6: Retrieve & validate your key in MainActivity
After referring to the above two articles, you will have your API key called in the Main. To validate the key for using Map Fragment, add this code.
Step 7: Initialize the Map Fragment
After appending the below code, the IDE will want to extend the MainActivity to OnMapReadyCallback. Apply these changes. You will also need to implement the member functions now. The member function will be onMapReady. Once done, the code will have no errors.
Step 8: Get the coordinates of two places
We have manually declared the latitude and longitude values of two places, between whom we wish to generate a route. We declared them globally. But you can use your own methods to get those coordinates.
Step 9: Edit the onMapReady function
mMap is already declared in the global variable.
Now we shall change the onMapReady call.
Step 10: Create a function to generate the direction URL
Step 11: Create a function to decode polyline
Step 12: Create a class for Map Parameters
The response when Step 10 is passed requires an instance of the object to catch the JSON. This class is that object.
Step 13: Create an inner class to pass the URL string generated in Step 8 and call the decode polyline function
Complete Source Codes:
Download the Source Code from here.