In this article, we will create an Android application which will display current location in Google Maps using Google Maps Android API V2.
Since the Google Map is displayed using SupportMapFragment, this application can run in Android API Level 8 or above.
In order to use MapFragment for Google Maps, we need Android device with API level 12 or above.
This application is developed in Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ). This application is tested in a real Android Phone with Android ( 2.3.6 ).
An alternative method for this application is available at Showing current location using OnMyLocationChangeListener in Google Map Android API V2
1. Download and configure Google Play Services Library in Eclipse
Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.
Please follow the given below link to setup Google Play Service library in Eclipse.
http://developer.android.com/google/play-services/setup.html
2. Create a new Android Application Project namely “LocationInGoogleMapV2″
3. Configure Android Application Project
4. Design Application Launcher Icon
5. Create a blank activity
6. Enter Main Activity Details
7. Link to Google Play Service Library
8. Get the API key for Google Maps Android API v2
We need to get an API key from Google to use Google Maps in Android application. Please follow the given below link to get the API key for Google Maps Android API v2.
https://developers.google.com/maps/documentation/android/start
9. Add Android Support library to this project
By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :
- Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
- Right click this project
- Then from popup window, Click “Android Tools -> Add Support Library “
10. Update the file res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">CurrentLocation</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> </resources>
11. Update the file AndroidManfiest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.wptrafficanalyzer.locationingooglemapv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <permission android:name="in.wptrafficanalyzer.locationingooglemapv2.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="in.wptrafficanalyzer.locationingooglemapv2.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"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-feature android:glEsVersion="0x00020000" android:required="true"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="in.wptrafficanalyzer.locationingooglemapv2.MainActivity" 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="YOUR_API_KEY"/> </application> </manifest>
Note : In the above code, replace “YOUR_API_KEY” with the api key, you generated in step 8.
12. Update the layout file to display Google Map using SupportMapFragment
<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" tools:context=".MainActivity" > <TextView android:id="@+id/tv_location" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/tv_location" class="com.google.android.gms.maps.SupportMapFragment" /> </RelativeLayout>
13. Update the file src/in/wptrafficanalyzer/locationingooglemapv2/MainActivity.java
package in.wptrafficanalyzer.locationingooglemapv2; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; public class MainActivity extends FragmentActivity implements LocationListener { GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting Google Play availability status int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); // Showing status if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); dialog.show(); }else { // Google Play Services are available // Getting reference to the SupportMapFragment of activity_main.xml SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // Getting GoogleMap object from the fragment googleMap = fm.getMap(); // Enabling MyLocation Layer of Google Map googleMap.setMyLocationEnabled(true); // Getting LocationManager object from System Service LOCATION_SERVICE LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // Creating a criteria object to retrieve provider Criteria criteria = new Criteria(); // Getting the name of the best provider String provider = locationManager.getBestProvider(criteria, true); // Getting Current Location Location location = locationManager.getLastKnownLocation(provider); if(location!=null){ onLocationChanged(location); } locationManager.requestLocationUpdates(provider, 20000, 0, this); } } @Override public void onLocationChanged(Location location) { TextView tvLocation = (TextView) findViewById(R.id.tv_location); // Getting latitude of the current location double latitude = location.getLatitude(); // Getting longitude of the current location double longitude = location.getLongitude(); // Creating a LatLng object for the current location LatLng latLng = new LatLng(latitude, longitude); // Showing the current location in Google Map googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Zoom in the Google Map googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); // Setting latitude and longitude in the TextView tv_location tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude ); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
14. Enable GPS in the device from Settings
15. Running the application
16. Download Source Code

