Month: June 2016

Add Google Maps to your app!

Below, I am going to demonstrate how to add the google maps utility to your android application in Android Studio.

Install Google Play Services package in Android Sdk Manager

In Tools->Android->SDK manager , click on SDK Tools and install Google Play Services package if not installed.

Screenshot

In build.gradle file, add the latest version of google-play services under dependencies

dependencies {
      compile 'com.google.android.gms:play-services:9.0.2'
}

Get Google API Key

In order to use the Google Maps Android API, the app project needs to be registered on Google Developers console and a Google API key is obtained which needs to be added in the app.
The steps for this are mentioned below:

  • The first time you build your android project, a debug keystore file is created and found in the following locations:
Windows : C:\Users\your_user_name\.android\
OS x & Linux : ~/.android/
  • Go to the java jdk location on your system and list the SHA-1 fingerprint through the following commands:
Windows : keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
OS x & Linux : keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

The line that starts from SHA1 contains the fingerprint, a sequence of 20 two-digit hexadecimal numbers separated by colons.

  • Click on below link to go to the Google Developer Console

Developer Console
Either select an existing project, or create a new one, click on continue – this enables the API
Click on Go to Credentials to set the API key and click on add package name and fingerprint.
Capture
Enter the package name and the fingerprint and click on create. A new api key is generated starting with ‘AIza’.

Add the following permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Also add the API key obtained from the google console to the manifest file like below:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIza*****" />

In order to display google maps , Google provides a GoogleMap & MapFragment API. Create an object of GoogleMap & get its reference from the layout file, as shown below:

layout file : 

<fragment
    android:id="@+id/myMap"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Activity file : 

GoogleMap googleMap;
googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.myMap)).getMap();

Sample code is available in github.