Wednesday 12 December 2012

android: User Current location

Note: Enable your provider


locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

if (location != null) {
System.out.println("Provider " + provider + " has been selected.");

} else {
Toast.makeText(this, "Provider not available",
Toast.LENGTH_SHORT).show();
}

double lat = location.getLatitude();
double lng = location.getLongitude();
String addressString = "no address found";
           Geocoder gc = new Geocoder(this, Locale.getDefault());
           try
           {
               List<Address> addresses = gc.getFromLocation(lat,
                       lng, 1);
               StringBuilder sb = new StringBuilder();
               if (addresses.size() > 0)
               {
                   address = (Address) addresses.get(0);
                   sb.append(address.getLocality());
               }
               addressString = sb.toString();
           
           } catch (Exception e)
           {
           }
           Toast.makeText(this,"Your Current Location is :"+String.valueOf(addressString),
    Toast.LENGTH_SHORT).show();
           System.out.println(String.valueOf(addressString));
                   Toast.makeText(this,address.getLocality(),
     Toast.LENGTH_SHORT).show();

No comments:

Post a Comment