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
Subscribe
Notify of
guest
198 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] more from the original source: Android Working with Google Maps | AndroidHive | Tutorials, Games … This entry was posted in News and tagged already-download, api, new-project, project, […]

Gentor_sic
Gentor_sic
8 years ago

Great tutorial! DO you have a tutorial on getting the location from an edittext?

Boopathy Balakrishnan
Boopathy Balakrishnan
8 years ago

Hi Ravi how to use Google Map Android api v2?

Panchanan Rauta816
Panchanan Rauta816
8 years ago

it is really though full and good.

Krunal Dave1988
Krunal Dave1988
8 years ago

hi running this program in emmulator just shows the grid pin and zoom in zoom out control .no maps are displayed.

Anukool Tiwari
Anukool Tiwari
8 years ago

Generate the api key and add it in the main.xml android:apikey attribute.
Hope this helps.

Nazrul
Nazrul
8 years ago
Reply to  Anukool Tiwari

Hi Mate, ive done this and still see the same as above post.

Thanks,

Pavan Obbeli89
Pavan Obbeli89
8 years ago
Reply to  Anukool Tiwari

i have put apikey it shows icon with latitude and longitude but didin’t show maps

Daghfous
Daghfous
8 years ago
Reply to  Pavan Obbeli89

Try the new Google Maps Android API v2 using SupportMapFragment

Kislay Kumar
Kislay Kumar
8 years ago
Reply to  Daghfous

Please share the best tutorial for SupportMapFragment for Google Maps Android API v2. I am facing problem in adding map to lower version of android and devices without opengl. Please help

kaka
kaka
8 years ago
Reply to  Pavan Obbeli89

go f___ yourself…..
it will surely work…..@wave
u jaffa

nani
nani
8 years ago
Reply to  Pavan Obbeli89

Google Maps Android API v2 cannot run in emulator. Google Play service not support the emulator.

Source : http://ramsandroid4all.blogspot.com/2013/03/google-maps-android-api-v2.html

Luiz
Luiz
8 years ago

Hi Ravi, could you please do a tutorial on how to obtain the new Google Maps Android API v2, and integrate it in an app. Thanks

Jindra
Jindra
8 years ago

Great tutorial.. but i dont see the map either :/ only the grid with the pin and the toolbar. Could you pls give me an advice? Thx a lot

Anoop
Anoop
8 years ago

When Generate fingerprint using cmd, i am getting a SH1 code instead of MD5. Google is not accepting that code to generate API. What to do?

Kamalakar Damera
Kamalakar Damera
8 years ago

hey thanks man…..it helps me alot…but i didnt get the googlemap……. instead i got small boxes at the output…please reply me

mahesh gurram
mahesh gurram
8 years ago

hi running this program in emmulator just shows the grid pin and zoom in zoom out control and icon ,when move icon then show a message but no maps are displayed.

Iram Bukhari
Iram Bukhari
8 years ago

Really …very informative post…thanks for sharing..:)

Barry Maswan
Barry Maswan
8 years ago

Great post man! However, I keep on getting some error in my Styles.xml. This what is displayed in the console whenever I try to run the app
[2013-01-15 12:17:57 – GoogleMaps] W/ResourceType( 4149): Bad XML block: header size 56 or total size 154188856 is larger than data size 0
[2013-01-15 12:17:57 – GoogleMaps] /home/barry/workspace/GoogleMaps/res/menu/activity_android_google_maps.xml:3: error: No resource identifier found for attribute ‘showAsAction’ in package ‘android’

Please help me

Gauravfree2rhyme
Gauravfree2rhyme
8 years ago

if you use proxy on your network please enter
-http-proxy http://10.1.8.30:8080
in your additional input parameters for emulator

Nazrul
Nazrul
8 years ago

Hi there, all I get is a blank canvas with gridlines. No actual map is displayed?

Thanks,

jayant shinde
jayant shinde
8 years ago
Reply to  Nazrul

Please use your own google maps api key not the one posted above.

Tcwijekoon
Tcwijekoon
8 years ago

Very useful post. Thank you

Reyajali
Reyajali
8 years ago

awesome tutorial, it’s nice working and also very helpful for startups.

Ashutosh
Ashutosh
8 years ago

Nice post ravi please tell how to plot two llocation on map

Danish
Danish
8 years ago

