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

Author: Rachee Singh ('racheesingh')
In Published Edition? Yes
FormatLanguage: WikiFormat

Getting Location Updates with OpenStreetMap Maps


You need to react to the changes in the device's location and move the map focus to changed location


Using LocationListener, an application can request for location updates and then react to these changes in location


public class LocationChange extends Activity implements LocationListener {
    private LocationManager myLocationManager;
	private MapView mapView;
	private MapController mapController;

    public void onCreate(Bundle savedInstanceState) {
        mapView = (MapView)findViewById(R.id.mapview);
        mapController = this.mapView.getController();
        GeoPoint mapCenter = new GeoPoint(53554070, -2959520); 
        myLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100, this);

	public void onLocationChanged(Location location) {
        int latitude = (int) (location.getLatitude() * 1E6);
        int longitude = (int) (location.getLongitude() * 1E6);
        GeoPoint geopoint = new GeoPoint(latitude, longitude);

	public void onProviderDisabled(String arg0) {

	public void onProviderEnabled(String arg0) {

	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

When the application starts, the map is centered around the mapCenter GeoPoint. Since the application is listening to location changes, the icon in the top bar of the phone is visible:

Now using the Emulator controls new GPS coordinates (-122.094095, 37.422006) are sent to the emulator. The application reacts to it and centers the map around then new coordinates:

Similarly, different GPS coordinates are given from the Emulator controls and the application centers the map around the new location:

Also, to allow the application to listen for location changes, include these permissions in the AndroidManifest.

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

See Also