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

I am building an android application where I am using TouchableWrapper class for getting latitude & longitude.When a user removes the finger, the camera center position latitude and longitude are parsed and shown in a toast.
Now all I need is the address at that latitude and longitude.
Here is code that I am using to get latitude and longitude:
public class MainActivity extends FragmentActivity implements TouchActionDown, TouchActionUp {
CameraPosition mDownCameraPosition;
CameraPosition mUpCameraPosition;
ImageView submitbtn,mappoint;
String addressfixed,completed;
EditText whitebord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintut);
// get data views
mappoint = (ImageView) findViewById(R.id.mappoint);
whitebord = (EditText) findViewById(R.id.searchmapedit);
mappoint.setImageResource(R.drawable.point);
submitbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
getMap().getMap().setMyLocationEnabled(true);
getMap().getMap().setOnMapLoadedCallback(
new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
Location myLocation = getMap().getMap().getMyLocation();
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30)
.build();
getMap().getMap().animateCamera(
CameraUpdateFactory
.newCameraPosition(myPosition));
}
});
}
#Override
protected void onResume() {
super.onResume();
// check google play services
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, 1).show();
}
}
#Override
public void onTouchDown(MotionEvent event) {
mDownCameraPosition = getMap().getMap().getCameraPosition();
}
#Override
public void onTouchUp(MotionEvent event) {
mUpCameraPosition = getMap().getMap().getCameraPosition();
getMap().getMap().clear();// to remove previous marker
MarkerOptions options = new MarkerOptions()
.title("This is your selected place to host game")
.position(
new LatLng(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude));
new GetAddressTask(getApplicationContext()).execute();
}
private SupportMapFragment getMap() {
return ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
}
public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
public GetAddressTask (Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground (android.location.Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
android.location.Location location = params[0];
Location markerLocation = getMap().getMap().getMyLocation();
List<Address> addresses = null;
try {
if (mByMap && markerLocation != null) {
addresses = geocoder.getFromLocation(markerLocation.getLatitude(),
markerLocation.getLongitude(), 1);
} else if (!mByMap && location != null) {
addresses = geocoder.getFromLocation(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude, 1);
}
} catch (IOException exception) {
Log.e("ComplaintLocation",
"IO Exception in getFromLocation()", exception);
// handler.post(new Runnable() {
//
// #Override
// public void run() {
// Toast.makeText(mContext,
// mContext.getString("Updating your location failed"),
// Toast.LENGTH_SHORT).show();
// }
// });
return ("IO Exception trying to get address");
} catch (IllegalArgumentException exception) {
String errorString = "Illegal arguments " +
Double.toString(location.getLatitude()) + " , " +
Double.toString(location.getLongitude()) + " passed to address service";
Log.e("LocationSampleActivity", errorString, exception);
return errorString;
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getMaxAddressLineIndex() > 0) {
return String.format(
"%s/%s/%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getThoroughfare(), // 2
address.getSubThoroughfare(), //3
address.getPostalCode(), // 4
address.getLocality()); // 5
} else {
return String.format(
"%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getPostalCode(), // 2
address.getLocality()); // 3
}
} else return "No address found";
}
// Format address string after lookup
#Override
protected void onPostExecute (String address) {
String[] addressFields = TextUtils.split(address, "/");
Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
// Log.d("LOCATION", "Using " + mProvider);
// Workaround: doInBackground can only return Strings instead of, for example, an
// Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
// on fields returned by this method, set each String that currently reads "null" to
// a null reference
for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
if (addressFields[fieldcnt].equals("null"))
addressFields[fieldcnt] = null;
}
String mStreet,mHouseNumber,mLatitude,mLongtitude,mPostalCode,mCity;
switch (addressFields.length) {
case 4:
mStreet = null;
mHouseNumber = null;
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mPostalCode = addressFields[2];
mCity = addressFields[3];
break;
case 6:
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mStreet = addressFields[2];
mHouseNumber = addressFields[3];
mPostalCode = addressFields[4];
mCity = addressFields[5];
break;
default:
mLatitude = null;
mLongtitude = null;
mStreet = null;
mHouseNumber = null;
mPostalCode = null;
mCity = null;
break;
}
Toast.makeText(getApplicationContext(), mStreet,
Toast.LENGTH_LONG).show();
}
}
private boolean mByMap;
// Lookup address via reverse geolocation
public void lookUpAddress (boolean byMap) {
mByMap = byMap;
if (Geocoder.isPresent()) {
// (new GetAddressTask(mContext)).execute(mCurrentBestLocation);
}
}
private SupportMapFragment getMap() {
return ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
}
}
Any help would be greatly appreciated.

