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

Problem

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

Solution

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

Discussion

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

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView)findViewById(R.id.mapview);
        mapController = this.mapView.getController();
        mapController.setZoom(15);
        GeoPoint mapCenter = new GeoPoint(53554070, -2959520); 
        mapController.setCenter(mapCenter);
        myLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100, this);
    }

	@Override
	public void onLocationChanged(Location location) {
        int latitude = (int) (location.getLatitude() * 1E6);
        int longitude = (int) (location.getLongitude() * 1E6);
        GeoPoint geopoint = new GeoPoint(latitude, longitude);
        mapController.setCenter(geopoint);
        mapView.invalidate();
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		
	}

	@Override
	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

Download

https://docs.google.com/leaf?id=0B_rESQKgad5LNGViMzhmM2ItZGFiZC00NGVhLWJmNjctNTRjNTA0M2QzMjdh&hl=en_US