17. Tryout
We can tryout this application from Google Play Store at https://play.google.com/store/apps/details?id=in.wptrafficanalyzer.locationingooglemapv2

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to info@wptrafficanalyzer.in.
My other blogs
store4js.blogspot.com
Hi George, Sorry but again in trouble. Getting nullpointerException on line googleMap.setMyLocationEnabled(true); any ideas what might be the problem.
Thanks in advance.
Hi,
I am not able to reproduce any NullPointerException as you mentioned. May be you missed some steps at somewhere.
Hello Sir,
I can not able add google play service lib as reference library so please help me
hi, I used to get the same problem.
click copy into my workplace when you referencing google_play_service.lib
hope it could solve your problems
i don’t want to get location some error are occur setContentview and java.lang.IllegalStateException.
The meta-data tag in my app androidmanifest.xml does not have the right value..
please help me…
Thanks
Hi’
is ti also working for indoor localization?
Hi and thanks for the tutorial.
How can I add a possibility for the user to activate the GPS localization ?
Thanks
Have you figured out how to provide option to activate GPS from application and then returning back to the application with the current location on maps.
For me only white screen shown no map
Are you getting any hint from logcat messages?
Dear George,
Nice tutorial.
I too am getting only a white/grey screen with no map. but i do get my longitude and langitude.
Do u have any idea what is causing this problem?
I have tried many other solutions/examples and nvr get the map to show on my device. (I have a 2.2 Froyo device)
When i try it on a AVD emulator i am getting a
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{
com.example.test3/com.example.test3.MainActivity}: java.lang.NullPointerException
…
Dear Michael,
Please ensure that, the correct API key is entered in the AndroidManifest.xml.
Google Maps Android API V2 applications will not be executed in emulators since it require Google Play Services library.
I too i’m getting on the white screen with lat and long.
I assure you that my API KEY and package name are correct
What could be the problem
Also, my logcat doesn’t show anything significant..only some ‘pause 4ms+…’ stuff
thanks, it’s very helpful. Finally found the solution to show current location!!!!
Thanks man, worked like a charm!
As for those who have white screen problems – make sure that you got the right API key and package name is yours one (if you’ve changed it while following the tutorial) in AndroidManifest.xml
very nice solution.but provide me configartion for Mapv2 for android
Hi..AOA
I am working on google maps in android app . I want reverse geocoding but it doesnt works and give warning ” Service not available” . please help me……………..
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class fragment
hepl me!
hi , r u using SupportMapFragment
I have an error. Error is :
Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
XML File :
Line 12 :
Java Class :
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
please help me i downloaded the Source code and Obtain a Google Maps API key. and Add Google Play Services
but iam get “the application MyLocation(process in.Wptrafficanalyzer,locationingooglemapv2)has stooped unexpectedly.please try agin”
Thank You George, concise and in depth tutorials, easy to follow even for beginners like me. Bookmarked as a great Android resource
hai brother i downloaded your app and run it in ma Tab with my API key but the logcat shows Failed to load MAP could not contact google servers what should i have to do the screen is showing the longitude and lanti of my current location
thank you
thank you brother i have solved it great job for you thank you very much
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.os.Handler.dispatchMessage(Handler.java:99)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.os.Looper.loop(Looper.java:137)
04-18 14:02:57.110: E/AndroidRuntime(14414): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-18 14:02:57.110: E/AndroidRuntime(14414): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 14:02:57.110: E/AndroidRuntime(14414): at java.lang.reflect.Method.invoke(Method.java:511)
04-18 14:02:57.110: E/AndroidRuntime(14414): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-18 14:02:57.110: E/AndroidRuntime(14414): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
04-18 14:02:57.110: E/AndroidRuntime(14414): at dalvik.system.NativeStart.main(Native Method)
Really Nice Explanation. I tried a lot and search many sites. But find solution here only. Thanks for the post.
Hi, George! Thanks for this great tutorial, really helped me.
I’ve got problem with GooglePlayServicesUtil. Its says “cannot be resolved”. How to fix it??
sorry for my bad english :p
Ensure that, you downloaded and configured Google Play Services library as mentioned in the Step 1.
Once Google Play Services library is configured, then link that library to this project as shown in the Step 7.
i did
sorry its my mistake, I forgot to add the import things. Thanks George
i got the lantitute and latitude bt not getting map in place of that getting white screen
In this application the latitude and longitude are obtained using LocationManager api.
If you are getting a white screen instead of map, probably you may not have entered the correct Android API Key in AndroidManifest.xml file.
I put the appropriate Api key also bt i think is there any other apk we need to install before run this application…??
Please check the logcat to get a hint on the white screen
logcat is not showing any error..
hy george i still face the proble,
i got the zoom in and zoom out button bt don’t get any map..
Thanx in Advance
Hi Priyank Pandya,
Please ensure that, Google Maps Android API v2 service is enabled in Google APIs Console.
this app won’t run unless you update google play services
Hi George,
We are making a running app for school, and i have tried several different ways of showing the current users MyLocation, your solution works great.
But when you are moving, the camera does not update your current new location, so it is in the middle of the screen the whole time. Why is that, i cant find a solution for google Maps v2 which will move to the rigt location automatic. Hope you can help me.
Hello Rasmus,
This application will automatically update the current location, even when the device is moving.
hi
i m making an alarm based application in android and for this i need to get current train locations , how can i get these type of details plzz help me asap. thanks
I had problem in logcat “can’t redirect to app setting for Google Play Services”??
why i didn’t got bid blue circle?
i am getting an error in
the error is Unexpected namespace prefix “xmlns” found for tag fragment
I’m getting on the white screen with lat and long..how can it resolve this
helo george ..
i want ask something..why my emulator take time tO launched..
hi George
Do u know how make “Add connection” in android contacts..
as i want to add contact using my account
Thnx…
05-25 07:46:50.922: E/dalvikvm(5727): Could not find class ‘com.google.android.gms.maps.model.LatLng’, referenced from method com.bas.wisatasulawesi.Posisi.onLocationChanged
help please, thanks
Hi George,
Everything is according to your tutorial and I am also getting the current location but the map is not displaying. My API key is correct and Google Maps Android API v2 service is also running, still I don’t get it what’s going wrong please advise.
Thank you very much. You helped me.
what can i add to this cod to show this position with (latitude and logntitude)
Hello,I’m having a problem.My logcat show as below.Please help me!
06-19 20:41:05.169: E/AndroidRuntime(32447): FATAL EXCEPTION: main
06-19 20:41:05.169: E/AndroidRuntime(32447): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationingooglemapv2/in.wptrafficanalyzer.locationingooglemapv2.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationingooglemapv2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/in.wptrafficanalyzer.locationingooglemapv2-1.apk]
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.os.Handler.dispatchMessage(Handler.java:99)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.os.Looper.loop(Looper.java:130)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-19 20:41:05.169: E/AndroidRuntime(32447): at java.lang.reflect.Method.invokeNative(Native Method)
06-19 20:41:05.169: E/AndroidRuntime(32447): at java.lang.reflect.Method.invoke(Method.java:507)
06-19 20:41:05.169: E/AndroidRuntime(32447): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
06-19 20:41:05.169: E/AndroidRuntime(32447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
06-19 20:41:05.169: E/AndroidRuntime(32447): at dalvik.system.NativeStart.main(Native Method)
06-19 20:41:05.169: E/AndroidRuntime(32447): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationingooglemapv2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/in.wptrafficanalyzer.locationingooglemapv2-1.apk]
06-19 20:41:05.169: E/AndroidRuntime(32447): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
Me too
Resolved
http://stackoverflow.com/questions/12270493/android-unable-to-resolve-superclass
Amazing tutorial, thanks so much for making this. Worked perfectly.
Its working but i cant zoom into my location, it zooms near it, how can i solve it ? any ideas?
this is cool man,thanks a lot dude,this is the best google maps tutorial i ever found in google
Muchas por este ejemplo. Esta increíble.
Saludos.
In the Logcat , I am gettinng such error
No class found for Main Activity
I have downloaded ur project!1
Hi,
Please do the following :
* Open properties window by right clicking the project from eclipse’s package explorer
* Select Java Build Path -> Order and Export tab
* Ensure “Android Private Libraries” is checked
* If unchecked, “check” it and click ok
* Clean and Build the project and run the application
Sir still no luck
I am also getting this
06-19 20:41:05.169: E/AndroidRuntime(32447): FATAL EXCEPTION: main
06-19 20:41:05.169: E/AndroidRuntime(32447): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationingooglemapv2/in.wptrafficanalyzer.locationingooglemapv2.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationingooglemapv2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/in.wptrafficanalyzer.locationingooglemapv2-1.apk]
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.os.Handler.dispatchMessage(Handler.java:99)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.os.Looper.loop(Looper.java:130)
06-19 20:41:05.169: E/AndroidRuntime(32447): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-19 20:41:05.169: E/AndroidRuntime(32447): at java.lang.reflect.Method.invokeNative(Native Method)
06-19 20:41:05.169: E/AndroidRuntime(32447): at java.lang.reflect.Method.invoke(Method.java:507)
06-19 20:41:05.169: E/AndroidRuntime(32447): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
06-19 20:41:05.169: E/AndroidRuntime(32447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
06-19 20:41:05.169: E/AndroidRuntime(32447): at dalvik.system.NativeStart.main(Native Method)
06-19 20:41:05.169: E/AndroidRuntime(32447): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationingooglemapv2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/in.wptrafficanalyzer.locationingooglemapv2-1.apk]
06-19 20:41:05.169: E/AndroidRuntime(32447): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
Hi sir,your tutorials r very helpful.Is it possible that one user update the map (make a marker on map saying traffic jam on some road ) can be seen to other users using that app too.
plz help
sure you can.
( Cloud + Google cloud message ) is a solution for your problem
Cloud : for updating data in the server
Google cloud messaging : for informing clients regarding updated data
thnx ,can u suggest any tutorial on that.
Sir,
Can u tell me how to update data on map through receiver as getSupportMapFragment is not working in the Receiver
Is it possible adding two or more pipoints to the Map?I thing it’s about OverlayItem ? Please give me example about that.Enjoy yourself.thanks.
hi admin & everyone. the TextView no display Location(latitude, longitude). why?
Thank you sir it’s really help me thanks a lot……
Hi George, great job sincerely.
Your app works great but when I move my device i notice that the textview with the current location coordinates does not changes, although my position on the map changes correctly.
Any solution
Hi George,
Great work here!!
I have a doubt .. is it possible to show just the available possible routes to the user? i.e. from Location A to B which possible routes are there. And then when user selects one of the route .. you show the selected route on the Map?
Does Map API or Direction API allows this?
Use Directions API. He has an example for that too. Keep the polyline somewhat thick for neatness,
How do i add a marker to current location and keep updating that marker in onlocationchanged to the new location point.
I think we can add Map as class variable. You can remove marker from map and add a new one again on onlocationchanged() ?
thank you so much George, really appreciate your work!!!
you help me to solve my research about GPS dvelopment…
Dear Sir,
I have lot of doubts in android,now i need a tutorial about find friend location during call via message,please help me sir.
I have an app in which i am trying to create a map and show my current location and add another location as my destination. So i used this code to generate map and show my current location. When i exported and installed it on my device it says “Unfortunately application has stopped”. Is there anything that i am missing.
Hi mate! Do you know how to use this Google maps android v2 like the Google places?
Hi,
Please see the given below article :
Your awesome sir..your sample codes on google maps are very helpful to me…thanq you so much sir…..
Sir ,
i doing my project i.e Spot Me!!!
i have to find out my location and share it with my friends and relatives and also i have to find out my friend’s location….
i didnt get the flow of my project..plz help me…
can u able to provide adt bundle eclipse with google api ???
plz reply….asap
Hi George , im doing my project using MyLocation on Google maps to changes dynamically if you can help with it .
looking forward to hear from you
How can I fix “Dialog cannot be resolved to a type”?
Thank you sir.
Good code, worked for me
Hai sir,
Current Location is not showing in my emulator. pls help me sir
i want to know that on the place of blue dot that represent our current location i want to show a sign or marker.. how i can do this??
Hey nice code man!! I have a doubt.
what should i do if i need to get coordinates of any point on the map by dragging the icon present on the map?
Hi George,
Thank you so much for this tutorial – it works fantastic.
Do you have any tutorial or code that will allow a user to click on more points in the map so that they can create a route with waypoints? If not, then what do you think the best way to do this would be?
Thanks in advance
just upgrade your google play services, now it is available
Sir, Excellent tutorial. I want to reduce the internet data usage now. I have disabled buildings. what should i do to minimize by data usage when i’m on the go?
I am facing Unfortunately (Application Name) has stopped problem. While I am checking error using logcat it shows error on fragment and 25 more.
Where is the problem and how can I solve this?