How to get address from latitude and longitude android? - android

I have an application that will get the latitude and the longitude of the users location. What I need to know is how do I take the latitude and the longitude of the location and convert it into just the address of the user?
Thanks for any help.

You can use GeoCoding. Follow the instructions on this link where it says Geocoding and Reverse Geocoding
You can find code there that you can try it out on your own app (copy/paste)
I hope it helps :)

Try using Geocoder

try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(MainActivity.this);
Toast.makeText(this, "before if",
Toast.LENGTH_LONG).show();
if (latitude != 0 || longitude != 0) {
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);
Log.d("TAG", "address = "+address+", city ="+city+", country = "+country );
Toast.makeText(this, "address = "+address+", city ="+city+", country = "+country, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "latitude and longitude are null",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}

Related

App crashes when I click on ocean or sea to get city name in maps

Error
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0.
This is my code.
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Geocoder geocoder;
geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
if (city == null) {
Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapsActivity.this, "" + city, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
GeoCoder might not return a result in all cases, since a sea or ocean might not have an address.
In this case the list of results called addresses will have 0 items, but you still try to access to first item.
You should do something like this:
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses.size() == 0) {
Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
return;
}
// ... rest of the code

Failed to retrieve street address from cordinates

I am trying to get the full address by providing longitude and latitude coordinates. for now i succedd to get the coordinates correctly
this is what i get:
my coordinates﹕ 32.6653854,35.1051237
now when i use getCompleteAddressString()
i get all the time exception:
Current location address﹕ Can not get Address!
this is my getCompleteAddressString function:
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, 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 location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
and this is the class where i try to run it:
#Override
public void updateUI() {
Log.d("my location","updateUI");
Log.d("get coordinates","my location");
String realAddress = myLocManager.getCompleteAddressString(myLocManager.getmLastLocation().getLatitude(),myLocManager.getmLastLocation().getLatitude(),this.getActivity().getApplicationContext());
Log.d("my coordinates", String.valueOf(myLocManager.getmLastLocation().getLatitude()+","+myLocManager.getmLastLocation().getLongitude()));
Log.d("my real address",realAddress);
if(realAddress != null)
streetAddress.setText(realAddress);
}
i try to run updateUI also with getActivity() method but still i got the same error.
when i used LocationManager in other app it was work good.
it was my mistake i call the method with the wrond parameters:
getmLastLocation().getLatitude(),myLocManager.getmLastLocation().getLatitude()
i pass the Latitude param twice

How to zoom to a country by name in an Android application

How to zoom to a country by name in an Android application(google map)? IF I get a coutry name Ireland then the map location to the Ireland
1 Get location by country name
Geocoder geocoder = new Geocoder(<your context>);
List<Address> addresses;
addresses = geocoder.getFromLocationName(<String address>, 1);
if(addresses.size() > 0) {
double latitude= addresses.get(0).getLatitude();
double longitude= addresses.get(0).getLongitude();
}
2 Zoom to current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
You can use the Geocoder API to fetch the location based on the country name and then animate the map camera to that position:
try {
List<Address> address = new Geocoder(this).getFromLocationName("Ireland", 1);
if (address == null) {
Log.e(TAG, "Not found");
} else {
Address loc = address.get(0);
Log.e(TAG, loc.getLatitude() + " " + loc.getLongitude());
LatLng pos = new LatLng(loc.getLatitude(), loc.getLongitude())
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 14));
}
} catch (IOException e) {
e.printStackTrace();
}

Geocoding android - Finding address based on coordinates

I've put together this little function in my android app:
protected void toAddress(double lat, double lng, int maxResults) {
String address = null;
Geocoder gcd = new Geocoder(TarsActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(lat, lng, maxResults);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
address = addresses.get(0).getLocality().toString();
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_LONG );
}
else
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG);
}
The function call goes like this
toAddress(location.getLatitude(), location.getLongitude(), 10);
But the app doesn't display any Toast with the address? I've debugged it and the correct address is in the addresses-list. As you can see I've tried to convert it to a string with the toString()-function. Anybody? Thanks in advance!
Try:
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_LONG ).show();
You are not calling .show() after you create the Toast.

cannot get place from google map using location

I try to get place(ex: locality, country, postal code) form google map using
latitude and longitude. The following is my code that got null data:
Edit:
public void onLocationChanged(Location location) {
geocoder = new Geocoder(this, Locale.getDefault());
if (location != null) {
try {
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
if (addresses.size() > 0) {
resultAddress = addresses.get(0);
locality = resultAddress.getLocality();
sublocality = resultAddress.getSubLocality();
postalcode = resultAddress.getPostalCode();
country = resultAddress.getCountryName();
adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I tried to assign latitude and longitude manually, but got nothing.
Any one can correct my mistakes ? Thank you
I think the problem is on the parameters of the method. I guess that location is a GeoPoint In that case, instead of
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
try this:
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
because the coordinates in a geopoint are represented in microdegrees
Edit
I copied your code and tried it. Assuming your "location" object is a GeoPoint, the code that works is as follows:
GeoPoint location = new GeoPoint(lat, lon);
if (location != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitudeE6()/1E6,
location.getLongitudeE6()/1E6, 1);
if (addresses.size() > 0) {
Address resultAddress = addresses.get(0);
String locality = resultAddress.getLocality();
String sublocality = resultAddress.getSubLocality();
String postalcode = resultAddress.getPostalCode();
String country = resultAddress.getCountryName();
String adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
however, if you are testing it on the emulator, be sure you have internet connection. Otherwise, the method "getFromLocation" cannot find out the address and won't display anything. If you don't have any error in the logcat and the problem is only that nothing is displayed, that is the problem: no network.
Do you have the <uses-permission android:name="android.permission.INTERNET" /> in manifest.xml?

Categories

Resources