You can get address by GeoCoder Object
note that you will receive a list of suggested addresses.
Here in the example I take the first one
Geocoder geocoder;
List<Address> yourAddresses;
geocoder = new Geocoder(this, Locale.getDefault());
yourAddresses= geocoder.getFromLocation(yourLatitude, yourLongitude, 1);
if (yourAddress.size() > 0)
{
String yourAddress = yourAddresses.get(0).getAddressLine(0);
String yourCity = yourAddresses.get(0).getAddressLine(1);
String yourCountry = yourAddresses.get(0).getAddressLine(2);
}

You can use GeoCoder for the purpose of finding a Location Address by providing latitude and longtitude as described in the Android Developer Guidelines: Displaying a Location Address
Because I had trouble finding it when I was searching for it recently: You can get the street by using Address's getThoroughfare (and getSubThoroughfare) getter methods.
Create a new class GeoLocation, copy the following into it:
package com.stackoverflow.hitesh.geocoder;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class GeoLocation {
private Context mContext;
private String mLatitude;
private String mLongtitude;
private String mStreet;
private String mHouseNumber;
private String mPostalCode;
private String mCity;
private Location mMarkerLocation;
public GeoLocation (Context context) {
mContext = context;
}
public String getStreet () {
return mStreet;
}
public String getHouseNumber () {
return mHouseNumber;
}
public String getPostalCode () {
return mPostalCode;
}
public String getCity () {
return mCity;
}
public String getLatitude () {
return mLatitude;
}
public String getLongtitude () {
return mLongtitude;
}
// Lookup address via reverse geolocation
// Call this one
public void lookUpAddress (Location markerLocation) {
mMarkerLocation = markerLocation;
if (Geocoder.isPresent()) {
(new GetAddressTask(mContext)).execute();
}
}
public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
public GetAddressTask (Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground (android.location.Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
android.location.Location location = params[0];
List<Address> addresses = null;
try {
if (mMarkerLocation != null) {
addresses = geocoder.getFromLocation(mMarkerLocation.getLatitude(),
mMarkerLocation.getLongitude(), 1);
}
} catch (IOException exception) {
Log.e("ComplaintLocation",
"IO Exception in getFromLocation()", exception);
return ("IO Exception trying to get address");
} catch (IllegalArgumentException exception) {
String errorString = "Illegal arguments " +
Double.toString(location.getLatitude()) + " , " +
Double.toString(location.getLongitude()) + " passed to address service";
Log.e("LocationSampleActivity", errorString, exception);
return errorString;
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getMaxAddressLineIndex() > 0) {
return String.format(
"%s/%s/%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getThoroughfare(), // 2
address.getSubThoroughfare(), //3
address.getPostalCode(), // 4
address.getLocality()); // 5
} else {
return String.format(
"%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getPostalCode(), // 2
address.getLocality()); // 3
}
} else return "No address found";
}
// Format address string after lookup
#Override
protected void onPostExecute (String address) {
String[] addressFields = TextUtils.split(address, "/");
Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
// Workaround: doInBackground can only return Strings instead of, for example, an
// Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
// on fields returned by this method, set each String that currently reads "null" to
// a null reference
for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
if (addressFields[fieldcnt].equals("null"))
addressFields[fieldcnt] = null;
}
switch (addressFields.length) {
case 4:
mStreet = null;
mHouseNumber = null;
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mPostalCode = addressFields[2];
mCity = addressFields[3];
break;
case 6:
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mStreet = addressFields[2];
mHouseNumber = addressFields[3];
mPostalCode = addressFields[4];
mCity = addressFields[5];
break;
default:
mLatitude = null;
mLongtitude = null;
mStreet = null;
mHouseNumber = null;
mPostalCode = null;
mCity = null;
break;
}
Log.d("GeoLocation Street", mStreet);
Log.d("GeoLocation No.", mHouseNumber);
Log.d("GeoLocation Postalcode", mPostalCode);
Log.d("GeoLocation Locality", mCity);
Log.d("GeoLocation Lat/Lng", "[" + mLatitude + ", " + mLongtitude + "]");
}
}
}
You then instantiate it using
GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if called from an activity and not from a fragment
mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
Of course, you have to replace LOCATION_FROM_MAP with the Location object you get from your map.

use this code for converting latitude and longitute to address on camera change
#Override
public void onCameraChange(CameraPosition cameraPosition)
{
mGoogleMap.setOnMapLoadedCallback(this);
}
#Override
public void onMapLoaded()
{
LatLng position = mGoogleMap.getCameraPosition().target;
double Lat = position.latitude;
double Long = position.longitude;
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
addresses = geocoder.getFromLocation(Lat, Long, 1);
if (addresses != null && addresses.size() > 0)
{
String address = addresses.get(0).getAddressLine(0);
String address11 = addresses.get(0).getAddressLine(1);
String city = addresses.get(0).getLocality();
}
}
catch (IOException e) {
}
}
and call onCameraChangeListener in onMapReady after map load
mGoogleMap.setOnCameraChangeListener(this);

Related

Android Google Maps stop unfortunately on other device

