Is there a way I can get the name of the city from my current location (Android)? I know how to get the lattitue/long but if there is a concrete example then better
thank you
Is there a way I can get the name of the city from my current location (Android)? I know how to get the lattitue/long but if there is a concrete example then better
thank you
Just use google's API
http://maps.googleapis.com/maps/api/geocode/json?latlng=<LAT>,<LNG>&sensor=true
Put your latitude and longitude in the right place and use a JSONObject to parse the results
Geocoder gcd = new Geocoder(context, Locale.getDefault());
try{
List<Address> addresses = gcd.getFromLocation(lat, lon, 1);//lat and lon is the latitude and longitude in double
if (addresses.size() > 0)
String cityName=addresses.get(0).getLocality();
}
catch (IOException e) {}
catch (NullPointerException e) {}
Try out this, hope it helps. Excuse the loop, just took it out from a recent work of mine.
Take a look at this link.
Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
for(int i=0; i<addresses.size(); ++i)
{
address = addresses.get(i);
string city = address.getLocality();
}
May be this article could could help you: http://www.devlper.com/2010/07/geocoding-and-reverse-geocoding-in-android/ It also provides its source code.
Else, from here:
public class AndroidFromLocation extends Activity {
double LATITUDE = 37.42233;
double LONGITUDE = -122.083;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
}
}
Also, check this concrete example: http://www.smnirven.com/blog/2009/10/09/reverse-geocode-lookup-using-google-maps-api-on-android-revisited/ and get the full code from here.