Android Working with Google Maps

This article is outdated as Google Maps V1 is deprecated officially and no more supporting.

Consider reading updated article on Googe Maps Android Working with Google Maps V2

Google is providing an easy way to integrate Google Maps into your android applications. Today i am giving tutorial about embedding google maps in your android apps.

Download Code


Creating new project by selecting Google API SDK

While creating your project you need to select target SDK as Google API. If you don’t have one already download Google API SDK by opening your SDK Manager

1. Create a new project by going to File ⇒ New Android Project. Fill all the details, select Google API as target sdk and name your activity.

Android Google API SDK

2. As Google Map libraries are not part of Android libraries we need to mention library in AndroidManifest.xml file. Also we need to give permission to connect to internet. Open your AndroidManifest.xml file and modify as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.googlemaps"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <!--  Add Google Map Library -->
        <uses-library android:name="com.google.android.maps" />
        
        <activity
            android:label="@string/app_name"
            android:name=".AndroidGoogleMapsActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    <!-- Allow to connect with internet -->
    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

Obtaining Google Map Key

In order to use google maps you need to get map key. I am assuming you are working on windows PC. Now you need to get MD5 key from your jdk installation.

3. Open your command prompt by typing cmd in your run. Start ⇒ Run ⇒ type cmd.

c:\<path-to-jdk-dir>\bin\keytool.exe -list -alias androiddebugkey -keystore "C:\users\<user-name>\.android\debug.keystore" -storepass android -keypass android

below is how got my MD5 fingerprint

keytool.exe -list -alias androiddebugkey -keystore "C:\users\ravi\.android\debug.keystore" -storepass android -keypass android
android maps generating MD5

4. Now you need to get map key using MD5 fingerprint. Go to Sign Up for the Android Maps API and get your map key by giving MD5 fingerprint.

Android Google Map Key


Android Google Map Key

5. Now open your main.xml file under src ⇒ layout ⇒ main.xml and insert the following code. Don’t forgot to place your key.

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="05M-7qOGbEjYduPPUdQgJt9ysL8HToawGdvu_ow"
/>

6. Now open your MainActivity class and extend it from MapActivity.

public class AndroidGoogleMapsActivity extends MapActivity { 

7. After extending your activity from MapActivity you need to override isRouteDisplayed() and also set your default view to main.xml

package com.androidhive.googlemaps;

import android.os.Bundle;
import com.google.android.maps.MapActivity;

public class AndroidGoogleMapsActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}

8. Now run your project, you should see map displaying on your device. If don’t please redo all the steps above.

android google maps

Displaying Zooming Controls

Until now we have a static map with drag and move features only. We can add zooming controls in order to zoom in or zoom out maps. Google maps had inbuilt zooming controls, so all we need to do is call couple of lines.

package com.androidhive.googlemaps;

import android.os.Bundle;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class AndroidGoogleMapsActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Displaying Zooming controls
        MapView mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        
        
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
Android google Maps

Changing Map Display Type

You can also change map type like satellite, streetview etc.,

mapView.setSatellite(true); // Satellite View
mapView.setStreetView(true); // Street View
mapView.setTraffic(true); // Traffic View
Android google map types

Showing Location by passing Latitude and Longitude

Below code will show a location on the map by passing latitude and longitude of that location.

MapController mc = mapView.getController();
double lat = Double.parseDouble("48.85827758964043"); // latitude
double lon = Double.parseDouble("2.294543981552124"); // longitude
GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate(); 
Android google maps by latitude and longitude

Adding Marker on the map

For displaying marker on the map you need to create new class which extends ItemizedOverlay.
Create new class and name it as AddItemizedOverlay.java and write following code.

package com.androidhive.googlemaps;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
	   
	   private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
	   
	   private Context context;
	   
	   public AddItemizedOverlay(Drawable defaultMarker) {
	        super(boundCenterBottom(defaultMarker));
	   }
	   
	   public AddItemizedOverlay(Drawable defaultMarker, Context context) {
	        this(defaultMarker);
	        this.context = context;
	   }

	   @Override
	   protected OverlayItem createItem(int i) {
	      return mapOverlays.get(i);
	   }

	   @Override
	   public int size() {
	      return mapOverlays.size();
	   }
	   
	   @Override
	   protected boolean onTap(int index) {
		  Log.e("Tap", "Tap Performed");
	      return true;
	   }
	   
	   public void addOverlay(OverlayItem overlay) {
	      mapOverlays.add(overlay);
	       this.populate();
	   }

	}

Now open your MainActivity.java (in my case AndroidGoogleMapsActivity.java) and write following code.

List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay = 
new AddItemizedOverlay(drawable, this);
        
        
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
        
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
Android maps placing marker

Getting Latitude and Longitude of location that was touched

You can also get the latitude and longitude of location which was touched. Open your AddItemizedOverlay.java and add following method.

package com.androidhive.googlemaps;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

       /*................. Add this method ........*/
       @Override
       public boolean onTouchEvent(MotionEvent event, MapView mapView) 
       {   
           
           if (event.getAction() == 1) {                
               GeoPoint geopoint = mapView.getProjection().fromPixels(
                   (int) event.getX(),
                   (int) event.getY());
               // latitude
               double lat = geopoint.getLatitudeE6() / 1E6;
               // longitude
               double lon = geopoint.getLongitudeE6() / 1E6;
               Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
           }                            
           return false;
       } 

	}

Now run your project and touch a particular location to get lat and long of that location.

google maps getting latitude and longitude
This is image is for thumbnail purpose
Android Google maps