Why my GoogleMaps is making my app stop unfortunately when I run it in another devices? Here is my code:
mapFragment.getMapAsync(this);
prefs = getSharedPreferences(AppConstants.LOGIN_PREFS,
Context.MODE_PRIVATE);
}
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<android.location.Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Click here"));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String frst = address.getLocality();
Double lat=address.getLatitude();
Double longi=address.getLongitude();
SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
editor.putString(AppConstants.CITYNAME, frst);
editor.putString(AppConstants.LAT,""+lat);
editor.putString(AppConstants.LONG,""+longi);
editor.commit();
Intent intent = new Intent(MapsActivity.this, MainActivity.class);
startActivity(intent);
}
});
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
protected void onResume() {
super.onResume();
// create class object
final GPSTracker gps = new GPSTracker(MapsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
if (latitude != 0.0 && longitude != 0.0) {
if (Utils.isNetworkAvailable(MapsActivity.this))
sendGetAddressRequest(latitude, longitude);
else
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
if (latitude != 0.0 && longitude != 0.0) {
if (Utils.isNetworkAvailable(MapsActivity.this)) {
sendGetAddressRequest(latitude, longitude);
} else
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MapsActivity.this, "couldn't get your current location enter manually", Toast.LENGTH_LONG).show();
}
}
}, 10000);
}
} else {
}
}
private void sendGetAddressRequest(double latitude, double longitude) {
// lat.setText("latitude" + latitude);
if (Utils.isNetworkAvailable(MapsActivity.this)) {
getAddressAsync = new GetAddress(latitude, longitude);
getAddressAsync.execute();
} else {
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
}
}
private class GetAddress extends AsyncTask<String, String, String> {
double latitude, longitude;
public GetAddress(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
#Override
protected String doInBackground(String... params) {
String result = null;
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + latitude + "," + longitude + "&ka&sensor=false");
// Log.d(TAG, "CURRENT ADDRESS API : " + "http://maps.google.com/maps/api/geocode/json?address=" + latitude + "," + longitude + "&ka&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
result = jsonObject.toString();
// Log.d(TAG, "Address : " + result);
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressBar.setVisibility(View.VISIBLE);
// progressBar.setClickable(true);
// currentLocation.setVisibility(View.GONE);
}
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject result = new JSONObject(s);
if (result.has("results")) {
JSONArray array = result.getJSONArray("results");
if (array.length() > 0) {
JSONObject place = array.getJSONObject(0);
JSONArray components = place.getJSONArray("address_components");
for (int i = 0; i < components.length(); i++) {
JSONObject component = components.getJSONObject(i);
JSONArray types = component.getJSONArray("types");
for (int j = 0; j < types.length(); j++) {
if (types.getString(j).equals("locality")) {
cityName = component.getString("long_name");
} else if (types.getString(j).equals("premise")) {
plot = component.getString("long_name");
} else if (types.getString(j).equals("sublocality_level_1")) {
area = component.getString("long_name");
} else if (types.getString(j).equals("administrative_area_level_1")) {
state = component.getString("long_name");
} else if (types.getString(j).equals("postal_code")) {
postalCode = component.getString("long_name");
} else if (types.getString(j).equals("country")) {
country = component.getString("long_name");
}
}
}
formattedAddress = place.getString("formatted_address");
onMapReady(mMap);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(TAG, "Locality : " + cityName + ", Area : " + area + ", State : " + state + ", PostalCode : " + postalCode + ", Country : " + country);
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng latlng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latlng).draggable(true).title("Current Location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(30));
// mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
// #Override
// public void onInfoWindowClick(Marker marker) {
//
// Intent intent = new Intent(MapsActivity.this, MainActivity.class);
// intent.putExtra("City",cityName);
// intent.putExtra("Area",area);
// intent.putExtra("State",state);
// intent.putExtra("PostalCode",postalCode);
// intent.putExtra("Country",country);
// intent.putExtra("Plot",plot);
// startActivity(intent);
//
// }
// });
}
}
When I run my app on other devices, it crashes sometimes but when I run it on my phone, it works fine. On most of devices, I got a crash.
I don't know where it is throwing an exception.
Suggest me something guys, please, I'm stuck in this from a very long time. I want to fix it on every phone.

how to convert longitude and latitude into text format to show street address?

I am developing an app,In this I'm using google map to show users current location.
Following code I am using but it doesn't give the result of street address only shows the current location in map and shows longitude and latitude.How do I show the current street address in text field from current longitude and latitude?
//java
public class LocationActivity extends Activity {
private TextView locationText;
private TextView addressText, textview;
private GoogleMap map;
String mob_no;
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
// textview=(TextView)findViewById(R.id.textView_euser);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available");
// textview.setText(String.valueOf(mob_no));
//replace GOOGLE MAP fragment in this Activity
replaceMapFragment();
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
// getCompleteAddressString(longitude,latitude);
}
};
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
/* #SuppressLint("LongLogTag")
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("Address:");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
addressText.setText(strAdd);
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;
} */
}
//getaddress
public class GetAddressTask extends AsyncTask<String, Void, String> {
private LocationActivity activity;
public GetAddressTask(LocationActivity activity) {
super();
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(activity, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(params[0]), Double.parseDouble(params[1]), 1);
//get current Street name
String address = addresses.get(0).getAddressLine(0);
//get current province/City
String province = addresses.get(0).getAdminArea();
//get country
String country = addresses.get(0).getCountryName();
//get postal code
String postalCode = addresses.get(0).getPostalCode();
//get place Name
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
return "Street: " + address + "\n" + "City/Province: " + province + "\nCountry: " + country
+ "\nPostal CODE: " + postalCode + "\n" + "Place Name: " + knownName;
} catch (IOException ex) {
ex.printStackTrace();
return "IOE EXCEPTION";
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return "IllegalArgument Exception";
}
}
/**
* When the task finishes, onPostExecute() call back data to Activity UI and displays the address.
* #param address
*/
#Override
protected void onPostExecute(String address) {
// Call back Data and Display the current address in the UI
activity.callBackDataFromAsyncTask(address);
}
}
You can use Double.toString() to convert a double to a String. Alternatively, you can use +:
"" + latitude
If you need more control over the output, such as the number of decimal places to display, you can use String.format().
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");
}
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);
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);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
more info please check below link:-
http://javapapers.com/android/android-get-address-with-street-name-city-for-location-with-geocoding/
its helps to you

