If you have developed any app that contains Google Maps v1, It’s time to upgrade it to Google Maps V2 as google maps version 1 deprecated officially on December 3rd, 2012 and it won’t work anymore. This article aims to give knowledge about how to implements newer Google Maps into your applications. If you have already worked with V1, implementing V2 is very easy. Refer Google Maps Docs for any topic that is not covered in this tutorial.
Before starting a new project, we need to go through some pre required steps. These steps involves importing required library, generating SHA1 fingerprint and configuring maps in google console.
1. Downloading Google Play Services
Google made new Maps V2 API as a part of Google Play Services SDK. So before we start developing maps we need to download google play services from SDK manger. You can open SDK manager either from Eclipse or from android sdk folder.
Open Eclipse ⇒ Windows ⇒ Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.
2. Importing Google Play Services into Eclipse
After downloading play services we need to import it to Eclipse which will be used as a library for our maps project.
1. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace
2. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
3. Importantly while importing check Copy projects into workspace option as shown in the below image.
3. Getting the Google Maps API key
1. Same as in maps v1 we need to generate SHA-1 fingerprint using java keytool. Open your terminal and execute the following command to generate SHA-1 fingerprint.
On Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
On Linux or Mac OS
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
In the output you can see SHA 1 finger print.
2. Now open Google API Console
3. Select Services on left side and turn on Google Maps Android API v2
4. Now select API Access on left side and on the right side click on Create new Android key…
5. It will popup a window asking the SHA1 and package name. Enter your SHA 1 and your android project package name separated by semicolon ; and click on create.
I have given like below
BE:03:E1:44:39:7B:E8:17:02:9F:7F:B7:98:82:EA:DF:84:D0:FB:6A;info.androidhive.googlemapsv2
And note down the API key which required later in our project.
4. Creating new Project
After completing required configuration, It’s time to start our project.
1. In Eclipse create a new project by going to File ⇒ New ⇒ Android Application Project and fill required details. I kept my project name as Google Maps V2 and package name as info.androidhive.info
2. Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see a Add button under library section. Click it and select google play services project which we imported previously.
3. Add the Map Key in the manifest file. Open AndroidManifest.xml file and add the following code before tag. Replace the android:value with your map key which you got from google console.
<!-- Goolge Maps API Key --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" />
4. Google maps needs following permissions and features.
ACCESS_NETWORK_STATE – To check network state whether data can be downloaded or not
INTERNET – To check internet connection status
WRITE_EXTERNAL_STORAGE – To write to external storage as google maps store map data in external storage
ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile cell data
ACCESS_FINE_LOCATION – To determine user’s location using GPS
OpenGL ES V2 – Required for Google Maps V2
Finally my AndroidManifest.xml file looks like this (Replace the package name with your project package)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.googlemapsv2" android:versionCode="1" android:versionName="1.0" > <permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" /> <uses-sdk android:minSdkVersion="12" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Required to show current location --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Required OpenGL ES 2.0. for Maps V2 --> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <activity android:name="info.androidhive.googlemapsv2.MainActivity" android:label="@string/app_name" android:theme="@style/AppBaseTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Goolge API Key --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" /> </application> </manifest>
5. New google maps are implemented using MapFragments which is a sub class of Fragments class. Open your main activity layout file activity_main.xml file and add following code. I used RelativeLayout as a parent element. You can remove it and use MapFragment directly.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
6. Add the following code in your Main Activity java (MainActivity.java) class.
public class MainActivity extends Activity { // Google Map private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Loading map initilizeMap(); } catch (Exception e) { e.printStackTrace(); } } /** * function to load map. If map is not created it will create it for you * */ private void initilizeMap() { if (googleMap == null) { googleMap = ((MapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } } @Override protected void onResume() { super.onResume(); initilizeMap(); } }
Run your project and congratulations if you see a map displaying on your device.
Placing a Marker
You can place a marker on the map by using following code.
// latitude and longitude double latitude = ; double longitude = ; // create marker MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps "); // adding marker googleMap.addMarker(marker);
Changing Marker Color
By default map marker color will be RED. Google maps provides some set of predefined colored icons for the marker.
// ROSE color icon marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); // GREEN color icon marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
Custom Marker Icon
Apart from maps native marker icons, you can use own image to show as a marker. You can load the icon from any kind of supported sources.
fromAsset(String assetName) – Loading from assets folder
fromBitmap (Bitmap image) – Loading bitmap image
fromFile (String path) – Loading from file
fromResource (int resourceId) – Loading from drawable resource
Below I loaded a custom marker icon from drawable folder
// latitude and longitude double latitude = 17.385044; double longitude = 78.486671; // create marker MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps"); // Changing marker icon marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon))); // adding marker googleMap.addMarker(marker);
Moving Camera to a Location with animation
You may want to move camera to a particular position. Google maps provides set of functions to achieve this.
CameraPosition cameraPosition = new CameraPosition.Builder().target( new LatLng(17.385044, 78.486671)).zoom(12).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Following are enhancements and features that google maps provides. You can utilize these features which suites to your requirements.
Changing Map Type
Google provides 4 kinds of map types Normal, Hybrid, Satellite and Terrain. You can toggle to any kind of map using googleMap.setMapType() method.
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
Showing Current Location
You can show user’s current location on the map by calling setMyLocationEnabled(). Pass true / false to enable or disable this feature
googleMap.setMyLocationEnabled(true); // false to disable
Zooming Buttons
You can call setZoomControlsEnabled() function to get rid of those zooming controls on the map. By disabling these buttons map zooming functionality still work by pinching gesture.
googleMap.getUiSettings().setZoomControlsEnabled(false); // true to enable
Zooming Functionality
You can disable zooming gesture functionality by calling setZoomGesturesEnabled()
googleMap.getUiSettings().setZoomGesturesEnabled(false);
Compass Functionality
Compass can be disabled by calling setCompassEnabled() function
googleMap.getUiSettings().setCompassEnabled(true);
My Location Button
My location button will be used to move map to your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled() function
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
Map Rotate Gesture
My rotate gesture can be enabled or disabled by calling setRotateGesturesEnabled() method
googleMap.getUiSettings().setRotateGesturesEnabled(true);
Although google maps provides lot of other features, I covered only basic topics in this tutorial. Remaining topics seems to be pretty much lengthy, so I’ll post them as separate articles.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
Awesome … Thanks for the Tutorial
Thank you bro …
hi my toast is not working while showing current location which i get through latitude and longitude
hi prabodh you know how to get nearest atm,restaurants from current locatiom
Can you make a tutorial how to put markers on Google Map from MySQL db?
From your mysql db generate a json file containing the information latitude and longitude. On the android fetch and parse the json and using latitude and longitude from json you can display markers.
Follow below tutorial to know how to generate json from mysql
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I tried to do that today, but I am having issue with JSON. Maybe I can send you my code on email, so you can take a look? Tnx
Can you give an example on how to parse the json? It will help a lot!
How to get Name of Location using google map API?
You can’t do that, for that you need to use places api
is it possible to use it with android? Will you add a tutorial for it here?
Awesome
method “getFragmentManager” is error
my android is 2.3.3
Try using android.support.v4.jar file in your project.
tanx
update android to api 14 and work
but map not show
this msg show “google play services wich some of your app is not suported by your device…”
Awesome… Very Nice… Thanks for the tutorial..!! 🙂 🙂
K thanks ravi i have alredy seen your apps in this.and what is differebce between befor google map v1 and v2 i mean any extra feature than v1.explain me .Thank you
Hi Kalla,
Maps v1 is deprecated and they won’t work anymore. You have to use V2 maps only and implementation of v2 is different from maps v1.
thanks a lot Ravi…
You are welcome 🙂
This is so much easy tutorials with source code ,
Thanks for your Mehinat (Hardworking) for this valuable resource to new developers.
send me comlete Android tutorials with source code thanks
Asad Ali Jogi
+92-332-2696273
http://www.fb.com/JogiAsadMirwahi
As always, clear and precise! Thanks for this wonderful tutorial.
Currently i’m looking for an example of Android Maps 2.0 where using my current location, I can show on the map the positions of place by coordinates coming from Sqlite table within 50meters. Hope you can provide on how to compute list of coordinates within a given radius.
I’m always folllowing your tutorials. Many thanks!
You can calculate distance between two geo points. And if the distance is within your radius you can show them on the map.
Check distanceBetween() method in the following doc
http://developer.android.com/reference/android/location/Location.html#distanceBetween%28double,%20double,%20double,%20double,%20float%5B%5D%29
Superb Tutorials Ravi …. Nice and clean ….. very easy to follow. Keep posting new tutorials on android development. Ravi Rockkkssssss !!!!!
Thanks 🙂
k it works f9 .then we are implemting musicplayer with equalizer as like poweramp.so you have any source to implement sound quality like poweramp .suggest us with our code samples or links in andoidapi or ndk
thank you all.
How to show up a balloon when click on Marker, with let’s say some additional info? Can you please post some code…
I haven’t covered it. I planned it for later. Check this link
http://stackoverflow.com/questions/14123243/google-maps-api-v2-custom-infowindow-like-in-original-android-google-maps
Ravi Tamada …man You are a genius…and a life saver always …
thanks a lot for every such amazing tutorial …
You are welcome 🙂
Hi Jeffy.
I followed Ravi’s android SQLite tutorial,working Google map, working with google places and Maps tutorial, android GPS location Manager,android populating spinner from SQLite database,android dropdown,android alert,android tab layout,android menu and tab tutorials for my MCA main project.
Thanks once again Ravi.. 🙂
Another Great tutorial..
Awesome … this is great great tutorial, and help my case… thank you
i wait for next tutorial around maps v2
You Are AWESOME Ravi ! I Love your tutorial. please put a tutorial about how can we build an app with sliding activities. like android home or android menu. Thanks alot
googleMap gives the null value ….
Google-map get white screen on device and emulator
hi i want your help i run the project on my device s2 and no output the output is white page with zoom and icon in the top and no map loaded help its urgent
Map is showing blank white screen!!
Check whether you generated or replaced the map key correctly.
you know how to get nearest atm,restaurants from current locatiom
do i need to generatemyown key to run your project on eclipse i want to test the project
Yes. As this key is system specific you have to generate your own key.
Got It Thanks!
how its still white black forme 🙁
my problem was i switched on
Google Maps API v2 instead of
Google Maps Android API v2 before on console
and worked for android device ,do i have to generate the key to test his project ,i created aexample and still not worked please i need help urgent
here is my email
jhg184@gmail.com
Yap generate key for application
Open cmd
go to C:Program FilesJavajdk1.6.0_30bin folder
Execute this command
keytool -list -v -keystore “%USERPROFILE%.androiddebug.keystore” -alias androiddebugkey -storepass android -keypass android
And follow the rest of the Procedure
how its still blank page
thanks
can anyone tell how to get nearest places from a particular point
Use Google Places API
http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
GREAT MAN …….RAVI
how to solve google play services which some of your applications rely on is not supported by your device.
how to solve google play services which some of your applications rely on is not supported by your device.(mdadil298@gmail.com)
Thanks sir.
I get a message:
“this app won’t run without google play services, which are missing from this phone”
and the the app still don’t run
i got this message too, what’s the problem?
Try the app on a real device
Its Very Useful, Thanks Android Hive to support new android developer …
Great tutorial! nice explanations. very useful information for the android developers. thanks a lot to share.
ipad application development company in Chennai
Hi Ravi,
Window->Preference->Android->Build shows a MD5 fingerprint and SHA1 finger print.Is this the same finger print getting after executing
“keytool -list -v -keystore “%USERPROFILE%.androiddebug.keystore” -alias androiddebugkey -storepass android -keypass android”
I am not aware of Build Show option. I’ll check and let you know.
Thank for the new info 🙂
Hi Ravi..
I have tried both the procedure ie,by running the “keytool -list -v -keystore “%USERPROFILE%.androiddebug.keystore” -alias androiddebugkey -storepass android -keypass android” command in terminal and the eclipse procedure(Window-> Preferences-> Android->Build). I got the same SHA-1 finger print for both procedure.
Please confirm whether the eclipse procedure is dependable or not
Great! having Ravi is like i can never lost within my android code. i am his fan and i’d say from the android music player to his latest tutorial of sqlite . I just love it Thanks for these free stuff. god Bless You mahn
Thanks Pankaj for all your support 🙂
Cheers!
How do I change it from starting with list view with button to show map? I would like to go to the map first zoomed into my location then I have a button to show the list?
hi ravi i m window8 user.. and when i Run this Code in CMD Prompt “C:Program FilesJavajdk1.7.0_05bin>keytool.exe -list -v -keystore “c:usersravijai.androiddebug.keystore” -alias androiddebugkey -storepass android -keypass android”
then i got message this message
access is denided..
plzzz helpp how get sh1 fingerprint keyy… 🙁
Hi . I am also using windows 8. I did’nt face any problem.Watch this video
https://www.youtube.com/watch?v=dSqLKIow7sY
I think this will help you to generate SHA 1 fingerprint.
hi ravi i m window8 user..
and when i Run this Code in CMD Prompt “C:Program
FilesJavajdk1.7.0_05bin>keytool.exe -list -v -keystore
“c:usersravijai.androiddebug.keystore” -alias androiddebugkey
-storepass android -keypass android”
then i got message this message
access is denided..
plzzz helpp how get sh1 fingerprint keyy..
I haven’t encounter this error before. May be this help you
http://stackoverflow.com/questions/15254171/access-denied-when-obtaining-android-md5-fingerprint
http://stackoverflow.com/questions/15149522/keytool-not-working-for-signing-android-app
Hi Ravi Chouhan. I am also using windows 8. I did’nt face any problem.Watch this video
https://www.youtube.com/watch?v=dSqLKIow7sY
I think this will help you to generate SHA 1 fingerprint.
Hi Ravi, Can you please check this video?
https://www.youtube.com/watch?v=dSqLKIow7sY
I think this video will help the people who is facing problem with generating SHA-1 fingerprint using java keytool.
Hi Guys here is an easy way to generate SHA-1 finger print.
” Ravi, Please confirm whether this procedure is dependable or not ”
Here is the easy way to generate SHA-1 finger print without executing
“keytool -list -v -keystore “%USERPROFILE%.androiddebug.keystore” -alias androiddebugkey -storepass android -keypass android”
Steps:
1.Open the Eclipse that you are using to develop android apps.
2. Go to Window-> Preferences
3.Expand Android(under General)
4. Click on ‘Build’
You can see the MD5 fingerprint and SHA-1 Fingerprint .
I have tried both procedure ie,executed above command in terminal and the eclipse procedure (Window-> Preferences-> Android->Build). I got the same SHA-1 finger print for both procedure.
Ultimate Solution or trick thanks
Thank you bro ..
Hi Ravi Please help me to solve the issue “google play services which some of your applications rely on is not supported by your device”
sorry i get error,
android.view.InflateException:binary xml file line #11 :Error inflating class fragment
got the same problem…
got the same problem
I got the same problem !
After 3 hours research I found out this is really common error.
I try so many solutions but nothing work.
Anyone has experience with this error! Please help and explain
Great tutorial. Took me less than one hour to complete!
Hi Ravi, I’m getting an error
” Google Play Services, which some of your applications rely on, is not supported on your device. Please contact the manufacturer for assistance.” Shall I test this on a real device? Thank You so Much.
it will not run on emulator,install the .apk file in your device,it will work fine
I try to display simply google map on android device. I did all of the steps. but when i run the program, it stopped. So I debug and it says source not found at ‘setContentView(R.layout.activity_main);’.. How can I solve?
clean the project and rebuild it,if u are running the same project it should work fine with it,
I am implementing this on a device having api level 8. Instead of MapFragment, I have used SupportMapFragment. But still the map is not being displayed. Only the zoom in/out buttons are visible.
Please help me out.
I am also having the same zoom in/out issue
Did you generated the map key correctly by giving your project package name ?
I have resolved it 😛 I actually activated Google Maps API v2 Instead of Google Android Maps API v2. And btw this tutorial is simply awesome, real easy to follow and understand 😀 😀
Oh. Good 🙂
Hi Ravi, Can you please tell me how to
activate “Google Android Maps API v2 from Api Access while generating the Api Key”.
Hi Aman i am facing the same problem ” only zoom in/out is visible “.can u please explain how did u resolved the problem?
Activate the Google Android Maps API v2 from Api Access while generating the Api Key
Hi MAD, Can you please tell me how to
activate “Google Android Maps API v2 from Api Access while generating the Api Key”.
Hi Aman can u please mention the steps ??
Hi Neha. Did u fix this problem?
i got this message: “this app won’t run unless you update google play services” what’s wrong?
i followed all steps
nice tutorial…
I found an error on this line …
googleMap.addMarker(Marker);
ERROR: syntax error on token “Marker”, VariableDeclaratorId after this token..
so kindly help me out to solve this problem.. Thanks..
Hi Ravi.
I have generate my own key and put in to manifest.
Then debug your sample on my phone.
But I still get map doesn’t show up
Can you please do another tutorial for this but with android studio? I know a lot of people on the internet are having troubles setting this up in android studio.
i am getting like ” The app wont run unless you update google play services and dispaying a button update”. even if i am clicking the button nothing is happening..
i have tried it with different emulators but the o/p is same…
plz help me..
The mapsV2 will run only run on the real device. you have to take your .apk file(in bin folder) and have to install it into your phone and then it will run.