I reffred many questions from Stack overflow and implemented the above procedure. But I am unable to get the adress. Please let me know If i missed something.. ?
myLoc = (TextView) findViewById(R.id.id1);
Geocoder geocoder = new Geocoder(getBaseContext(),Locale.getDefault());
try {
address = geocoder.getFromLocation(latitude, longitude, 1);
if (address.size() > 0) {
for (int i = 0; i < address.get(0)
.getMaxAddressLineIndex(); i++) {
display = "";
display += address.get(0).getAddressLine(i)
+ "\n";
}
}
} catch (Exception e2) {
// TODO: handle exception
}
myLoc.setText("Current Location:"+display);
System.out.println(display);
You can use Reverse geo coding to and Google apis to get address from latitude and longitude.
Reverse Geo Coding:
double currentLatitude;
double currentLongitude;
void getAddress(){
try{
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
if (addresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < addresses.size(); i++){
Address address = addresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
result.append(",");
}
result.append(address.getLocality());
result.append(",");
result.append(address.getPostalCode());
result.append("\n\n");
}
addressText.setText(result.toString());
}
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
Google API: See this api which retrun address from latitude and longitude
http://maps.googleapis.com/maps/api/geocode/json?latlng=17.734884,83.299507&sensor=true
To know more read this
getMaxAddressLineIndex() returns an index which start from zero and thus your for-loop condition should be 0 <= maxIndex instead of 0 < maxIndex
You overwrite previous address lines on every iteration by assigning display = ""; and thus will end up with the last address line only. Is that on purpose?
Another good idea is to implement the LocationListener interface and register your Activity as a listener using LocationManager requestLocationUpdates() method. You can then override onLocationUpdate() to be informed whenever the location of the device changes. You provide the requestLocationUpdates() method the minimum amount of time that must pass before you will accept another update and how far the device must move before you get an update.
You can do like this to get complete address. In case you want country name
, state etc seperately .Then, I will not prefer you this method .
public class ParentHomeActivity extends AppCompatActivity {
...
private Geocoder geocoder;
private TextView mAddressTxtVu;
...
// I assume that you got latitude and longitude correctly
mLatitude = 20.23232
mLongitude = 32.999
String errorMessage = "";
geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
mlattitude,
mlongitude,
1);
} catch (IOException e) {
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +",
Longitude = " + mlongitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
// Log.i(TAG, getString(R.string.address_found));
mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
Related
I am trying to add twitter style add location to feed.
When I try to search cities for instance words starts with "new york" results comes with many different results with new york as image
My geocode is as below
public static List<String> getAddressesFromLocation(Context context, double lat, double lon) {
Locale current = context.getResources().getConfiguration().locale;
Geocoder coder = new Geocoder(context, current);
List<Address> addresses;
int maxResult = 5;
List<String> addressList = new ArrayList<String>();
try {
// May throw an IOException
addresses = coder.getFromLocation(lat, lon, maxResult);
if (addresses == null) {
return null;
}
for (int j = 0; j < addresses.size(); j++) {
Address returnedAddress = addresses.get(j);
String city = (returnedAddress.getLocality() == null || returnedAddress.getLocality().isEmpty()) ? "" : (returnedAddress.getLocality() + ", ");
String state = (returnedAddress.getAdminArea() == null || returnedAddress.getAdminArea().isEmpty()) ? "" : (returnedAddress.getAdminArea() + ", ");
String country = (returnedAddress.getCountryName() == null || returnedAddress.getCountryName().isEmpty()) ? "" : returnedAddress.getCountryName();
if((city == null || city.isEmpty()) && (state == null || state.isEmpty())){
continue;
}
if(city.equals(state)){
state = "";
}
addressList.add(city + state + country);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return addressList;
}
Everything works fine but with wrong results. What is the problem?
When I try to get default locale it returns "zz_ZZ":
countryCode: "ZZ"
languageCode: "zz"
Code is:
private String getAddressFromLocation(Location location) {
Geocoder geoCoder = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> matches = null;
try {
matches = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0) );
if (bestMatch != null){
String fullAddress = bestMatch.getAddressLine(0);
for (int i = 1; i <= bestMatch.getMaxAddressLineIndex(); i++){
fullAddress += ", " + bestMatch.getAddressLine(i);
}
return fullAddress;
}else{
return Constants.EMPTY_STRING;
}
} catch (IOException e) {
ACRA.getErrorReporter().handleSilentException(new MyGeoLocationAddressException(TAG + " ERROR CREATING ADDRESS - " + e.getMessage()));
return Constants.EMPTY_STRING;
}
}
Do I need to setDefaultLocale? What does ZZ_zz mean?
Second problem is:
If I use the "ZZ_zz" default locale, I don't get any address but if I use:
Locale.setDefault(Locale.ENGLISH);
I get the exact address.
ZZ_zz is the identifier for the Accented English locale and is mostly used for finding missing translations in your app.
I don't think there's a best practice on how to handle accented english, but treating it as english would probably be the best option.
You must handle locations in this way, check the scenario when no address is returned
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
// In this sample, get just a single address.
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " +
"Latitude = " + location.getLatitude() +
", Longitude = " +
location.getLongitude(), illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
Log.i(TAG, getString(R.string.address_found));
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
}
I want to get location address from LatLng
I tried some ways but i did not get answer, because it seems this service closed by google, so i getting timeout error when i using following code, is there another solution?
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
Try this function, it is working fine.
This is working fine, check code below and keep your geocoder.getFromLocation() method in try block
Click Here
Try this one
public static String getAddressInString(Context context, LatLng latLng) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses != null && addresses.size() > 0) {
return convertToString(addresses.get(0));
} else {
return "";
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String convertToString(Address obj) {
String add = "";
if (obj == null)
return "";
add = obj.getAddressLine(0);
if (obj.getSubAdminArea() != null)
add = add + "\n" + obj.getSubAdminArea();
if (obj.getPostalCode() != null)
add = add + " - " + obj.getPostalCode();
if (obj.getAdminArea() != null)
add = add + "\n" + obj.getAdminArea();
if (obj.getCountryName() != null)
add = add + "\n" + obj.getCountryName();
return add;
}
List<Address> addressList = geocoder.getFromLocationName(locationName, 5);
Log.d("size:",""+addressList.size());
The size always prints 1 . for example: I gave a street address marathahalli as a locationName . I got only 1 value but when i try the same street address in google map i get 10 address . please need some help or any links which can solve my problem .
I have used below code it is working for me, try this code.
String address = etEntreAddress.getText().toString();
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = new ArrayList<Address>();
addresses = geocoder.getFromLocationName(
TextUtils.htmlEncode(address), 5);
if (addresses != null) {
for (int j = 0; j < 1; j++) {
Address returnedAddress = addresses.get(j);
Log.i("address", "returnedAddress :" + returnedAddress);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm using a Geocoder to locate my location with address, postal code and country values included.
But getFromLocation(latitude,longitude,number) returns null, even though i use known location attributes ( Latitude: 40,645081 Longitude: 22,988892 ).
I'm testing my app on an AVD (API Level 7), using Eclipse.
Thanks in advance.
Here is a snippet of where the getFromLocation function is used.
private void updateWithNewLocation(Location location){
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
//double latitude = 73.147536;
//double longitude = 0.510638;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
Log.v("TRY_BODY", "All addresses are: " + addresses);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Log.v("IF_BODY", "All addresses are: " + addresses);
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
} catch (IOException e) {}
}
else {
latLongString = "No location found";
}
myLocationText.setText("Current Position:\n"+latLongString + "\n" + addressString);
}
Its very common, sometimes google server does not return any address, so that you should try it agian, it could be anything server busy, or somethimg else,
you can run this code in any thread with a loop, and if the address comes successfully, you can stop the loop and it will end the thread.