Home > Articles > Programming > Java

Accessing Google Maps in Android Apps

  • Print
  • + Share This
  • 💬 Discuss
This article by Bintu Harwani, author of Android Programming Unleashed, explains how to use Google Maps Android API V2 in Android applications.

Google provides via Google play a library for using Google Maps in Android applications. You can use Google Maps Android API V2 in Android applications. The V2 version is an improved form of V1. In V1 version, MapView displayed map component, which is now deprecated, whereas the version V2 uses the MapFragment class for displaying the map component.

Following are the steps required to display Google maps in Android applications:

  1. Install the Google Play Services Library.
  2. Import Google Play Services Library into your workspace.
  3. Create the Android Project and reference the Google Play Services Library.
  4. Get the SHA1 fingerprint.
  5. Get the Maps API Key using the SHA1 fingerprint.
  6. Add permissions in the AndroidManifest.xml.
  7. Define MapFragment in the activity layout file.
  8. Write code in the Java activity file to display Google Map.

Install the Google Play Services Library

The first step in using Google Maps v2 for Android is to download the Google Play Services SDK. The Google Play Services SDK contains the APIs needed by Google maps, so you need to download it and reference it in your Android application. Use the following steps to download Google Plays Services SDK:

  1. Launch Eclipse, select the Windows > Android SDK Manager option.
  2. Check the Google Play services check box located under the Extras node (see Figure 1).
  3. Click the Install 1 package... button. The Google Play services library will be installed into the following folder of your computer:
<android-sdk-
folder>/extras/google/google_play_services/libproject/google-play-
services_lib

Figure 1 Android SDK Manager window for installing Google Play services

Import the Google Play Services Library Project into Your Workspace

The next step is to import the Google Play Services Library into your workspace so that it can be referenced in your Android project. Following are the steps to import Google Play Service Library:

  1. In Eclipse, select the File > Import... option.
  2. Select Android > Existing Android Code, and browse to the location of the Google Play Services Library. Recall, the Google Play Services Library is installed in the following folder:
  3. <android-sdk-
    folder>/extras/google/google_play_services/libproject/google-play-
    services_lib
  4. In the Import Projects dialog, check the Copy Projects into Workspace option and then click Finish (see Figure 2).

Figure 2 Import the Projects dialog for importing the Google Play Services Library into the workspace

The google-play-services_lib project will be imported into your workspace. The next step is to reference this library into the Android project.

Create the Android Project

You can now create an Android Project to use the new Google Maps Android API v2. Launch Eclipse, create an Android Application Project, and set its Minimum Required SDK, Target SDK, and Compile With drop-down lists to the values shown in Figure 3.

Figure 3 Dialog box for creating a new Android project

  • Click the Next buttons accepting the default for the following dialogs in the wizard. In the dialog that asks to create an activity, name the activity GoogleMapAppActivity and click the Finish button. The Android project will be created, and the ADT will automatically create all the necessary files.
  • To reference the Google Play Services Library in the Android project, right-click the project in Package Explorer window, and select the Properties option.
  • Select the Android node on the left, and click the Add... button on the right.
  • Select the google-play-services_lib project, and click the Apply button; then click OK (see Figure 4).

Figure 4 Referencing the Google Play Services Library in the Android project

Get SHA1 Fingerprint

To use Google maps you need to create a valid Google Maps API key. The key is free and can be obtained from the Google APIS Console. At the Google APIS console, you have to provide your application's SHA1 fingerprint and the application package name.

Eclipse automatically creates and uses a debug key, that is, it automatically creates a debug keystore for you. You can create the SHA1 for your debug keystore using the keytool command. Alternatively, you can get the SHA1 fingerprint from the project's preferences. Open the Preferences dialog by selecting the Window > Preferences option. Expand Android > Build node and copy the SHA1 fingerprint (see Figure 5).

Figure 5 Preferences dialog showing the SHA1 fingerprint

Get the Maps API Key Using SHA1 Fingerprint

To enable Google Maps v2 for Android and to get the Maps API key, you need to open the Google APIs Console by pointing the browser at the following URL, https://code.google.com/apis/console. Sign in with your Google account. A Dashboard opens showing the Project Summary of an API Project. A project name and a project number is generated by default, as shown in Figure 6.

Figure 6 Browser displaying Google APIs Console

From the list of services available, locate the Google Maps Android API v2 item, and turn on the service (see Figure 7).

Figure 7 Enabling the Google Maps Android API v2 services

After enabling the Google Maps Android API v2 services, click the API Access link on the left, and click the Create new Android key… button.

In the dialog that opens, enter the SHA1 fingerprint that you obtained in the earlier step followed by a ";" and the package name of your project. Click Create button (see Figure 8).

Figure 8 Generating Google Maps API key

The Google Maps API key will be generated. Copy the key and save it because you will soon need it.

Next, add permissions in the Android project so that it can access Google Map and the Internet. In Eclipse, open the AndroidManifest.xml file, and write the code as shown in Listing 1 to use Google Maps. Only the code in bold is the added code; the rest is the default code that is auto-generated by the ADT-plug-in.

