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 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.
11. 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>
12. 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;
}
}
13. Enable GPS in the device from Settings
14. Running the application
15. Download Source Code







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.
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
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)