English: GPS navigation solution running on a ...

Image via Wikipedia

English: Screenshot of Android Froyo 2.2 runni...

Image via Wikipedia

Google Map Maker

Image via Wikipedia

Android Location API and Google Maps

This tutorial describes the usage of the Android Location API, the usage of Google Maps and the Geolocation API. It is based on Eclipse 3.7, Java 1.6 and Android 4.0 (Ice Cream Sandwich) (Gingerbread).

1. Android Basics

The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial for the basics.

2. Android Location API

2.1. Android Location API

Most Android devices allow to determine the current geolocation. This can be done via a GPS (Global Positioning System) device, via cell tower triangulation or via wifi networks for which the geolocation is known. Android contains the android.location package which provides the API to determine the current geo position.

The LocationManager provides access to the Android location service. This services allows to access location providers, to register location update listeners and proximity alerts and more.

The LocationProvider class provides location data via the Location class. The LocationProvider class is the superclass of the different location providers which deliver the information about the current location.

The Android device might have several LocationProvider available and you can select one of them. For a flexible selection of the best location provider use a Criteria object in which you can define how the provider should be selected.

You can register a LocationListener object with the LocationManager class to receive periodic updates about the geoposition.

You can also register an Intent which allows to define a proximity alert, this alert will be triggered if the device enters a area given by a longitude, latitude and radius (proximity alert).

2.2. Forward and reverse Geocoding

The Geocoder class allows to determine the geo-coordinates (longitude, laditude) for a given address and possible addresses for given geo-coordinates.

This process is known as forward and reverse geocoding.

2.3. Security

If you want to access the GSP then you need the ACCESS_FINE_LOCATION permission. Otherwise you need the ACCESS_COARSE_LOCATION.

2.4. Setting the geoposition

You can use the “DDMS” Perspective of Eclipse to send your geoposition to the emulator or a connected device. For open this Perspective select Window → Open Perspective → Other → DDMS.

In the Emulator Control part you can enter the geocoordinates and press “Send.”

You can als set the geoposition the Android emulator via telnet. Open a console and connect to your device. The port number of your device can be seen in the title area of your emulator.

				
telnet localhost 5554

Set the position via the following command.

				
geo fix 13.24 52.31

3. How to check if the LocationProvider is available

You can find out if a LocationManager is enabled via the isProviderEnabled() method. If its not enabled you can send the user to the settings via an Intent with the Settings.ACTION_LOCATION_SOURCE_SETTINGS action for the android.provider.Settings class.

			
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
	.isProviderEnabled(LocationManager.GPS_PROVIDER);

// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to 
// go to the settings
if (!enabled) {
  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	startActivity(intent);
}

Typically you would open an AlarmDialog prompt the user and if he wants to enable GPS or if the application should be canceled.

You cannot enable the GPS directly in your code, the user has to do this.

4. Activating the GPS module on the device

You need to activate GPS on your test device. If you test on the emulator and its not activated you “null” if you try to use a LocationManager.

The Google Map Activity should automatically activate the GPS device in the emulator but if you want to use the location manager directly you need to do this yourself. Currently their seems to be an issue with this.

Start Google Maps on the emulator and request the current geo-position, this will allow you to activate the GPS. Send new GPS coordinates to the Android emulator.

5. Tutorial: Using the Android Location API

Create a new project called “de.vogella.android.locationapi.simple” with the Activity called “ShowLocationActivity”.

This example will not use the Google Map therefore is also runs on an Android device.

Change your “main.xml” layout file from the “res/layout” folder to the following:

				
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Latitude: "
            android:textSize="20dip" >
        </TextView>

        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Longitute: "
            android:textSize="20dip" >
        </TextView>

        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>

</LinearLayout>

5.2. Add permissions

Add the following permissions to your application in your “AndroidManifest.xml” file

  • INTERNET
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION

5.3. Activity

Change ShowLocationActivity to the following. It queries the location manager and display the queried values in the activity.

package de.vogella.android.locationsapi.simple;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class ShowLocationActivity extends Activity implements LocationListener {
	private TextView latituteField;
	private TextView longitudeField;
	private LocationManager locationManager;
	private String provider;
/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		latituteField = (TextView) findViewById(R.id.TextView02);
		longitudeField = (TextView) findViewById(R.id.TextView04);

		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);

		// Initialize the location fields
		if (location != null) {
			System.out.println("Provider " + provider + " has been selected.");
			int lat = (int) (location.getLatitude());
			int lng = (int) (location.getLongitude());
			latituteField.setText(String.valueOf(lat));
			longitudeField.setText(String.valueOf(lng));
		} else {
			latituteField.setText("Provider not available");
			longitudeField.setText("Provider not available");
		}
	}

	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, 400, 1, this);
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	@Override
	public void onLocationChanged(Location location) {
		int lat = (int) (location.getLatitude());
		int lng = (int) (location.getLongitude());
		latituteField.setText(String.valueOf(lat));
		longitudeField.setText(String.valueOf(lng));
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();

	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}
}

