Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Getting Location InformationBack to Android Cookbook Home | Up to Chapter: Location and Map Applications

Author: Ian Darwin ('idarwin')
In Published Edition? Yes
FormatLanguage: WikiFormat

Getting Location Information


You want to know where you are.


Android provides two levels of locational position. If you need to know fairly precisely where you are, you can use the "FINE" resolution, which is GPS-based. If you only need to know roughly where you are, you can use the "COARSE" resolution, which is based on the location of the cell phone tower your phone is talking to.


Here is the setup portion of the code. This is part of jpstrack, a mapping application for OpenStreetMap. For mapping purpose the GPS is a must, so I only ask for the FINE resolution.

	// Part of jpstrack Main.java
	LocationManager mgr = 
		(LocationManager) getSystemService(LOCATION_SERVICE);
	for (String prov : mgr.getAllProviders()) {
		Log.i(LOG_TAG, getString(R.string.provider_found) + prov);

	// GPS setup
	Criteria criteria = new Criteria();
	List<String> providers = mgr.getProviders(criteria, true);
	if (providers == null || providers.size() == 0) {
		Log.e(JPSTRACK, getString(R.string.cannot_get_gps_service));
		Toast.makeText(this, "Could not open GPS service",
	String preferred = providers.get(0); // first == preferred

After this setup, when you actually want to start the GPS sending you location data, you have to call the LocationManager.requestLocationUpdates with the name of the provider you looked up previously, the minimum time between updates (in milliseconds), the minimum distance between updates (in meters), and an instance of the LocationListener interface. You stop updates by removeUpdates with the previously-passed-in LocationListener. In jpstrack the code looks like this:

	protected void onResume() {
		if (preferred != null) {
				MIN_SECONDS * 1000,
				MIN_METRES, this);

	protected void onPause() {
		if (preferred != null) {

Finally, the LocationListener's onLocationChanged() method is called when the location changes, and this is where you do something with the location information.

	public void onLocationChanged(Location location) {
		long time = location.getTime();
		double latitude = location.getLatitude();
		double longitude = location.getLongitude();
		// do something with latitude and longitude (and time?)...

There are a few other methods in LocationListener but they aren't required to do anything.

What you do with the location data depends on your application, of course. In jpstrack I save it into a track file with hand-written XML-writing code. Commonly you would use it to update your position on a map, or upload it to a location service. There's no limit to what you can do with it.

See Also