Location manager in android get wrong results - android

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);
}
});

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

Geocoder returned address

I am using Geocoder class to get Latitude and Longitude to from my String address that user types to EditText.
And what is interesting it returns results for such query as "q", "qq", "n", "N". Is there any way to make it better?(validate or something, or use another service?)
if (!s.toString().isEmpty()) {
try {
List<Address> addresses = geocoder.getFromLocationName(s.toString(), 4);
if (addresses.size() > 0) {
Address userAddress = addresses.get(0);
double latitude = userAddress.getLatitude();
double longitude = userAddress.getLongitude();
mRestaurantLatLng = new LatLng(latitude, longitude);
if (userAddress != null) {
mPin.setVisibility(View.VISIBLE);
} else {
mPin.setVisibility(View.GONE);
mRestaurantLatLng = null;
}
} else {
mPin.setVisibility(View.GONE);
mRestaurantLatLng = null;
}
} catch (Exception e) {
e.printStackTrace();
}
You could always use another Service directly, or you could prune your results for the detail level you want.
So like:
List<Address> results = GeoCoder.getFromLocationName(query, 100);
filter(results);
if (results.size() > 0) {
// Do Stuff
}
....
void filter(List<Address> results) {
for (int i = 0; i < results.size(); i++) {
Address address = results.get(i);
if (!address.hasLatitude() || !address.hasLongitude()) {
results.remove(i);
}
// remove any that dont match your desired detail level
...
}

How to get address from latitude and longitude in 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);

How to get location from latitude and longitude in android

So I have a piece of code I got from the internet that lets me get the latitude and longitude from the current location. What I want now is to get the location of that place. And yes I did allot of research, and got this code from stack overflow from someone that had the same request as me(below). It probably worked for them, but it doesn't work with me. I used an example latitude and longitude because this code wasn't working. The problem is that the addresses is always null. What am I doing wrong? Why isn't geocoder.getFromLocation working? I tried logging addresses aswel, and I get [] as result.
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(51.977315, 5.921753, 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;
}
Create Location Utility Class
public class LocationUtility {
private String currentLatitude = "";
private String currentLongitude = "";
private LocationManager mLocationManager = null;
private final int TEN_SECOND = 0;
private final int TEN_METRES = 1;
private final int TWO_MINUTES = 1000 * 60 * 2; // Better Location
String provider;
public LocationUtility(Activity activity) {
mLocationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
getCurrentLocation();
}
private boolean isGpsOn;
private void getCurrentLocation() {
Location gpsLocation = null;
Location networkLocation = null;
mLocationManager.removeUpdates(listener);
/*
* Criteria criteria = new Criteria();
* criteria.setAccuracy(Criteria.ACCURACY_FINE);
* criteria.setCostAllowed(false);
*
* String bestProviderName = mLocationManager.getBestProvider(criteria,
* true);
*
* if(bestProviderName!=null) Logger.d("bestProvider",
* bestProviderName);
*/
gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER);
networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER);
isGpsOn = true;
if (gpsLocation != null && networkLocation != null) {
updateLocation(getBetterLocation(gpsLocation, networkLocation));
} else if (gpsLocation != null) {
updateLocation(gpsLocation);
} else if (networkLocation != null) {
updateLocation(networkLocation);
} else {
isGpsOn = false;
}
}
public String getCurrentLatitude() {
return currentLatitude;
}
public String getCurrentLongitude() {
return currentLongitude;
}
private final LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null)
updateLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
if (provider != null)
Logger.d(provider + " provider", "disabled");
}
#Override
public void onProviderEnabled(String provider) {
if (provider != null)
Logger.d(provider + " provider", "enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Logger.d("status", "" + status);
}
};
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
private Location getBetterLocation(Location newLocation,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return newLocation;
} else if (newLocation == null) {
// A new location is always better than no location
return currentBestLocation;
}
// Check whether the new location fix is newer or older
long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved.
if (isSignificantlyNewer) {
return newLocation;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return currentBestLocation;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(newLocation.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return newLocation;
} else if (isNewer && !isLessAccurate) {
return newLocation;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return newLocation;
}
return currentBestLocation;
}
private Location requestUpdatesFromProvider(String provider) {
Location location = null;
if (mLocationManager.isProviderEnabled(provider)) {
mLocationManager.requestLocationUpdates(provider, TEN_SECOND,TEN_METRES, listener);
location = mLocationManager.getLastKnownLocation(provider);
}
return location;
}
private void updateLocation(Location location) {
try {
Logger.d("new Location",location.getLatitude() + " " + location.getLongitude());
currentLatitude = String.valueOf(location.getLatitude());
currentLongitude = String.valueOf(location.getLongitude());
} catch (Exception e) {
// if (e != null)
// e.printStackTrace();
}
}
/**
*
* #return
*/
public boolean isGPSON() {
return isGpsOn;
}
public void removeUpdates() {
if (listener != null) {
try {
mLocationManager.removeUpdates(listener);
} catch (Exception e) {
// if (e != null)
// e.printStackTrace();
}
}
}
}
write this method to get current latitude and longitude
public static String[] getLatAndLong(Activity mContext) {
LocationUtility mLocation = new LocationUtility(mContext);
return new String[] { String.valueOf(mLocation.getCurrentLatitude()),String.valueOf(mLocation.getCurrentLongitude()),String.valueOf(mLocation.isGPSON()) };
}
write this into your main activity where you get location details
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, Long, 1);
//String address = addresses.get(0).getAddressLine(0);
//String city = addresses.get(0).getAddressLine(1);
//String newstring = city.replaceAll(",","");
//String country = addresses.get(1).getAddressLine(2);
try {
if (addresses != null && addresses.size() >= 0) {
strCity = addresses.get(0).getLocality();
strCounty = addresses.get(0).getCountryName();
strState = addresses.get(0).getAdminArea();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Categories

Resources