How to get Current Location(Street,City, etc,..) using gps in Android

I want to create a app to Track the Users who installed my App, So i have a following code for tracking, This code working good but it will return only CITY NAME. But i need full details like street name, city, like wise .
public class GetCurrentLocation extends Activity
implements OnClickListener {
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to" +
" see the changes in coordinates." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Try this :
public void setCurrentLocation() {
if (UtilityMethods.isGPSEnabled(mContext)) {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
// return;
} else {
getCurrentAddress();
}
} else {
alertbox("Gps Status", "Your Device's GPS is Disable", mContext);
}
}
Using LocationManager
public void getCurrentAddress() {
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
try {
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (Exception ex) {
Log.i("msg", "fail to request location update, ignore", ex);
}
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (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 locality = addresses.get(0).getLocality();
String subLocality = addresses.get(0).getSubLocality();
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 (subLocality != null) {
currentLocation = locality + "," + subLocality;
} else {
currentLocation = locality;
}
current_locality = locality;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(HomeActivity.this, Constants.ToastConstatnts.ERROR_FETCHING_LOCATION, Toast.LENGTH_SHORT).show();
}
}
}
Use fused Location Provider to get current device latitude and longitude.
With the help of latitude and longitude, you can get city name and address.
To get full street name, use getMaxAddressLineIndex().
In onLocationChanged, check whether you are getting current location or not.
Edit:
String strAdd = "";
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(TabClubActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (!addresses.isEmpty()) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(" ");
}
strAdd = strReturnedAddress.toString();
textview.setText(strAdd);
Log.e("MyCurrentLoctionAddress", "" + strReturnedAddress.toString());
cityName=addresses.get(0).getLocality();
} else {
// Log.e("MyCurrentLoctionAddress", "No Address returned!");
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
I tried the Geocoder however the results are unreliable. So better go for the nearbysearch googleapi for the result. It provides the city name directly. Here's the version of my implementation.
interface Api{
String BASE_URL = "https://maps.googleapis.com";
#GET("/maps/api/place/nearbysearch/json")
Call<List<ResultDO>> getPlaceDetailByLatLong(#Query("location") String type,#Query("radius") String radius,#Query("key")String key);
}
And in the main activity or fragment.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API service = retrofit.create(API.class);
service.getCityResults(types, input, location, radius, key).enqueue(new Callback<List<ResultDO>>() {
#Override
public void onResponse(Call<List<ResultDO>> call, Response<List<ResultDO>> response) {
tvCity.setText(response.body().get(0).getVicinity());// first object gives me the city name
}
#Override
public void onFailure(Call<List<ResultDO>> call, Throwable t) {
}
});
You can get address (street name, city, country, etc) by converting Geographic Location (e.g Latitude, longitude) to address. This process called Reverse Geocoding this doc.
You can use FusedLocationProviderApi(), but it has been deprecated (here). The alternative, You can use FusedLocationProviderClient() to get LastKnownLocation, from LastKnownLocation object (contain latitude and longitude), so we can use to get address like street name, city, country, etc using Geocoder. The sample doc do synchronously. But here i am doing Asynchronously using AsyncTask. Hope this Help.
To get Current Location:
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
public class MainActivity extends AppCompatActivity{
//before public class MainActivity extends AppCompatActivity implements LocationListener,...,...
private static final String TAG = "MainActivity";
public static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
private FusedLocationProviderClient mFusedLocationClient;
private Location mGetedLocation;
private double currentLat, currentLng;
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
return;
}
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mGetedLocation = task.getResult();
//currentLat = mGetedLocation.getLatitude();
//currentLng = mGetedLocation.getLongitude();
//start reverse geocoding
//little different with the doc
(new GetAddressTask(this)).execute(mGetedLocation);
}else{
Log.e(TAG, "no location detected");
Log.w(TAG, "getLastLocation:exception", task.getException());
}
}
});
}
To Get Address from LastKnownLocation
//sorry, I forgot where I got this asyncTask code. So I did not mention the source.
//If anyone feels that making this code please comment.
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
GetAddressTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
/*
address.getLocality(),
address.getCountryName());
*/
return address.getLocality();
} else {
return "No address found";
}
}
#Override
protected void onPostExecute(String address) {
if (address != null)
mtextView.setText(address);//=============================> GOT THIS
}
}
In the Activity Class makes a customized method :
private void getTheUserPermission() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationGetter locationGetter = new LocationGetter(FreshMenuSearchActivity.this, REQUEST_LOCATION, locationManager);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationGetter.OnGPS();
} else {
locationGetter.getLocation();
}
}
Make a UserDefined Class name LocationGetter:-
public class LocationGetter {
private int REQUEST_LOCATION;
private FreshMenuSearchActivity mContext;
private LocationManager locationManager;
private Geocoder geocoder;
public LocationGetter(FreshMenuSearchActivity mContext, int requestLocation, LocationManager locationManager) {
this.mContext = mContext;
this.locationManager = locationManager;
this.REQUEST_LOCATION = requestLocation;
}
public void getLocation() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mContext, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location LocationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps != null) {
double lat = LocationGps.getLatitude();
double longi = LocationGps.getLongitude();
getTheAddress(lat, longi);
} else if (LocationNetwork != null) {
double lat = LocationNetwork.getLatitude();
double longi = LocationNetwork.getLongitude();
getTheAddress(lat, longi);
} else if (LocationPassive != null) {
double lat = LocationPassive.getLatitude();
double longi = LocationPassive.getLongitude();
getTheAddress(lat, longi);
} else {
Toast.makeText(mContext, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
}
}
private void getTheAddress(double latitude, double longitude) {
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
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();
Log.d("neel", address);
} catch (IOException e) {
e.printStackTrace();
}
}
public void OnGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mContext.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}

