Android

Developing Google Map Application
Apr 28, 2011
1

 

About This Article

Developing map based application is one of the must have product for new mobile devices. To develop map based application in Android, Google has provided map library as add on feature. This article explains about the map library and how to develop Google map based application in Android.

Scope:

This article is intended for novice users who want brief understanding on Android programming. This article guides you step by step on developing Google Maps Application. It assumes that the developer has already installed Android and necessary tools to develop application. It also assumes that the develeopr to be familiar with Java or familiar with Object Oriented Programming concepts.

Introduction

Android provides Google’s external map library “com.google.android.maps” as add-on for developing application based on Google API’s. Map library offers built-in map downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls.

This article assumes you are developing application using Eclipse IDE and Android plugin has been added in Eclipse IDE.

Installing Google API

Before starting developing Google Map Application, make sure that you have installed Google API add-on in Android SDK.

The Maps external library is not included in the standard Android library provided in the SDK. The Google APIs add-on provides the Maps library to develop, build, and run maps-based applications in the Android SDK.

To know whether Google API has been added in Android SDK, Launch the Android SDK and AVD Manager as shown in Figure 1.

Figure1:Launching Android SDK and AVD Manager

In case the Google APIs are not already installed, you will have to manually install them.

Choose the “Installed Options” section to see what is already installed and the “Available Packages” to download the additional APIs. Figure 2 shows that Google API has been added in Android SDK.

Figure2:Android SDK and AVD Manager
Creating the Project

With all the necessary requirements met, let’s start with developing application.

First create Google Map Project in Eclipse IDE as shown in Figure 3. Give desired project name and select desired target as Google APIs. It is important to use the “Google APIs” as the target since this option includes the Google extensions that allow you to use Google Maps.

If you cannot see the Google APIs option then you need to install it as described in Installing Google APIs section.

Figure3:GoogleMap Project Creation
Create AVD with Google APIs

After creating project you need to create device which supports Google APIs.

Launch the Android SDK and AVD Manager as shown in Figure 1. Select "Virtual devices”. Click the "New" button to create AVD. Dialog appears as shown in Figure 4.

Figure4:AVD Creation

Specify a name for the AVD and select one of the "Google APIs (Google Inc.)" target. Configure the other options and then click "Create AVD". New AVD for running the project has been created.

Obtaining Google API Key

Google map library gives Google map data for rendering the map. Since application access Google data, developer needs to register with Google web services.

Google Maps API Key is required for allowing Google API to access the web services which in turn provides the map data.

Registering for a Maps API Key is simple, free, and has two parts:

  1. Extract the MD5 fingerprint of the certificate.
  2. Registering the MD5 fingerprint of the certificate.
Extract the MD5 fingerprint of the certificate

To register for a Maps API Key, developer needs to provide MD5 fingerprint of the certificate that you will use to sign your application. Here we need to use two things.

debug.keystore

By default, build tools create the debug keystore in the active AVD directory. The location of the AVD directories varies by platform:

  • Windows Vista: C:\Users\\.android\debug.keystore
  • Windows XP: C:\Documents and Settings\\.android\debug.keystore
  • OS X and Linux: ~/.android/debug.keystorekeytool.exe
keytool.exe

You need to extract MD5 fingerprint using the keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. The keytool.exe file is usually present in the %JAVA_HOME%/bin directory for Windows or $JAVA_HOME/bin for Linux/OS X.

Since we are developing and debugging application in debug mode, we need to sign the application in debug mode i.e. SDK build tools will automatically sign your application using the debug certificate.

To sign the application we need to extract the MD5 fingerprint of the certificate and for this you need to use the debug.keystore file. If in case you are not able to locate the debug.keystore file, you can select Windows < Preferences < Android < Build in Eclipse IDE to check the path. Figure 5 shows the debug.keystore path in Eclipse IDE.

Figure5:debug.keystore location path

Once you have located the keystore, use this Keytool command to get the MD5 fingerprint of the debug certificate:

$ keytool -list -alias androiddebugkey -keystore .keystore -storepass android -keypass android

For example: $ keytool -list -alias androiddebugkey -keystore "C:\android\debug.keystore” -storepass android -keypass android

Register the MD5 fingerprint of the certificate

The output of the keytool would be something like the one shown in Figure 6.

Figure6:Extracting MD5 fingerprint

Copy the MD5 Certificate and open your web browser to http://code.google.com/android/maps-api-signup.html

As shown in Figure 7, agree to the terms and conditions of the Google API and enter the MD5 fingerprint of the certificate.

Figure7:Generating API Key

Click on the “Generate API Key” button to generate the API Key. The generated API Key is shown in Figure 8.

Figure8:API Key Generated
Modify AndroidManifest.xml

Now to access Google Map in your application, developer needs to modify the AndroidManifest.xml file with the following

Add Permissions

You need to add the Internet permissions using tag element. The permissions required are:

  • android.permission.ACCESS_COARSE_LOCATION
  • android.permission.ACCESS_FINE_LOCATION - android.permission.INTERNET
Add Library

You also need to add the Google map library using tag element. This is so because Google map library is not a part of the standard library.

The final AndroidManifest.xml file is shown in Figure 9.

Figure9:AndroidManifest.xml file

As you can see is placed outside the element and element inside the element.

Modify main.xml

Now open the main.xml file present in the res\layout folder of the project. Developer need to use the element to display the Google Maps in your activity. Use element to position the map within the activity.