5.4. Run and Test

If you using the emulator send some geo-coordinates to your device. These geo-coordinate should be displayed as soon as you press the button.

6. Google Maps

6.1. MapsView

Google provides via the com.google.android.maps package a library for using the MapView in your application. You require an additional key to use them. This key will be specified in the View which displays the map.

You need to add the following uses-library statement to your AndroidManifest.xml file. The project creation wizard does this automatically if you select a Google API version.

				
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>

The usage of MapView requires the permission to access the Internet, as the data displayed in the MapView is downloaded from the Internet.

6.2. MapsActivity

The MapActivity class extends the Activity class and provides the life-cycle management and the services for displaying a MapView widget.

MapActivity simplify the handling MapViews similar to ListActivity simplifies the usage of ListViews.

A MapView is typically defined in the XML layout file used by the MapActivity and requires the API key in the “android:apiKey” attribute. A MapView can be used with other user interface components in the same layout.

The MapController class can be used to interact with the MapView, e.g. by moving it. A Geopoint is a position described via latitude and longitude.

6.3. OverlayItem

You can also draw OverlayItem on the map. These are typical graphics which you want to display on the map.

6.4. maps library usage declaration

You must declare that your application uses the com.google.android.maps library in the application of your AndroidManifest.xml file. Please note that the usage declaration must be in the application tag otherwise you get java.lang.ClassNotFoundException for your Activity.

				
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.locationapi.maps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="com.google.android.maps" >
        </uses-library>

        <activity
            android:name="MapViewDemo"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

7. Device with Google API

In case you want to use Google Maps in your emulator you have to create a device which supports the Google API’s. This requires that you also install the “Google API”. During device creation select the target Google API’s in the version of your SDK.

8. Google Map key

To use Google Maps you need an additional key. See for following description:

			

http://code.google.com/android/add-ons/google-apis/mapkey.html

This process is a little bit time consuming and involves creating a value on the command line. This values is needed as input for a website which allow to create the key.

9. Google Maps

9.1. Create Project

Create a new Android project called “de.vogella.android.locationapi.maps” with an Activity called “ShowMapActivity”. Make sure to select the “Google API” als Target.

Add the following permissions to your application.

  • INTERNET
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION

9.2. Google Map library

You need to add the Google maps library to your application. Add “uses library” to “AndroidManifest.xml”.

				
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.locationapi.maps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="com.google.android.maps" >
        </uses-library>

        <activity
            android:name="MapViewDemo"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

9.3. Overlays

Create the following class. We will later use an image called “point”. But one icon with this name in your drawable folders.

				
package de.vogella.android.locationapi.maps;

import android.graphics.drawable.Drawable;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class MyOverlays extends ItemizedOverlay<OverlayItem> {

	private static int maxNum = 3;
	private OverlayItem overlays[] = new OverlayItem[maxNum];
	private int index = 0;
	private boolean full = false;
	private MyOverlays itemizedoverlay;

	public MyOverlays(Drawable defaultMarker) {
		super(boundCenterBottom(defaultMarker));
	}

	@Override
	protected OverlayItem createItem(int i) {
		return overlays[i];
	}

	@Override
	public int size() {
		if (full) {
			return overlays.length;
		} else {
			return index;
		}

	}

	public void addOverlay(OverlayItem overlay) {
		if (index < maxNum) {
			overlays[index] = overlay;
		} else {
			index = 0;
			full = true;
			overlays[index] = overlay;
		}
		index++;
		populate();
	}

}

9.4. Layout

The next step requires that you have created a valid key for using the MapView widget.

Change the “main.xml” layout file in your “res/layout” folder to the following. and replace “Your Maps API Key” with your Google Maps API key.

				
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="Your Maps API Key"
        android:clickable="true" />

</RelativeLayout>

9.5. Activity

Change your Activity to the following. This Activity use an LocationListner to update the MapView with the current location.

				
package de.vogella.android.locationapi.maps;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class ShowMapActivity extends MapActivity {

	private MapController mapController;
	private MapView mapView;
	private LocationManager locationManager;
	private MyOverlays itemizedoverlay;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main); // bind the layout to the activity

		// create a map view
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setStreetView(true);
		mapController = mapView.getController();
		mapController.setZoom(14); // Zoon 1 is world view
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, new GeoUpdateHandler());

		Drawable drawable = this.getResources().getDrawable(R.drawable.point);
		itemizedoverlay = new MyOverlays(drawable);
		createMarker();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public class GeoUpdateHandler implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			GeoPoint point = new GeoPoint(lat, lng);
			createMarker();
			mapController.animateTo(point); // mapController.setCenter(point);

		}		@Override
		public void onProviderDisabled(String provider) {
		}		@Override
		public void onProviderEnabled(String provider) {
		}		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}	private void createMarker() {
		GeoPoint p = mapView.getMapCenter();
		OverlayItem overlayitem = new OverlayItem(p, "", "");
		itemizedoverlay.addOverlay(overlayitem);
		mapView.getOverlays().add(itemizedoverlay);
	}
}

