Home > Android API > Android Location API

Android Location API

January 16th, 2009 Leave a comment Go to comments

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

  • kenji

    Can I get your example code?

    • admin

      We will update the post with the link to the code.

  • Shane

    Yeah can i also get a copy of your example code?

  • kenji

    can you send your code to my email? @admin

  • John Coryat

    Small error in your code:

    You have:
    p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);

    Should be:

    p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));

    The error is casting the coordinate to an integer before it gets multiplied.

    • Guest

      There is nothing wrong with that in language perspective. Casting operator bounds to the nearest subexpression that is lat or lng variable, and the constant literal 1000000 is an int. The * operator applies to (int,int) and produces int, which is exaclty what the ctor expects: http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/GeoPoint.html#GeoPoint(int, int)

      However the logic is wrong because (int)0.1*1000000 results in 0 instead of 100000.

      • http://profiles.google.com/alaeri Mouffe K rema

        I wish I had read that comment before I tried the above code. :)
        Anyway thanks to the OP and you.

  • shishir

    this is wat m getting in my logcat
    plz resolve

    package com.wissen.android.require unavailable shared libraray com.google.android.maps; ignoring

    package couldnt be installed in /data/app/com.wissen.android.apk

  • jean-marc

    Thanks for the excellent info. I run it well (not using the map just the location) when I use the emulator and send the new lat ond long.
    But on my phone the gps location never changed and I do not know how to exit the application.

  • lulala

    in your program you have a predefined latitude and longtitude at the start of the program. How is it possible for the android to get my current location without any hardcode input of location?

    I want android to detect my location (lat and long) on the start up of the program and place the “you are here” mark in that position.

  • Kj

    I was going through the code to find the problem, what’s causing the position of the map to be off and the fix from John works.

    You can start with the current location, by changing the geopoint to this (after getting the locationmanager):

    Location currentGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    p = new GeoPoint((int) (currentGPS.getLatitude() * 1000000), (int) currentGPS.getLongitude() * 1000000));

  • naik

    Hi

    i would like to know do we get Broadcast event when the location changes?

  • nimi

    hello …
    i change this activity in a service and it is called from Broadcast Receiver class.
    this was running good..but now my service got crashed..
    what is the region..
    plz help me

  • A.W.

    Can you give more details as to how to run the provided code? I extracted the hello folder and imported it into my eclipse workspace, but I’m not able to run it due to multiple errors

  • Wethiofr

    doesn’t compile when the posted file is imported into eclipse….=(

  • Superati

    Hi ,could you tell me how to set an zone location?
    Something like the javascript api’s
    ” ”
    how to do the same thing’s on android?

  • http://openchannel.co.kr Open Channel

    That’s it! Thank you so much.

  • Ofirbt

    Hi,
    There is an error in the code in the line: 
    p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);You should change it to:p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));Otherwise – you cast the double to int before the multiplication occurs…

  • ilavarasan

    hi, I need android source code to find location of google maps by giving address  in search field.for example if i type city name sydney in the text field and click the the search button the google map should show the location…..pls reply as soon as possible

  • Siabanie

    Thanks this tutorial – I have tried to follow and run the code but for some reason I got an error on my R file – It said I need to import R?
    As far as I know the resource field (R.java) located in gen folder and it generated itself. But on mine it seems not available. 
    It gives me some options either to ‘Import ‘R’ or Migrate Android Code and it will link to: http://tools.android.com/tips/non-constant-fields

    Can you suggest what went wrong on here?

  • Arjun Pola

    can someone plzz send the same code of this app…the present one is not working..plzz send it to arjun.pola@gmail.com

  • http://www.androidaspect.com/ Sunil@AndroidAspect

    Nice Tutorial…

  • Pingback: Mapping | NYUAD Mobile Media