Location manager in android get wrong results

I am writing android code to get current location and convert lat,long to address but I am getting wrong results,
the problem is here:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
Log.d("msgh","msgh");
} else {
System.out.println("location not available");
Log.d("msg","msg");
}
the code enters the else statement always
Try this one it works
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeoCoderHelper.class.getName());
private boolean running = false;
public interface CityListener {
public void cityNameListener(String s);
}
public void fetchCityName(final Context contex, final Location location,final CityListener listener)
{
if (running)
return;
new AsyncTask<Void, Void, String>()
{
protected void onPreExecute()
{
running = true;
};
#Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
Geocoder geocoder = new Geocoder(contex, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0)
{
cityName = addresses.get(0).getLocality();
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + location.getLatitude() + ","
+ location.getLongitude() + "&sensor=false&language=fr";
try
{
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String countyName = null ;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
return cityName;
}
}
}
}
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return null;
}
protected void onPostExecute(String cityName)
{
running = false;
if (cityName != null)
{
// Do something with cityName
Log.i("GeocoderHelper", cityName);
listener.cityNameListener(cityName);
}
};
}.execute();
}
and you can call like this
new GeoCoderHelper().fetchCityName(this,location,new GeoCoderHelper.CityListener() {
#Override
public void cityNameListener(String s) {
addressCityTextView.setText(s);
}
});

How to get complete address from latitude and longitude?

