I have found this solution: here to get the location name but I don't know how to display it in my textView:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
t.append("\n " + ????? + " ");
}
}
The t is the textView
You have the name address in the String _Location. Therefore, you could set the value of TextView in the try block.
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
t.setText(_Location);
}
Further Infomation
String address1 = listAddresses.get(0).getAddressLine(0);
String city = listAddresses.get(0).getLocality();
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String postalCode = listAddresses.get(0).getPostalCode();
String knownName = listAddresses.get(0).getFeatureName();
t.setText(address1 + " " + city + "\n" + state + " " + postalCode);
You could use this code to get further information about the adress
Related
I am trying to get location name or address. I have successfully fetched the latitude and longitude by Google Fused Location API.
Now I want to fetch the location address (example : City name,Road no, or specific address) by using the latitude and longitude.
For this purpose I am using Google Geocoder and it works fine. But in some devices the location address returns the null value.
I searched in the net for the solution of this problem and found that some device manufacturers does not include this feature in their devices. That's why those device can't find the the address by Reverse Geocoding method. Here is the link of that information
So is there any alternative way to find the address name as string without Geoconding ?
Here is my code for fetching address by Geocoding
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
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(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
Use this its working for me
public class LocationAddress {
private static final String TAG = "LocationAddress";
private static String area = null;
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
area = address.getSubLocality();
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
/*result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;*/
bundle.putString("address", result);
bundle.putString("area",area);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
/* result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";*/
bundle.putString("address", result);
bundle.putString("area",area);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
To call this in your Activity use
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude,longitude,
getApplicationContext(), new GeocoderHandler());
GeocoderHandler
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress = null;
String area = null;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
area = bundle.getString("area");
break;
default:
locationAddress = null;
}
if(locationAddress != null)
locationAddress=locationAddress.replaceAll("[\r\n]+", " ");
Log.d("===========>>>",area);
Log.d("===========>>>>",locationAddress);
}
}
I am trying to get city in TextView using latitude and longitude. I am getting IndexOutOfBoundsException.
AndroidGPSTrackingActivity.java
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static com.example.khaledsb.location.R.id.lng;
import static java.util.Locale.*;
public class AndroidGPSTrackingActivity extends Activity {
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
final TextView lat =(TextView) findViewById(R.id.lat);
final TextView lon = (TextView) findViewById(R.id.longt);
final TextView addr = (TextView) findViewById(R.id.address);
// 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();
double Distance;
Distance = distFrom((float) 36.5925907, 2.9051544f, 36.5805505f, 2.914749f);
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Geocoder geocoder = new Geocoder(AndroidGPSTrackingActivity.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");
}
addr.setText(strReturnedAddress.toString());
}
else{
addr.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
addr.setText("Can not get Address!");
}
// \n is for new line
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+" " +
//" diastance "+Distance, 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();
}
}
});
}
}
I am getting the following error in logcat :
5-09 11:17:21.858 4501-4501/com.example.khaledsb.location E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.example.khaledsb.location.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:79)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Try
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
}
Use below code to get city name
Geocoder geocoder = new Geocoder(this);
try {
List<Address>addresses = geocoder.getFromLocation(latitude,longitue,1);
if (geocoder.isPresent()) {
StringBuilder stringBuilder = new StringBuilder();
if (addresses.size()>0) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String name = returnAddress.getFeatureName();
String subLocality = returnAddress.getSubLocality();
String country = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
String state = returnAddress.getAdminArea();
}
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
Try this code, Hope it helps..
private static String getRegionName(double lati, double longi) {
String regioName = "";
Geocoder gcd = new Geocoder(AppInstance, Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(lati, longi, 1);
if (addresses.size() > 0) {
regioName = addresses.get(0).getLocality();
}
} catch (Exception e) {
e.printStackTrace();
}
return regioName;
}
Try to use following code to get complete address,
//Get address from Google api
//Log.e("Else","else");
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
+ longitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject location = Results.getJSONObject(0);
finalAddress = location.getString("formatted_address");
}
} catch (Exception e) {
e.printStackTrace();
}
instead of,
geocoder.getFromLocation(latitude, longitude, 1);
For Avoid ArrayIndexOutOfBound you could add if condition like below:
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
}
but, as I saw your code you are trying to get address using GeoCoder inside button click, So avoid this because it is a network call. You should not perform network call in main thread, it could block UI Or Cause ANR. You should use AsyncTask/Thread for network operation to avoid blocking Of UI.
Also make sure you have added
INTERNET_PERMISSION
in your manifest file.
Hope It help you !
Error states that the Array list is empty so make sure you initialize the list and check if it contains any data.
try this code:
List<Address> addresses = new List<Address>;
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if(addresses != null) {
String address = addresses.get(0).getAddressLine(0);
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();
}
This should give you required info.
Fetching location address from latlong co-ordinates fetched from Location object.
#Override
public void onLocationChanged(Location location) {
String longitude = "Longitude: " + location.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + location.getLatitude();
Log.v(TAG, latitude);
String address = null;
String knownName = null;
String city = null;
String state = null;
String country = null;
String postalCode = null;
Geocoder gcd = new Geocoder(MainActivity.this.getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
address = addresses.get(0).getAddressLine(0);
if (addresses.get(0).getFeatureName() != address) {
knownName = addresses.get(0).getFeatureName();
}
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
String foundAddress = knownName + ", " + address + ", " + city + ", " + state + ", " + country + "- " + postalCode + "\n";
myLocation.setText(foundAddress);
storeLocation();
}
In my app I am using osm map. I have latitude and longitude.
using this method
proj = mapView.getProjection();
loc = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
String longitude = Double
.toString(((double) loc.getLongitudeE6()) / 1000000);
String latitude = Double
.toString(((double) loc.getLatitudeE6()) / 1000000);
Toast toast = Toast.makeText(getApplicationContext(), "Longitude: "
+ longitude + " Latitude: " + latitude, Toast.LENGTH_SHORT);
toast.show();
So from here how I will query to get the city name from osm database. Please help me.
How can I convert this into human understandable form. Here is my code which I am using.link
Try this code for getting address.
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);
for openstreammap
final String requestString = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" +
Double.toString(lat) + "&lon=" + Double.toString(lon) + "&zoom=18&addressdetails=1";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(requestString));
try {
#SuppressWarnings("unused")
Request request = builder.sendRequest(null, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
String city = "";
try {
JSONValue json = JSONParser.parseStrict(response);
JSONObject address = json.isObject().get("address").isObject();
final String quotes = "^\"|\"$";
if (address.get("city") != null) {
city = address.get("city").toString().replaceAll(quotes, "");
} else if (address.get("village") != null) {
city = address.get("village").toString().replaceAll(quotes, "");
}
} catch (Exception e) {
}
}
}
});
} catch (Exception e) {
}
here is my solution. i think it works for you also.
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
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.
What i have: currently my app is only telling me the coordinates of my current location.
What i want: Get location name from coordinates fetched by gps, so that i could know where exactly i am. (Name of location)
Here is complete code from fetching long - lat to getting address:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can us the GeoCoder which is available in android.location.Geocoder package. The JavaDocs gives u full explaination. The possible sample for u.
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
The result will return the name of the location.
Here i am given a single just pass the latitude and longitude in this function then you got all the information related to this latitude and longitude.
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I hope you get the solution to your answer.