Tuesday, April 3, 2012

Where am I? Finding your location

One of the coolest thing that you can do with your Android device, is find your location!
In Android there are location-based services to get the current location of device. There are two ways to get the physical location:

  • Network Provider
  • GPS Provider
By LocationManager object we can retrieve latitude and longitude of last known location.
Now with these information and using Geocoder we get the addresses in the neighbours. Here's the code snippet:
// max of adresses near you
int max_result = 1;
// you can decide if use a network or gps provider
String provider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// get the last know location
Location location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
List<address> addresses = null;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
     addresses = gc.getFromLocation(latitude, longitude, max_result);
} catch (IOException e) {}
// return the string information
Toast.makeText(this, addresses.get(0).toString(), Toast.LENGTH_LONG)
This example assumes:

  •  that you have enabled the NETWORK_PROVIDER
  •  so you can add in the manifest file the ACCESS_FINE_LOCATION uses-permission

No comments :

Post a Comment