Google Maps and Directions API using Kotlin
Law Gimenez
Posted on September 20, 2018
I will implement below on how to implement Google Maps and Directions API using Kotlin and we are going to plot a route from origin to destination. I am not gonna include here on how to get the API Key from the Google Maps Platform Console as Google has a clear directions about it.
We are going to assume that you have already obtained the API Key and already added the <meta-data>
in the AndroidManifest.xml.
In your gradle file, add the following lines below and then sync after.
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.maps.android:android-maps-utils:0.5'
In your XML layout add the following code anywhere you want. On my end I added it below the toolbar.
<fragment
android:id="@+id/fragment_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar"
/>
Then in your Activity, we need to implement OnMapReadyCallback
. Your activity should look like the one below.
class HomeActivity: AppCompatActivity(), OnMapReadyCallback {
private var googleMap: GoogleMap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
val mapFragment = supportFragmentManager.findFragmentById(R.id.fragment_map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap?) {
this.googleMap = googleMap
}
}
Run your project and it should display the Google Map.
Next we are going to plot a route from origin to destination. In your override method of onMapReady
add the following lines below.
val latLngOrigin = LatLng(10.3181466, 123.9029382) // Ayala
val latLngDestination = LatLng(10.311795,123.915864) // SM City
this.googleMap!!.addMarker(MarkerOptions().position(latLngOrigin).title("Ayala"))
this.googleMap!!.addMarker(MarkerOptions().position(latLngDestination).title("SM City"))
this.googleMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOrigin, 14.5f))
The following code block we created a variable latLngOrigin
as this will be the origin or starting point of our route. The variable latLngDestination
will be the destination or the end of the route. Next lines is adding the following variables as markers to the Google Map.
Directions API
We are going to use Google's Directions API so that we can calculate the route between two endpoints. Try to read and get familiar with the documentation.
Since we only have the coordinates, we can pass them to the Directions API like the one below. Replace your own API Key.
https://maps.googleapis.com/maps/api/directions/json?origin=10.3181466,123.9029382&destination=10.311795,123.915864&key=<YOUR_API_KEY>
The sample JSON response can be found in the documentation. So take a look at it.
Take note I also used Volley as my HTTP request library.
val path: MutableList<List<LatLng>> = ArrayList()
val urlDirections = "https://maps.googleapis.com/maps/api/directions/json?origin=10.3181466,123.9029382&destination=10.311795,123.915864&key=<YOUR_API_KEY>"
val directionsRequest = object : StringRequest(Request.Method.GET, urlDirections, Response.Listener<String> {
response ->
val jsonResponse = JSONObject(response)
// Get routes
val routes = jsonResponse.getJSONArray("routes")
val legs = routes.getJSONObject(0).getJSONArray("legs")
val steps = legs.getJSONObject(0).getJSONArray("steps")
for (i in 0 until steps.length()) {
val points = steps.getJSONObject(i).getJSONObject("polyline").getString("points")
path.add(PolyUtil.decode(points))
}
for (i in 0 until path.size) {
this.googleMap!!.addPolyline(PolylineOptions().addAll(path[i]).color(Color.RED))
}
}, Response.ErrorListener {
_ ->
}){}
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add(directionsRequest)
The following code block sends a HTTP GET request to the Directions API and we are going to parse the response. What we are going to need is the points
data from the polyline
object. Run the project and you should get a route plotted on your Google Map.
Posted on September 20, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.