Home > Articles > Programming > Java

Accessing Google Maps in Android Apps

  • Print
  • + Share This
This article by Bintu Harwani, author of Android Programming Unleashed, explains how to use Google Maps Android API V2 in Android applications.
Like this article? We recommend

Like this article? We recommend

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020