I want to get following values from Latitude and Longitude in android
Street Address
City / State
Zip
Complete Address
How to achieve this?
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, 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(); // Only if available else return NULL
For more info of available details, Look at Android-Location-Address
Try this My friend
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;
}
City & Country are not Always getting in address Line 1 & Line 2...
Example is here
So,
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String zip = addresses.get(0).getPostalCode();
String country = addresses.get(0).getCountryName();
There is a last trick to get Address from Lat-Long (Geo-coordinates). You can simply hit google-maps web service passing the Latitude and longitude. It is simply a GET-Method web-service.
It will return the JSON Response that can be parsed easily to get address. The URL for this is:
http://maps.googleapis.com/maps/api/geocode/json?latlng=32,75&sensor=true
You can replace 32,75 with lat,long.
If you use Kotlin language, I create this method to get the address location directly
private fun getAddress(latLng: LatLng): String {
val geocoder = Geocoder(this, Locale.getDefault())
val addresses: List<Address>?
val address: Address?
var addressText = ""
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
if (addresses.isNotEmpty()) {
address = addresses[0]
addressText = address.getAddressLine(0)
} else{
addressText = "its not appear"
}
return addressText
}
But this method just return the String value when you call this method
If you want to get all address you just use this method/function
fun getAddress(latLng: LatLng){
val geocoder = Geocoder(this, Locale.getDefault())
val addresses: List<Address>?
val address: Address?
var fulladdress = ""
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
if (addresses.isNotEmpty()) {
address = addresses[0]
fulladdress = address.getAddressLine(0) // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex
var city = address.getLocality();
var state = address.getAdminArea();
var country = address.getCountryName();
var postalCode = address.getPostalCode();
var knownName = address.getFeatureName(); // Only if available else return NULL
} else{
fulladdress = "Location not found"
}
}
In onCreate()..
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS signal not found",
3000).show();
}
if (location != null) {
Log.e("location", "location--" + location);
Log.e("latitude at beginning",
"###############" + location.getLatitude());
onLocationChanged(location);
}
Write the code in onLocationChanged()
#Override
public void onLocationChanged(Location location) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("latitude", "latitude--" + latitude);
try {
Log.e("latitude", "inside latitude--" + latitude);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
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();
locationTxt.setText(address + " " + city + " " + country);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You are looking for the term Geocoding.
The short story is you need to do:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
To do more you should read up on the Geocoder here.
public static String getAddressFromLatLng(Context context, LatLng latLng) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
return addresses.get(0).getAddressLine(0);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
Just Use this method and pass your lat, long.
public static void getAddress(Context context, double LATITUDE, double LONGITUDE{
//Set Address
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;
}
Its very easy to get complete address from the Latitude and Longitude using Geocoder class. Following the code sample. Hope this helps!
if (l != null) {
val lat = l.latitude
val lon = l.longitude
val geocoder = Geocoder(this, Locale.getDefault())
val addresses: List<Address>
addresses = geocoder.getFromLocation(lat, lon, 1)
val address = addresses[0].getAddressLine(0)
val address2 = addresses[0].getAddressLine(1)
val city = addresses[0].locality
val state = addresses[0].adminArea
val country = addresses[0].countryName
val postalCode = addresses[0].postalCode
val knownName = addresses[0].featureName
val message =
"Emergency situation. Call for help. My location is: " + address + "." + "http://maps.google.com/maps?saddr=" + lat + "," + lon
}
You can use only the address value as it gives you all the complete address. If you want individual components, you can use others as well.
Use this it work for me :D
Retrieve json data of the latitude and longitude.
https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAr29XeWWAeWZcrOgjjfs3iSnqkWtAz4No&latlng=2.1812,102.4266&sensor=true
Change latitude , longitude with your own place.
https://maps.googleapis.com/maps/api/geocode/json?key=<\API_KEY_HERE>&latlng="latitude","longitude"&sensor=true
You can change the <\API_KEY_HERE> with your own key.
Need to enable api service in google console for new api key.
Hope it helps :D
Geocoder geocoder =new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 10);
} catch (IOException e1) {
Log.e("LocationSampleActivity","IO Exception in getFromLocation()");
e1.printStackTrace();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
}
Address address=null;
String zip=null;
String city=null;
String state=null;
StringBuffer st=new StringBuffer();
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
String add=addresses.get(0).getAddressLine(0)+","
+addresses.get(0).getSubAdminArea()+","
+addresses.get(0).getSubLocality();
city=addresses.get(0).getLocality();
state=addresses.get(0).getAdminArea();
// Get the first address
for(int i=0 ;i<addresses.size();i++){
address = addresses.get(i);
if(address.getPostalCode()!=null){
zip=address.getPostalCode();
break;
}
}
You can easily use the following code to get the address.
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSService extends Service implements LocationListener {
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
/**
* Returs the Location
*
* #return Location or null if no location is found
*/
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
/**
* Gives you complete address of the location
*
* #return complete address in String
*/
public String getLocationAddress() {
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
return ("IO Exception trying to get address:" + e1);
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
}
} else {
return "Location Not available";
}
}
/**
* get latitude
*
* #return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* get longitude
*
* #return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GPSService.this);
}
}
/**
* show settings to open GPS
*/
public void askUserToOpenGPS() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use use location services?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
/**
* Updating the location when location changes
*/
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
You can create class
public class GeoLocation {
private Context mContext;
private String mLatitude;
private String mLongtitude;
private String mStreet;
private String mHouseNumber;
private String mPostalCode;
private String mCity;
private Location mMarkerLocation;
public GeoLocation (Context context) {
mContext = context;
}
public String getStreet () {
return mStreet;
}
public String getHouseNumber () {
return mHouseNumber;
}
public String getPostalCode () {
return mPostalCode;
}
public String getCity () {
return mCity;
}
public String getLatitude () {
return mLatitude;
}
public String getLongtitude () {
return mLongtitude;
}
// Lookup address via reverse geolocation
// Call this one
public void lookUpAddress (Location markerLocation) {
mMarkerLocation = markerLocation;
if (Geocoder.isPresent()) {
(new GetAddressTask(mContext)).execute();
}
}
public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
public GetAddressTask (Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground (android.location.Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
android.location.Location location = params[0];
List<Address> addresses = null;
try {
if (mMarkerLocation != null) {
addresses = geocoder.getFromLocation(mMarkerLocation.getLatitude(),
mMarkerLocation.getLongitude(), 1);
}
} catch (IOException exception) {
Log.e("ComplaintLocation",
"IO Exception in getFromLocation()", exception);
return ("IO Exception trying to get address");
} catch (IllegalArgumentException exception) {
String errorString = "Illegal arguments " +
Double.toString(location.getLatitude()) + " , " +
Double.toString(location.getLongitude()) + " passed to address service";
Log.e("LocationSampleActivity", errorString, exception);
return errorString;
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getMaxAddressLineIndex() > 0) {
return String.format(
"%s/%s/%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getThoroughfare(), // 2
address.getSubThoroughfare(), //3
address.getPostalCode(), // 4
address.getLocality()); // 5
} else {
return String.format(
"%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getPostalCode(), // 2
address.getLocality()); // 3
}
} else return "No address found";
}
// Format address string after lookup
#Override
protected void onPostExecute (String address) {
String[] addressFields = TextUtils.split(address, "/");
Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
// Workaround: doInBackground can only return Strings instead of, for example, an
// Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
// on fields returned by this method, set each String that currently reads "null" to
// a null reference
for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
if (addressFields[fieldcnt].equals("null"))
addressFields[fieldcnt] = null;
}
switch (addressFields.length) {
case 4:
mStreet = null;
mHouseNumber = null;
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mPostalCode = addressFields[2];
mCity = addressFields[3];
break;
case 6:
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mStreet = addressFields[2];
mHouseNumber = addressFields[3];
mPostalCode = addressFields[4];
mCity = addressFields[5];
break;
default:
mLatitude = null;
mLongtitude = null;
mStreet = null;
mHouseNumber = null;
mPostalCode = null;
mCity = null;
break;
}
Log.d("GeoLocation Street", mStreet);
Log.d("GeoLocation No.", mHouseNumber);
Log.d("GeoLocation Postalcode", mPostalCode);
Log.d("GeoLocation Locality", mCity);
Log.d("GeoLocation Lat/Lng", "[" + mLatitude + ", " + mLongtitude +
"]");
}
}
}
You then instantiate it using
GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if
called from an activity and not from a fragment
mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
It seems that no-one has yet provided the solution suggested by Google Docs (https://developer.android.com/training/location/display-address#java). The correct solution should use an IntentService to make the network call for reverse geocoding.
An intent service is used rather than an AsyncTask as it is not tied to any specific activity. ie. it has its own lifecycle. The IntentService will stop itself when the Geocoding is finished.
public class GeocodingService extends IntentService {
public GeocodingService() {
super("GeocodingService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (intent == null) {
return;
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
BCCDatabase BCCDatabase = skicompanion.skicompanion.storage.BCCDatabase.getInstance(getApplicationContext());
// Get the location passed to this service through an extra.
Location location = intent.getParcelableExtra(
"location");
long trackID = intent.getLongExtra("trackID", -1);
List<Address> addresses = null;
String addressString = "";
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = "service not available";
Log.d(Constants.SkiCompanionDebug, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid lat long used";
Log.d(Constants.SkiCompanionDebug, 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 = "no address found";
Log.d(Constants.SkiCompanionDebug, errorMessage);
}
} else {
if(addresses.get(0).getLocality() != null){
addressString += addresses.get(0).getLocality() + ", ";
}
if(addresses.get(0).getAdminArea() != null){
addressString += addresses.get(0).getAdminArea() + ", ";
}
if(addresses.get(0).getCountryName() != null){
addressString += addresses.get(0).getCountryName();
}
//updating DB
BCCDatabase.setTrackLocation(trackID, addressString);
Log.d(Constants.SkiCompanionDebug, "address found: "+ addressString);
}
}
}
1 - You create variables for LocationManager and LocationListener in onCreate method.
2 - Check if there is a permission so execute the location updates and get lastKnownLocation from locationManager else you ask for permission
3 - Create onRequestPermissionResult in main class and check if there is a permission then execute the location updates
4 - Create separated method which includes Geocoder variable and create a list to put the coordinates from your location,
so to be safe you check if the List is exist and if each info we want in that list is exist, then you use (getThoroughfare ==> for Street Address), (getLocality ==> for City / State), (getPostalCode ==> for Zip), (getAdminArea ==> for Complete Address)
5 - Finally you call that method after checking the permission with (lastKnownLocation parameter ==> to show address when the App runs) and in onLocationChanged with (location parameter ==> to show address when location changes)
Code part:
LocationManager locationManager;
LocationListener locationListener;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateLocation(lastKnownLocation);
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
public void updateLocation ( Location location){
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
String address = "Could not find location :(";
if (listAddresses != null && listAddresses.size() > 0) {
if (listAddresses.get(0).getThoroughfare() != null) {
address = listAddresses.get(0).getThoroughfare() + " ";
}
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + " ";
}
if (listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + " ";
}
if (listAddresses.get(0).getAdminArea() != null) {
address += listAddresses.get(0).getAdminArea();
}
}
Log.i("Address",address);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using geocoder you can get something like this!
try {
Geocoder geo = new Geocoder(MapsActivity.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(origin.latitude, origin.longitude, 1);
address.setText("Loading...");
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getAddressLine(0);
String country = addresses.get(0).getCountryName();
String state = addresses.get(0).getAdminArea();
String sub_admin = addresses.get(0).getSubAdminArea();
String city = addresses.get(0).getFeatureName();
String pincode = addresses.get(0).getPostalCode();
String locality_city = addresses.get(0).getLocality();
String sub_localoty = addresses.get(0).getSubLocality();
if (locality != null && country != null) {
address.setText(locality + ", " + (sub_localoty != null ? sub_localoty + ", " : "") + (locality_city != null ? locality_city + ", " : "" ) + (city != null ? city + ", " : "") + (sub_admin != null ? sub_admin + ", " : "") + (state != null ? state + ", " : "") + country + ", " + (pincode != null ? pincode : ""));
} else {
address.setText("Location could not be fetched...");
}
}
} catch (Exception e) {
address.setText("Location could not be fetched...");
e.printStackTrace(); // getFromLocation() may sometimes fail
}
Try to use below code using geocoder:
Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> geoAddresses = geoAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (geoAddresses.size() > 0) {
String mUserLocation = "";
for (int i = 0; i < 4; i++) { //Since it return only four value we declare this as static.
mUserLocation = mUserLocation + geoAddresses.get(0).getAddressLine(i).replace(",", "") + ", ";
}
}
public String getAddress(LatLng latLng) {
String cAddress = "";
if (latLng == null) {
errorMessage = "no_location_data_provided";
Log.wtf(TAG, errorMessage);
return "";
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
// Address found using the Geocoder.
List<Address> addresses = null;
try {
// Using getFromLocation() returns an array of Addresses for the area immediately
// surrounding the given latitude and longitude. The results are a best guess and are
// not guaranteed to be accurate.
addresses = geocoder.getFromLocation(
latLng.latitude,
latLng.longitude,
// In this sample, we get just a single address.
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = "service_not_available";
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + latLng.latitude +
", Longitude = " + latLng.longitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using {#code getAddressLine},
// join them, and send them to the thread. The {#link android.location.address}
// class provides other options for fetching address details that you may prefer
// to use. Here are some examples:
// getLocality() ("Mountain View", for example)
// getAdminArea() ("CA", for example)
// getPostalCode() ("94043", for example)
// getCountryCode() ("US", for example)
// getCountryName() ("United States", for example)
String allAddress = "";
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
allAddress += address.getAddressLine(i) + " ";
}
if (address.getAdminArea() != null) {
state = address.getAdminArea();
} else {
state = "";
}
if (address.getLocality() != null) {
city = address.getLocality();
} else {
city = "";
}
if (address.getPostalCode() != null) {
postalCode = address.getPostalCode();
} else {
postalCode = "";
}
Log.i(TAG, "address_found");
//driverAddress = TextUtils.join(System.getProperty("line.separator"), addressFragments);
cAddress = allAddress;
Log.e("result", cAddress.toString());
}
return cAddress;
}
You Can use this method for geocoding proper complete Address
Accepted answer in kotlin format
private fun getAddressInfo(latitude:Double, longitude:Double){
val geocoder = Geocoder(this, Locale.getDefault())
val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
val address: String = addresses[0].getAddressLine(0)
val city: String = addresses[0].locality
val state: String = addresses[0].adminArea
val country: String = addresses[0].countryName
val postalCode: String = addresses[0].postalCode
val knownName: String = addresses[0].featureName
}
You can do like this to get complete address from latitude and longitude :
public class MainActivity 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));
}
You need to pass the latitude and longitude value.
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getContext(), Locale.getDefault());
try {
addresses = geocoder. getFromLocation(latitude, 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(); // Only if available else return NULL
System.out.println(address+"-------------");
} catch (IOException e) {
e.printStackTrace();
}
Try this code (working)
public void GetLocation() throws IOException {
LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, 200);
return;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: " + location.getLongitude() + " , " + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d(TAG, "onStatusChanged: " + s);
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(context, "GPS signal not found",
Toast.LENGTH_LONG).show();
}
if (location != null) {
Log.e("location", "location--" + location);
Log.e("latitude at beginning",
"###############" + location.getLatitude());
// onLocationChanged(location);
}
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 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();
Log.d(TAG, "GetLocation: address " + address + " city " + city + " state " + state + " country " + country + " postalCode " + postalCode + " knownName " + knownName);
}
}

Categories

Resources