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:
That will include the entire Google services to your app.
Be sure to include the latest version by checking this link:
Because each app uses Google Play services differently, it's up to you decide the appropriate place in your app to…developers.google.com
Then in your gradle.properties, add your Google Maps key like this:
You can generate the Key by clicking in the GET KEY button in this tutorial:
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:
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:
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.