The modified main.xml is shown in Figure 10.

Figure10:main.xml file

As you can see the Google Map API Key is entered in main.xml file.

Create GoogleMap Activity

Rendering map in the application is achieved by extending the MapActivity class instead of Activity class.

A MapActivity is actually a base class with code to manage the boring necessities of any activity that displays a MapView. Activity responsibilities include:

  • Activity lifecycle management
  • Setup and teardown of services behind a MapView

To extend from MapActivity we have to implement the isRouteDisplayed method, which denotes whether or not to display any kind of route information, such as traffic, satellite, street view information. We will not provide such information, so we just return false there.

Kindly have a look at the Google Map API documentation before proceeding. The GoogleMap class is shown in Figure 11.

Figure11:GoogleMap MapActivity Class
Deploy Application

For deploying the application on emulator press F11 in Eclipse IDE. The output is shown in Figure 12.

As you can see the map is rendered in the application as well as the built in zoom controls is added for zooming in and out of the map.

Figure12:GoogleMap Application Output
Changing Views of the Map

By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:

mapView.setSatellite(true);

You can also display the map in street view, using the setStreetView() method:

mapView.setStreetView(true);

Figure 13 shows the Google Maps displayed in satellite and street views, respectively.

Figure13:Map Views
Displaying a Particular Location

Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.

As shown in Figure 14, a MapController from the MapView is obtained. Then GeoPoint object is used to represent a geographical location. The latitude and longitude of a location for GeoPoint class are represented in micro degrees (stored as integer values).

To navigate the map to a particular location, we need to use the animateTo() method of the MapController class and setzoom() method to set the zoom level.

Figure14:MapView Controller Code

The output is shown in Figure 15. The GeoPoint coordinates represents the city of Mexico.

Figure15:Displaying Particular Location
Adding Overlay Items

So far we have seen the map, but you may wish to create and add markers, layovers to the map to indicate places of interests.

We will now add marker to the map. First, we need image to indicate marker. Copy Figure 16 and add it into the res/drawable folder of the project. This is shown in Figure 17.

Figure16:marker icon
Figure17:res folders structure

To add a marker to the map, you first need to define a class that extends the Overlay class:

In the MapOverlay class that you have to defined, override the draw() method so that you can draw the pushpin image on the map. In particular, note that you need to translate the geographical location (represented by a GeoPoint object, p) into screen coordinates.

To add the marker, create an instance of the MapOverlap class and add it to the list of overlays available on the MapView object. Figure 18 shows the final code.

Figure18:GoogleMap.java

The output is shown in Figure 19.

Figure19:marker shown at desired location
GoogleMap Application

GoogleMap project files are shown below

main.xml
<!--l version="1.0" encoding="utf-8-->
<relativelayout android:layout_height="fill_parent" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"></relativelayout>
    <com.google.android.maps.mapview android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/mapView" android:apikey="YOUR API KEY HERE" android:clickable="true" android:enabled="true"></com.google.android.maps.mapview>        

AndroidManifest.xml
<!--l version="1.0" encoding="utf-8-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionname="1.0" android:versioncode="1" package="com.samsung.maps.google"></manifest>    
      <uses-sdk android:maxsdkversion="8" android:targetsdkversion="8" android:minsdkversion="8"></uses-sdk>              
	  <uses-permission android:name="android.permission.INTERNET"></uses-permission>
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>      
      <application android:label="@string/app_name" android:icon="@drawable/icon"></application>
        <uses-library android:name="com.google.android.maps"></uses-library>    
          <activity android:name=".GoogleMap" android:label="@string/app_name"></activity>
            <intent-filter></intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>
            
        
      

GoogleMap.java
package com.samsung.maps.google;

import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class GoogleMap extends MapActivity  {	
	MapView mapView;
	MapController mc;
	GeoPoint p;
	Resources res;
	Context context;
	MapOverlay mapOverlay;
	 
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)   {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        res = getResources();
        context = getApplicationContext();        
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mc = mapView.getController();
        p = new GeoPoint(19240000,-99120000);               
        mc.animateTo(p);
        mc.setZoom(8);         
        //Add location marker
        //MapOverlay mapOverlay = new MapOverlay();
        mapOverlay = new MapOverlay(p, res, context);
        List listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);         
        mapView.invalidate();
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}
MapOverlay.java
package com.samsung.maps.google;

import android.content.Context;
import android.content.res.Resources;
import com.google.android.maps.Overlay;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class MapOverlay extends Overlay {	
	Resources res;
	Context context;
	GeoPoint geoPoint;

	public MapOverlay(GeoPoint g, Resources r, Context c)	{
		super();
		res = r;
		context = c;
		geoPoint = g;
	}

	@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)   {
        super.draw(canvas, mapView, shadow);                   	 
        //translate the GeoPoint to screen pixels
        Point screenPts = new Point();
        mapView.getProjection().toPixels(geoPoint, screenPts);	 
        //add marker
        Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.androidmarker);            
        canvas.drawBitmap(bmp, screenPts.x, screenPts.y-58, null);         
        return true;
    }
    
    @Override
    public boolean onTap(GeoPoint p, MapView mapView) {	          
      AlertDialog.Builder dialog = new AlertDialog.Builder(context);
      dialog.setTitle("Hi");
      dialog.setMessage("Hi Im in Mexico");
      dialog.show();
      return true;
    }
}

go to top
Revision history
REVISION HISTORY DATE
First update Apr 28, 2011