Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

To Add Device's current location to Google Maps

Author: Rachee Singh -- Published? false -- FormatLanguage: W

Problem:

Adding Current location of the device on Google maps.

Solution:

Using MyLocationOverlay class, current location of the device can be depicted on the Map.

Discussion:

Warning The Google Maps V1 API is deprecated; new code should use the V2 API discussed in Recipes 4285 and 4297.

Add the following permissions to the Android Manifest File:

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

Adding a mapView to your application, these few lines of code should be present in the XML layout. The Id of the map view is 'map'.

	<com.google.android.maps.MapView
	android:id="@+id/map"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:layout_below="@id/map_location_button"
	android:layout_above="@+id/use_this_location_button"
	android:clickable="true"
	android:apiKey = "Your API Key Should be placed here"/>

In the Java class for the activity which displays the map View, add a field:

	private MyLocationOverlay myLocationOverlay;

Also, get a handle to the map view defined in the XML and add a MyLocationOverlay. After that call the invalidate() method.

	mapView = (MapView)findViewById(R.id.map);
	myLocationOverlay = new MyLocationOverlay(this, mapView);
	mapView.getOverlays().add(myLocationOverlay);
	mapView.invalidate();

To prevent depletion of battery, in the onPause method of the class, disableMyLocation() method should be called.

@Override
	protected void onPause() {
	        super.onPause();
		myLocationOverlay.disableMyLocation();
	}

	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
	}

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LZGU1ZmIzYjUtZTY3OS00MjczLWIxNDAtNzY4NjI5ZWJmMzZj&hl=en_US&authkey=CNb-xe8C.
No records found.