9.6. Run and Test

Run and test your application. You should be able to zoom in and out and send new geocoordinates to your map via the Emulator .

It will also draw Overlays on the Map.

10. Thank you

About these ads
Comments
  1. Saad Umair says:

    Good to see you (MAJU) guys working on Mobile Application Development. Keep it up and going! :)

  2. Natashia Sorg says:

    I feel this is one of the such a lot vital information for me. And i’m satisfied reading your article. But want to commentary on few normal things, The web site style is ideal, the articles is in point of fact great :D. Good job, cheers.

  3. e-tupakka foorumi says:

    I like this weblog very much, Its a real nice place to read and incur info .

  4. certified nursing assistant exam says:

    I am extremely impressed with your writing abilities and also with the structure on your weblog. Is this a paid topic or did you customize it your self? Anyway stay up the nice quality writing, it’s rare to look a nice blog like this one nowadays.

  5. music publishing and licensing says:

    I always was concerned in this topic and still am, thanks for posting .

  6. music licensing agencies says:

    Yay google is my world beater aided me to find this great web site ! . “The worst sin – perhaps the only sin – passion can commit, is to be joyless.” by Dorothy L. Sayers.

  7. teething remedies says:

    I always was concerned in this topic and stock still am, thank you for putting up.

  8. Felipe Windly says:

    I am very happy to read this. This is the type of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this greatest doc.

  9. gamestop says:

    Some truly select articles on this web site , saved to favorites .

  10. watch television jamaica online says:

    Hi! This is my 1st comment here so I just wanted to give a quick shout out and tell you I really enjoy reading through your articles. Can you suggest any other blogs/websites/forums that deal with the same topics? Many thanks!

  11. Buy scrapebox list says:

    Some genuinely interesting data, effectively written and typically user genial .

  12. film izle says:

    Hello admin excellent post significantly thanks beloved this webpage actually significantly

  13. cheap vacations says:

    Awesome news indeed. My friend has been awaiting for this tips.

  14. leslie sansoneu0027s walk strong dvd says:

    Howdy! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found it and I’ll be book-marking and checking back frequently!

  15. music mastering service says:

    Undeniably believe that which you stated. Your favorite reason appeared to be at the net the easiest factor to take into accout of. I say to you, I definitely get annoyed even as folks consider concerns that they plainly don’t understand about. You controlled to hit the nail upon the top and outlined out the entire thing without having side-effects , folks can take a signal. Will likely be back to get more. Thank you!

  16. Elvin Schoenrock says:

    Thank you for the good writeup. It in truth was a leisure account it. Look advanced to more added agreeable from you! However, how could we communicate?

  17. hybrid car emblem says:

    I have recently started a site, the info you provide on this website has helped me greatly. Thanks for all of your time & work.

  18. colleges with nursing programs says:

    I’ve recently started a blog, the info you offer on this site has helped me tremendously. Thank you for all of your time & work.

  19. site says:

    magnificent points altogether, you simply gained a brand new reader. What may you recommend in regards to your put up that you just made some days in the past? Any positive?

  20. eliminating credit card bills says:

    Someone essentially help to make significantly articles I’d state. This is the first time I frequented your web page and so far? I surprised with the research you made to make this actual post extraordinary. Excellent task!

  21. Sherell says:

    Wohh precisely what I was looking for, regards for posting.

  22. usc basketball romeo miller says:

    I like this website its a master peace ! Glad I detected this on google. “Americans will put up with anything provided it doesn’t block traffic.” by Dan Rather.

  23. hd televisions says:

    Nice advice and incredibly true. One of the vital essential issues bloggers, or any company, can do is strive to not ever supply up. Even when instances are powerful it is vital for being there on your readers and customers outcome they’re going to remember you inside a constructive light as soon issues recover and you may be rewarded to your efforts.

  24. Maurice says:

    Nice read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch as I found it for him smile Thus let me rephrase that: Thanks for lunch! “Bill Dickey is learning me his experience.” by Lawrence Peter Berra.

  25. credit card holder says:

    I think other web-site proprietors should take this web site as an model, very clean and great user friendly style and design, let alone the content. You are an expert in this topic!

  26. Financial Planning for Retirement says:

    I will right away seize your rss feed as I can’t in finding your e-mail subscription link or newsletter service. Do you’ve any? Please allow me know in order that I could subscribe. Thanks.

  27. yahoo blackjack games says:

    You are my aspiration , I possess few blogs and occasionally run out from to post .

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s