Wednesday, 30 May 2012

Obtain your current location

Now that you know how to use Google Maps API to display markers and custom drawings on it, you may want to get your own location. You should get the Location Manager service and add a listener to it. If you want immediate coordinates, call the LocationManager#getLastKnownLocation function.
If you want to use those coordinates on a Map, don't forget to multiply them by 1E6.
Here is a more detailed snippet describing it:
public void obtainCoordinates() {

 //defines criteria of the coordinates provider you want
 final Criteria criteria = new Criteria();

 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 final String bestProvider = this.locationManager.getBestProvider(
    criteria, true);

 //get immediate last known location if you want it
 Location location = this.locationManager.getLastKnownLocation(bestProvider);
 double longitude = 0.0;
 double latitude = 0.0;
 if (location != null) {
  latitude = location.getLatitude();
  longitude = location.getLongitude();
 if ((latitude == 0) && (longitude == 0)) {
  final MyLocationListener listener = new MyLocationListener();
  this.locationManager.requestLocationUpdates(bestProvider, 0, 0, listener);
 } else {
  //use your coordinates

Here is the listener to the coordinates:

public class MyLocationListener implements LocationListener {

 public void onLocationChanged(Location location) {
  double latitude = location.getLatitude();
  double longitude = location.getLongitude();
                //use your coordinates

 public void onProviderDisabled(String provider) {


 public void onProviderEnabled(String provider) {


 public void onStatusChanged(String provider, int status, Bundle extras) {


Of course, you need to add those permissions to your AndroidManifest.xml
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">

And don't forget to call LocationManager#removeUpdates on the listener when you don't need GPS coordinates anymore.

1 comment:

  1. When it comes to gaming consoles, there is always a big fight between Sony's Playstation and Microsoft's XBox. Now this rivalry is going to increase even more because Microsoft is getting ready to launch it's next console, the Xbox 2. You can check out all the details from my site here Xbox 2 Release Date