How to setup a Google map on an Android application in the smart way?

Nowadays, most of Android applications integrate an Android Map. In this article, I will give you the all process on how to do it, and some tricks to increase it reusability inside your application.

The basic setup

First, you need to include the Google play services. Because this Google library is quite huge and we are using only map, it is better to include only the maps services like this:

compile 'com.google.android.gms:play-services-maps:10.2.0'

Rather than:

compile 'com.google.android.gms:play-services:10.2.0'

That will include the entire Google services to your app.

Be sure to include the latest version by checking this link:

Then in your gradle.properties, add your Google Maps key like this:

GOOGLE_MAPS_API_KEY=xxxxxxxxxxxxxxxxxxxx

You can generate the Key by clicking in the GET KEY button in this tutorial:

https://developers.google.com/maps/documentation/android-api

Then in your module build.gradle add this line in android > defaultConfig:

resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")

Then in your manifest in your application tag add these two meta data:

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

At this stage, your application should compile without errors.

Include your map

For this part, we are gonna do something counter intuitive, we are gonna create a custom view. This implementation will give us these advantages:

  • It will be very easy to include a map later on our application.
  • It will fit our business logic every time and we don’t have to know the Google map API to use it.
  • If we want to move to an other map provider, we only have to reimplement this view.
  • If you have one map that work on your application, you can guaranty that the other maps will work.

This will give us the following component:

Map View

This component is decomposed in 3 part:

  • Line 48 to 51, the Google map is added as a fragment to the component.
  • Line 53 to 56, a Google map RxJava2 Subject is created. This is required because the Google map API is async, so we use Rx to get rid of this async constraint.
  • Line 60 to 67, a public method is created to expose our business need. In this case, we need to be able to add a marker to the map. To do it we subscribe to the map subject to get a GoogleMap Object when it one is ready. Then we use the GoogleMap API to add a market to it.

And that’s it, I hope you enjoyed this article. If you have any questions, you can contact me using my linkedin, my twitter or in the comment section below.