Listing 1: Code in the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.pearsonarticles.googlemapapp"
   android:versionCode="1"
   android:versionName="1.0" >
   <uses-sdk
      android:minSdkVersion="14"
      android:targetSdkVersion="18" />
   <permission
      android:name="com.pearsonarticles.googlemapapp.permission.MAPS_RECEIVE"
      android:protectionLevel="signature" />
   <uses-permission  
      android:name="com.pearsonarticles.googlemapapp.permission.MAPS_RECEIVE"/>   
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name= 
      "com.google.android.providers.gsf.permission.READ_GSERVICES" />
   <uses-permission android:name= "android.permission.ACCESS_COARSE_LOCATION" />  #1
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />     #2
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.pearsonarticles.googlemapapp.GoogleMapAppActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <meta-data  android:name="com.google.android.maps.v2.API_KEY" 
         android:value="AIzaSyA3UR4FZFQWw9zIb9WlwacPPAb5g38tXMI" 
   />
   </application>
</manifest>

The permissions represented through statements #1 and #2 are not required to use Google Maps Android API v2 but are recommended. The main thing to observe in the preceding code is that the Google API key is added to the AndroidManifest.xml file via <meta-data> element.

Because Google Maps Android API V2 uses the MapFragment for displaying map component, you need to define it in the activity layout file. Open the activity layout file, activity_google_map_app.xml, and write the code as shown in Listing 2 in it.

Listing 2: Code in the activity layout file, activity_google_map_app.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".GoogleMapAppActivity" >
   <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>

To display the default Google Map, you don’t need to modify the Java activity file. The default code in the Java activity file, GoogleMapAppActivity.java, appears as shown in Listing 3.

Listing 3: Code in the Java activity file, GoogleMapAppActivity.java file

package com.pearsonarticles.googlemapapp;

import android.os.Bundle;
import android.app.Activity;
public class GoogleMapAppActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map_app);
    }
}

Your application and is ready to run. Deploy the application onto a real Android device. At the moment, the Android emulator does not support Google Maps v2 for Android because it needs access to Google Play on the emulator. On running the application, the default Google map appears, as shown in Figure 9 (left). When you switch the device to landscape mode, the map appears as shown in Figure 9 (right).

Figure 9 (left) Displaying the Google map when a device is in portrait mode; (right) Google map when a device switches to landscape mode

You can make your application display the wanted location on the Google map on startup. The only thing that you have to do is to supply the longitude and latitude values of that location. For example, to display San Francisco on the Google map by default, you need to create a LatLng instance, and you need to pass San Francisco’s latitude and longitude values to it. Thereafter, the moveCamera() method is called on the GoogleMap instance to focus on the location specified through the LatLng instance.

To display the San Francisco on Google Map by default, modify the Java activity file; GoogleMapAppActivity.java will appear as shown in Listing 4.

Listing 4: Code in the Java activity file, GoogleMapAppActivity.java file

package com.pearsonarticles.googlemapapp;

import android.os.Bundle;
import android.app.Activity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;

public class GoogleMapAppActivity extends Activity {
    private GoogleMap map;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map_app);
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
               .getMap();
       LatLng latLng = new LatLng(37.775, -122.4183333);
       map.setMapType(GoogleMap.MAP_TYPE_NORMAL);             #1
       map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    }
}

The MapFragment class extends the Fragment class and provides the life-cycle management and the services for displaying a GoogleMap widget. GoogleMap is the class that shows the map. The setMapType and moveCamera methods of the GoogleMap class are used to define the map type and move the camera instantly to the specified latitude and longitude location with the given zoom value. The map will appear as shown in Figure 10 (left). For changing the Google map to Satellite type, modify the statement #1 to the following:

map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

In the Satellite mode, the Google map will appear as shown in Figure 10 (middle). Similarly, to change the Google map type to Terrain mode, modify the statement #1 to appear as shown here:

map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

In Terrain mode, the Google map will appear as shown in Figure 10 (right).

Figure 10 (left)Google map in NORMAL mode; (middle) Google map in ATELLITE mode; and (right) Google map in TERRAIN mode

Displaying the Marker on the Map

To display the marker on the Google map, copy an image that will represent the marker in all the drawable folders of the project. Assuming the image filename is spot.png, copy it to the drawable folders of the project and modify the Java activity file, GoogleMapAppActivity.java, to appear as shown in Listing 5.

Listing 5: Code in the Java activity file, GoogleMapAppActivity.java file

package com.pearsonarticles.googlemapapp;

import android.os.Bundle;
import android.app.Activity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class GoogleMapAppActivity extends Activity {
    private GoogleMap map;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map_app);
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
       LatLng SanFrlatLng = new LatLng(37.775, -122.4183333);
       map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
       map.moveCamera(CameraUpdateFactory.newLatLngZoom(SanFrlatLng, 15));  
       if (map!=null){
           Marker sanfr = map.addMarker(new MarkerOptions().position(SanFrlatLng)
          .title("St San Francisco")
          .icon(BitmapDescriptorFactory
          .fromResource(R.drawable.spot)));
       }
    }
}

The Marker class is used for creating markers on the map. An instance sanfr of the Marker class is created that accesses the spot.png file from the drawable folder and displays it at the location specified through the LatLng instance, SanFrlatLng. On running the application, you find a marker pointing at San Francisco, as shown in Figure 11.

Figure 11 Google map with marker on San Francisco

Summary

You've learned how to use Google Maps v2 for Android to display Google maps in Android applications. You also learned to display wanted locations on Google map by default. Finally, you saw the procedure to display markers on the Google map.

For more interesting programs, check out my book Android Programming Unleashed. The book uses a step-by-step approach to explore the features of this amazing smartphone platform.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus