Archive

Posts Tagged ‘Android Location APIs’

Android Location API

January 16th, 2009

Android support Location based service APIs. Location service allows to find out the device current location. The application can ask for periodic update of the device location. The application can also register a intent receiver for proximity alerts like when the device is entering and existing from an area of given longitude, latitude and radius.

Let’s check the important classes present in the android.location package.

Android Location API:

Following are the some important classes present under the android location package.

LocationManager: The class provides access to the location service. It also provides facility to get the best Location Provider as per the criteria. Proximity alerts can be set (as said above) with help of this class.

LocationProvider: It’s an abstract superclass for location providers. A location provider provides periodic reports on the geographical location of the device.

LocationListener: Provides callback methods which are called when location gets changed. The listener object has to be registered with the location manager.

Criteria: The class provides the application to choose suitable Location Provider by providing access to set of required properties of the LocationProvider.

Android also provide an API to access the Google MAPs. So with the help of the Google MAPs and the location APIs the application can show required places to the user on the MAP. Let’s see Android support for the Google APIs.

Google Map API

Android defines a package called com.google.android.maps. The package contains classes related to rendering, controlling and overlaying information on the Google maps on the android devices. Let’s see the most important classes defined in the package:

MapActivity: It is the spacing activity defined to show the Google MAPs. The MapActivity takes care of the low-level networking.

MapView: MapView is the view that supports and displays the map. This must be contained by a MapActivity.

MapController : MapController is the object used to move the map around the screen.

Overlay: It’s a drawable object that can be shown on top of the map.

GeoPoint: It’s a position in latitude-longitude.

Now we have some basic knowledge of the Location and Map APIs, so let’s create some application and see them in action.

Application:

Let’s develop an application that shown the Google MAP on the screen and shows the user’s current position on the MAP. We will use Google MAP APIs to show map on the device and then use location APIs to get the device current location to show it on the MAP. The user location will gets updated if the user moved from the current location.

Application Activity:

To use map in an activity that activity has to be extended by the MapActivity as shown..

class MyGPSActivity extends MapActivity {
...
}

To use the Google MAP APIs, application AndroidManifest.xml file must define following XML element, as a child of the application element:

<uses-library android:name=”com.google.android.maps” />

Using the MapView:

To display Map we need to add MapView to the application. Add following in the activity’s layout file (main.xml).

<com.google.android.maps.MapView
android:id="@+id/myGMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="API_Key_String"
/>

To use the Google Map service an API key is needed. The API key can obtained as follows:

1) Get debug.keystore file. You will get this under USER_HOME\Local Settings\Application Data\Android directory.

2) Use keytool tool to generate Certificate fingerprint (MD5). Use following command on command prompt

keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android

3) Go to ‘Sign Up for the Android Maps API‘ page.  Put your Certificate fingerprint (MD5) And get your API key for android GMap application.

4) Replace “API_Key_String” with your API key.

Update the MyGPSActivity class to use the MapView

class MyGPSActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
// Creating and initializing Map
gMapView = (MapView) findViewById(R.id.myGMap);
GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (long * 1000000));
gMapView.setSatellite(true);
//get MapController that helps to set/get location, zoom etc.
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(14);
}
...
}

Certain permission has to be set in the AndroidManifest.xml file to use location information.

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

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

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

Using Location Manager:

The location manage object can be obtained with Context.getSystemService method with Context.LOCATION_SERVICE parameter.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Update the GPSActivity to implement the LocationListener interface so that the activity can listener to the location changes.

class MyGPSActivity extends MapActivity implements LocationListener {
...
/* This method is called when use position will get changed */
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected boolean isRouteDisplayed() {
return false;
}

}

Lets add code to initialize the LocationManager and register the Location Listener with the location manager in the onCreate() method

@Override

public void onCreate(Bundle savedInstanceState) {
...
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);

}

Now the onLocationChanged method of the GPSActivity method will be called if the user changes its position by 500m. A “gps” (GSP_PROVIDER) provider is used here but you can obtain a provider object as per your needs with the getBestProvider method of the LocationManger and the Criteria object.

Here is the implementation of the onLocationChanged method

public void onLocationChanged(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}

}

The code changes the map location to the new updated location.

We can add extra things in our application like Zoom controls, Marker and Text to show current location etc.

Adding Zoom control:

The MAP api provides facility to add zoom control to the map display. Following code add zoom control to your application:

// Adding zoom controls to Map

ZoomControls zoomControls = (ZoomControls) gMapView.getZoomControls();

zoomControls.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT));

gMapView.addView(zoomControls);

gMapView.displayZoomControls(true);

Adding Map Overlay:

A map overlay can be added showing the user’s current location. To add an overlay, define a class that will extend Overlay class.

class MyLocationOverlay extends com.google.android.maps.Overlay {
@Override

public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {

super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
// Converts lat/lng-Point to OUR coordinates on the screen.
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 255, 255, 255);
paint.setStyle(Paint.Style.STROKE);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
canvas.drawText("Here I am...", myScreenCoords.x, myScreenCoords.y, paint);
return true;

} }

The overlay display a text “Here I am..” on the map at user location.

Let’s add this overlay to our map view

// Add a location mark

MyLocationOverlay myLocationOverlay = new MyLocationOverlay();

List<Overlay> list = gMapView.getOverlays();

list.add(myLocationOverlay);

Running application on Emulator:

Run the emulator instance. The latitude and longitude values can be supplied to the emulator with the help of ‘Emulator Control’ window present in the DDMS eclipse perspective. According to latitude and longitude application will display location of user.

gpsapp

Download the sample code here

Android API , , ,