Hello Sir, I have tried it but only Grids on screen is viewing. i am not getting the original view of Map. Plz Help Me
@DANISH

jayant shinde
jayant shinde
8 years ago
Reply to  Danish

Hi Danish please use your own google maps api not the one posted above.

priyatham naga
priyatham naga
8 years ago

i am not getting google api in android sdk…wat to do?

Vishal Garg
Vishal Garg
8 years ago

fadu bhai fadu!!!!!!!!!!!!!!
Properly running

Merry Vino
Merry Vino
8 years ago

Check the manifest file. Add all the uses permission needed before run the application..Check Google Maps Android API v2 for this…..

Dhiraj
Dhiraj
8 years ago

hay i try this code on my eclipse but pin point is not displaying so could u tell me what necessary requirement need like- which sdk version or eclipse version???

Darshilrami
Darshilrami
8 years ago

In my application the map is shown but the marker does not shown….and when i used the code to show the latitude and longitude the application shows force close..please give some solution..

Brianmaldonado
Brianmaldonado
8 years ago

Hello from mexico! thank you very much for this work, I keep on all steps, but in step eight, didn’t drew the map, why?? I Can see only empty boxes in my aplication, well, I have been tried for three days and don’t can, I hope for you reply, take care.

Ubongmajesty
Ubongmajesty
8 years ago

Hello Ravi, i saw your Tutorial on Android application, this an amazing work. i really appreciate your Effort and time. please i have problem with my application. i can only see the grip but no actual map displaying .i have insert both my Map key and API key but still have the same problem. Please kindly help. thank you for your kind consideration. John

Karthickbe2008
Karthickbe2008
8 years ago

Such a nice tutorial you given to us,can you tell us how to do the search option to find the location using google map

Steven Perete
Steven Perete
8 years ago

is there an Maps API v2 example which uses MapFragment

Mrjadulco
Mrjadulco
8 years ago

hi… nice tutorial… but i have a problem… when i run it in the emulator,, it works… but when i exported it and install the apk in the tablet… it didn’t work… may you please tell me why it happen and what should i do??? i hope you can help me… thanks very much… more power… ^^,

Quvi
8 years ago

You are boss man!
I love android hive

Giancarlo Leonio
Giancarlo Leonio
8 years ago

Thanks for the tutorial! I compiled a list of top resources for adding a MapView to an Android Application. I included your post. Check it out/ feel free to share. http://www.verious.com/board/Giancarlo-Leonio/adding-a-map-view-to-an-android-application/ Hope other developers find this useful too 🙂

Srikanthlraj Raj
Srikanthlraj Raj
8 years ago

hey i want overlay on All Location..How can i Achived it??

Peter Mbugua
Peter Mbugua
3 years ago

hey everyone, how can we adopt the code to track devices like uber does (Show how the movement of the car on map as one moves)?

rajashree patil
rajashree patil
3 years ago

Google Maps QR Code: How to easily share your location via print media

om prakash
om prakash
2 years ago

how to open kml file on google map give solution
i work one weak but not wok proper

fuad setiawan
fuad setiawan
9 years ago

great post…ravi…keep sharing

M.Salmansabir
M.Salmansabir
9 years ago

nice post.can you make detail tutorail with android connect with mysql database and also with sqli.with the following statements select insert delete.I will be very helpful.

Hrishikesh Kumar
9 years ago

A great tutorial. Thanks for sharing it. I had an app idea in which I needed this. You ended my quest. 🙂

Ravi Tamada
9 years ago

You are welcome 🙂

nouga
nouga
9 years ago
Reply to  Ravi Tamada

Hi Ravi, good tutoriel
It force closes each time I run it. it give me the follow message: The application Googlemaps (process com.androidhive.googlemaps ) has stopped unexpectedly. Please try again.
the log error report:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.google.map/com.google.map.GoogleMapActivity}: java.lang.ClassNotFoundException: com.google.map.GoogleMapActivity in loader dalvik.system.PathClassLoader[/data/app/com.google.map-1.apk]

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.google.map.GoogleMapActivity in loader dalvik.system.PathClassLoader[/data/app/com.google.map-1.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)

Thank’s for your help

Ravi Tamada
9 years ago
Reply to  nouga

I think you didn’t added class file in your Androidmanifest.xml file …
Class name is GoogleMapActivity.

Check once..

