Hi I am working with android.I had created a GPS app for getting the current location.Now How can I get the country name from the latitude and longitude value ? is it possible ? please help me and thanks :)
here is my code I used
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
String countryCode,countryName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.i("location", " "+latitude+" "+longitude);
// \n is for new line
try
{Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude,longitude, 1);
if (addresses.size() > 0)
Toast.makeText(getApplicationContext(), "name "+addresses.get(0).getLocality(),Toast.LENGTH_SHORT).show();
//System.out.println(addresses.get(0).getLocality());
}
catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+countryName +" "+countryCode, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
@SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
Finally I got the solution, without lat and long value, i got country name.
String country = getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With