nouga1
nouga1
9 years ago
Reply to  Ravi Tamada

i added class GoogleMapActivity in my Androidmanifest.xml file this is the content of my file:

rajesh
rajesh
9 years ago

It force closes each time I run it.

Ravi Tamada
9 years ago
Reply to  rajesh

Hi Rajesh,

Please give log error report. Also make sure that you added internet permissions in you manifest.xml file.

Rajesh
Rajesh
9 years ago
Reply to  Ravi Tamada

The application Googlemaps (process com.androidhive.googlemaps ) has stopped unexpectedly. Please try again.

Thakurarun679
Thakurarun679
9 years ago
Reply to  Rajesh

rajesh:- this is not log error. please check ur log cat and post the error from there.then only you get an help.

nouga
nouga
9 years ago
Reply to  Rajesh

Hi rajesh,
i have the same error as you. did you find the solution?
thank’s for your help

Ravi Tamada
9 years ago
Reply to  nouga

Check your error log cat for error report.

Kalaivan10292
Kalaivan10292
8 years ago
Reply to  Ravi Tamada

Problems occurred when invoking code from plug-in: “org.eclipse.ui.workbench

Venki Utk
Venki Utk
8 years ago
Reply to  Rajesh

i think check ur mapkey,and check once ur itemizedOverlay initialization in AndroidGoogleMapsActivity ..

Asifse15
Asifse15
9 years ago

nice post but i have a problem that the is not seen just blank page is available
please guide me . via email
asifse15@gmail.com

Ravi Tamada
9 years ago
Reply to  Asifse15

Hi Asif,

I think its because your Google Maps Keys. Try to generate you keys again. Redo your steps from generating keys using CMD console..

Donfjohn
Donfjohn
9 years ago

how can we show our current position in the mao ?

Ravi Tamada
9 years ago
Reply to  Donfjohn

Hi Donfjohn,

I think we can’t get our location on the map directly. You need to get current location using GEO LOCATION and send lat and long and display that point on map

Mike Dalisay
9 years ago

Isn’t it that GMap v3 don’t need API key?

Somesh Bhowmick
Somesh Bhowmick
9 years ago

Simply Great … Great …Great . What I say This types of post is really grace for beginers. Thanks a lot . keep posting this types of stuff in future

Rema Bux Radic
9 years ago

Nice post Ravi :). Great job. Can I ask you what font did you use on the images http://www.androidhive.info/wp-content/uploads/2012/01/mapkey.png

Ravi Tamada
9 years ago
Reply to  Rema Bux Radic

Christopherhand

Rohit Patel
Rohit Patel
9 years ago

Thank You Ravi !! Great help for learners, very helpful tutorials.

Tanu_cste10
Tanu_cste10
9 years ago

i tried to find the api key in using the way existed here.C:usersdocumenta.androiddebug.keystore,but it says “The system cannot find the path specified”.how can i fix it?

Ravi Tamada
9 years ago
Reply to  Tanu_cste10

are you sure that file exists in that location. Check the path once by going to that folder

Tanu_cste10
Tanu_cste10
9 years ago
Reply to  Ravi Tamada

ya.i check the path.the debug.keystore existed there.but why it doesnot work i dont know

Ravi Tamada
9 years ago
Reply to  Tanu_cste10

Please give me the command you are executing in CMD

Tanu_cste10
Tanu_cste10
9 years ago
Reply to  Ravi Tamada

ravi@is this the example of find my own location or just google map?

Tanu_cste10
Tanu_cste10
9 years ago
Reply to  Tanu_cste10

how can i find my location using gps?

Tanu_cste10
Tanu_cste10
9 years ago
Reply to  Ravi Tamada

thanks for the tutorial.finally i have done it 🙂

KIRAN.V.MENON
9 years ago

While implementing “Getting Latitude and Longitude of location that was touched”, clicking on the map stops the entire application, do it require internet connection or a .gpx file loaded?

Niraj_kalra
Niraj_kalra
9 years ago

can i do the tracking of the path in this case

Ketan Mehta
Ketan Mehta
9 years ago

Very Nice…thanks for sharing..

Ana Paula Gomes
Ana Paula Gomes
9 years ago

Very nice! Congratulations for your job!

Rebaimoez
Rebaimoez
9 years ago

nice tutorial ravi go ahead yr master

198
0
Would love your thoughts, please comment.x
()
x