android - Best way to get the Current Address - android

I am getting the Latitude and Longitude from the Location Manager.
After getting these points, I am trying to get the Address using Geocoder method with these geopoints but I got the IOException called service not available.
I was try to fix this issue but I am unable to do it. Then I was changed the Implementation, after few hours I found one solution but I don't Know Is this best way.
Please advice what's the best way to get the current address?
public class MainActivity extends Activity implements LocationListener {
// providers
public LocationManager locationManager;
String strNetworkProvider;
public TextView tvAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the Location Manager
String locati
locati getSystemService(location_context);
strNetworkProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(strNetworkProvider, 0, 0,
MainActivity.this);
tvAddress = (TextView) findViewById(R.id.address);
}
// Get the current Location
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locationManager.removeUpdates(MainActivity.this);
double latitude = location.getLatitude();
double l
Double[] geopoints = { latitude, longitude };
Log.i("Latitude and Logitude", latitude + ", " + longitude);
// async task for initial WS call
new getAddressFromGeopoints().execute(geopoints);
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
// Async task for getting the address
public class getAddressFromGeopoints extends
AsyncTask<Double, Void, List<Address>> {
#Override
protected List<Address> doInBackground(Double... geoPoints) {
List<Address> addresses;
addresses = getFromLocation(geoPoints[0], geoPoints[1], 1);
return addresses;
}
protected void onPostExecute(final List<Address> addresses) {
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
tvAddress.setText(address);
Log.i("Address", address);
}
}
}
// This method is responsible for get the address from the
// Geopoints(Latitude and Longitude)
public static List<Address> getFromLocation(double lat, double lng,
int maxResult) {
String address = String
.format(Locale.ENGLISH,
"http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language;="
+ Locale.getDefault().getCountry(), lat, lng);
HttpGet httpGet = new HttpGet(address);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
List<Address> retList = null;
try {
resp
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject js JSONObject();
js JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
retList.add(addr);
}
}
} catch (ClientProtocolException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
} catch (IOException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
} catch (JSONException e) {
Log.e(MainActivity.class.getName(),
"Error parsing Google geocode webservice response.", e);
}
return retList;
}
}

Sharing the code which I generally use
How to use the code :- first calculate the lat and lng and the call String address[] = getCountry();
address[0] // country
address[1] // postal code
address[2] // Locality
address[3] // AddressLine
Constants
private static final int COUNTRY = 0;
private static final int POSTALCODE = 1;
private static final int CITY = 2;
private static final int ADDRESS = 3;
Methods
public String[] getCountry() {
if (lat != 0.0 && lng != 0.0) {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
String[] country = new String[4];
try {
List<Address> addresses = geocoder.getFromLocation(lat,
lng, 1);
if (addresses.size() > 0) {
Address obj = addresses.get(0);
// String add = obj.getAddressLine(0);
country[0] = obj.getCountryName() == null ? "xx" : obj
.getCountryName();
country[1] = obj.getPostalCode() == null ? "xx" : obj
.getPostalCode();
country[2] = obj.getLocality() == null ? "xx" : obj
.getLocality();
country[3] = obj.getAddressLine(0) == null ? "xx" : obj
.getAddressLine(0);
} else {
country = getFromLocation();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// Toast.makeText(activity, e.getMessage(),
// Toast.LENGTH_SHORT).show();
return getFromLocation();
}
return country;
} else {
return new String[] { "xx", "xx", "xx", "xx" };
}
}
public String[] getFromLocation() {
String[] countries = new String[4];
String address = String
.format(Locale.ENGLISH,
"http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
+ Locale.getDefault().getCountry(), lat,
lng);
// Log.v("url", address);
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream stream = conn.getInputStream();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
// Log.v("json", stringBuilder.toString());
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
int count = 0;
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
countries[ADDRESS] = result
.getString("formatted_address");
JSONArray array = result
.getJSONArray("address_components");
for (int j = 0; j < array.length(); j++) {
JSONObject oo = array.getJSONObject(j);
JSONArray type = oo.getJSONArray("types");
for (int k = 0; k < type.length(); k++) {
String tt = type.getString(k);
if (tt.equals("country")) {
countries[COUNTRY] = oo
.getString("long_name");
count++;
}
if (tt.equals("postal_code")) {
countries[POSTALCODE] = oo
.getString("long_name");
count++;
}
if (tt.equals("locality")) {
countries[CITY] = oo.getString("long_name");
count++;
}
if (count == 3) {
return countries;
}
}
}
String indiStr = result.getString("address_components");
Address addr = new Address(Locale.getDefault());
addr.setAddressLine(0, indiStr);
}
}
} catch (ClientProtocolException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
return new String[] { "xx", "xx", "xx", "xx" };
} catch (IOException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
return new String[] { "xx", "xx", "xx", "xx" };
} catch (JSONException e) {
Log.e(MainActivity.class.getName(),
"Error parsing Google geocode webservice response.", e);
return new String[] { "xx", "xx", "xx", "xx" };
}
return countries;
}
}
If the code can not find the address it will return xx.

Related

How to use Async task for different values.I will explain my problem briefly in description

I am getting retrieved data from server using volley and display in the list view. So I will get client's address from server and I need to calculate the distance between current location of the person who is using the app to the address which I got from the server.I will get different clients address and i need to calculate all their distances and display seperately in listview along with clients name.So I am using the following code.I am getting the same distance for all the clients as show in the image.there are places,thane,delhi,kalyan.I need to calculate the distance from current location to those places.I dont understand what the problem is. code for calculating distance using AyncTask.this code is inside fragment.
public class getLocationFromNameAsync extends
AsyncTask<String ,String,Double> {
Context context;
onTaskCompleted completed;
public getLocationFromNameAsync(Context context) {
this.context = context;
this.completed = (onTaskCompleted) context;
}
#Override
protected Double doInBackground(String... strings) {
Geocoder coder = new Geocoder(getActivity());
List<Address> address1=null;
List<Address> addresses = null;
try {
address1 = coder.getFromLocationName(district, 5);
} catch (IOException e) {
e.printStackTrace();
}
if (address1 == null) {
Toast.makeText(getActivity(), "Fetching Location,Please wait", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
final Address location11 = address1.get(0);
location11.getLatitude();
location11.getLongitude();
if (checkPermission()) {
LocationManager locationManager=(LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (location != null) {
latti = location.getLatitude();
longi = location.getLongitude();
} else if (location1 != null) {
latti = location1.getLatitude();
longi = location1.getLongitude();
} else if (location2 != null) {
latti = location2.getLatitude();
longi = location2.getLongitude();
}
coder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = coder.getFromLocation(latti, longi, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
area = addresses.get(0).getLocality();
String city = addresses.get(0).getAdminArea();
String county = addresses.get(0).getCountryName();
String postal_code = addresses.get(0).getPostalCode();
fullAddress=address+","+area+","+city+","+county+","+postal_code;
}
} catch (IOException e) {
e.printStackTrace();
}
}
LatLng source = new LatLng(latti, longi);
LatLng destination = new LatLng(location11.getLatitude(), location11.getLongitude());
double dis= SphericalUtil.computeDistanceBetween(source,destination);
dis/=1000;
return dis;
}
#Override
protected void onPostExecute(Double aDouble) {
completed.onTaskComplete(aDouble);
}
}
my interface code.
public interface onTaskCompleted {
public void onTaskComplete(Double result);
}
navigationDrawerActivity code.In this activity,I am getting result.
public class navigationDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,onTaskCompleted{
static double distance;
#Override
public void onTaskComplete(Double result) {
distance=result;
Toast.makeText(getApplicationContext(),"result is "+result,Toast.LENGTH_SHORT).show();
}
}
Getting data from API and setting data in listView
StringRequest stringRequest = new StringRequest(Request.Method.POST, getTaskUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
arrayList.clear();
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("dataObj");
int length=ja.length();
for(int i=0; i<length; i++){
JSONObject temp = ja.getJSONObject(i);
nameC= temp.getString("name");
checkId=temp.getString("clientEid");
clientName=temp.getString("client");
candidateFatherName=temp.getString("fatherName");
clientProcess=temp.getString("otherId");
dueDate=temp.getString("deadline");
JSONArray jsaDate = temp.getJSONArray("updateDetails");
for(int k=0; k<jsaDate.length(); k++){
JSONObject jo1 = jsaDate.getJSONObject(k);
sentDate = jo1.getString("date");
}
JSONArray ja1 = temp.getJSONArray("address");
for(int j=0; j<ja1.length(); j++){
JSONObject jo1 = ja1.getJSONObject(j);
landmark=jo1.getString("landmark");
district= jo1.getString("district");
userAddrss=jo1.getString("full");
Geocoder coder = new Geocoder(getActivity());
new getLocationFromNameAsync(getContext()).execute(district);
arrayList.add(new DataModel(nameC,district,landmark,checkId,Math.floor((navigationDrawer.distance*100)/100),clientName,candidateFatherName,clientProcess,sentDate,dueDate));
}
}
#MarconVasconcelos is saying that you need to iterate all your list items, and for each of them apply the response received

My UI is blocked using AsyncTask with distancematrix and google Maps

I'm using google maps to show some markers. The markers are download from a database and, at the same time, I get the distancematrix from google api, between the current position of the user and the marker that I get from the database.
My problem is that I was doing this with .get, bloking my ui (I've read that .get blocked the ui:
dataFromAsyncTask = testAsyncTask.get();
Now, I'm trying to do the same without blocking the ui, but I'm not be able to get at the same time, or in a good way, the distance for this markers.
I appreciate some help, please.
This is my code with my old and wrong .get:
for (City city : listCity.getData()) {
geoPoint = city.getLocation();
nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
startRetrievenDistanceAndDuration();
try {
dataFromAsyncTask = testAsyncTask.get();
} catch (InterruptedException i) {
} catch (ExecutionException e) {
}
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameCity)
.snippet(dataFromAsyncTask)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
startRetrievenDistanceAndDuration method:
private void startRetrievenDistanceAndDuration() {
final String url;
testAsyncTask = new DistanceBetweenLocations(new FragmentCallback() {
#Override
public void onTaskDone(String result) {
}
});
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";
testAsyncTask.execute(new String[]{url});
}
public interface FragmentCallback {
public void onTaskDone(String result);
AsyncTask class:
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url=new URL(params[0]);
}catch (MalformedURLException m){
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
}catch (IOException e){}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
}catch (IOException e){
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return distance + ", " + duration;
}
#Override
protected void onPostExecute(String result) {
mFragmentCallback.onTaskDone(result);
}
}
I'm trying to do this, but I only show the last marker of my list:
Call in the loop the method:
startRetrievenDistanceAndDuration();
And in onTaskDone try to put the marker, but only get the last marker of my list
#Override
public void onTaskDone(String result) {
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(result)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
UPDATED AFTER CHANGES: (still don't work)
I can parse the data in Asynctask and send it in onPostExecute, but I only get one value, and not the 9 values that I have....
MAIN ACTIVITY:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(HashMap<String, String> result) {
super.onPostExecute(result);
String name = result.get("beachName");
String distance = result.get("distance");
String duration = result.get("duration");
String latitue = result.get("latitude");
String longitude = result.get("longitude");
Double mlatituDouble = Double.parseDouble(latitue);
Double mlongitudeDouble = Double.parseDouble(longitude);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
Toast.makeText(getActivity(), "mMap NO null", Toast.LENGTH_SHORT).show();
mMap.addMarker(new MarkerOptions().position(new LatLng(mlatituDouble, mlongitudeDouble))
.title(name)
.snippet(distance + " " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
ASYNCTASK CLASS:.
public class DistanceBetweenLocations extends AsyncTask<String, String, HashMap<String, String>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
HashMap<String, String> map;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected HashMap<String, String> doInBackground(String... params) {
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
map = new HashMap<String, String>();
map.put("beachName", nameBeach);
map.put("distance", distance);
map.put("duration", duration);
map.put("latitude", latitude);
map.put("longitude", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return map;
}
}
I'll use your last code (the "UPDATED AFTER CHANGES"), ok?
If I get it right, your DistanceBetweenLocations result will be a list of beaches geolocation data. So, on every iteration of the for loop in doInBackground, you are replacing the value of "map" variable, this is your problem.
To solve your problem, you can have a List of HashMap or a List of a Pojo like this:
public class BeachPojo {
private String beachName;
private String distance;
private String duration;
private String latitude;
private String longitude;
public String getBeachName() {
return beachName;
}
public void setBeachName(String beachName) {
this.beachName = beachName;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
Using the Pojo, your AsyncTask will be like this:
public class DistanceBetweenLocations extends AsyncTask<String, String, List<BeachPojo>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected List<BeachPojo> doInBackground(String... params) {
List<BeachPojo> list = new ArrayList<BeachPojo>();
BeachPojo pojo;
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
pojo = new BeachPojo();
pojo.setBeachName(nameBeach);
pojo.setDistance(distance);
pojo.setDuration(duration);
pojo.setLatitude(latitude);
pojo.setLongitude(longitude);
list.add(pojo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return list;
}
}
Now you have a List to iterate. I have adjusted the code a little bit to this goal:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(List<BeachPojo> result) {
super.onPostExecute(result);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
}
Double beachLatitude;
Double beachLongitude;
for (BeachPojo pojo : result) {
beachLatitude = Double.parseDouble(pojo.getLatitude());
beachLongitude = Double.parseDouble(pojo.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(beachLatitude, beachLongitude))
.title(pojo.getBeachName())
.snippet(pojo.getDistance() + " " + pojo.getDuration())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
I hope you understand the idea of returning a List from your AsyncTask and loop throught the result on onPostExecute method.
Note: this is an implementation without knowing the real code, then you should adjust to your reality.
I'm not exactly sure what you're trying to do but I think you've made this more complicated then it has to be.
From what I understand you have a list of City objects and you use them to construct some URLs from which you retrieve a JSON object that is use to construct MarkerOptions objects.
You can do that using a AsyncTask like this:
public class Task extends AsyncTask<City, Void, Markers> {
String currentLatitude;
String currentlongitude;
public Task(String currentLatitude, String currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected String doInBackground(City... cities) {
final Markers mMap = ...;
for (City city : cities) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint != null) {
String latitude = String.valueOf(geoPoint.getLatitude());
String longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";);
urlConnection = (HttpURLConnection) url.openConnection();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString()).getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0);
String duration = jsonObject.getJSONObject("duration").getString("text");
String distance = jsonObject.getJSONObject("distance").getString("text");
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(distance + ", " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (urlConnection != null) {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return mMap;
}
}
And here is how you can use this task.
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Task task = new Task(currentLatitude, currentlongitude){
#Override
protected void onPostExecute(Markers markers) {
super.onPostExecute(markers);
//This runs on the UI thread and "markers" is the "mMap" object that was create on the background thread.
}
};
List<City> cities = ....
task.execute(cities.toArray(new City[cities.size()]));
}
}
The idea is that you need to execute all the long running operation in the AsyncTask's doInBackground(...) method. Also, you don't need to create other objects to deal with the AsyncTask response, you can override the task's onPostExecute(...) inside the class you've created the task in.

Android location listener does not work on some devices

I need to find user location in android. As I do not want to use GPS, I tried below code to find user location based on his/her Network, this works on some devices but not on all of them, what is the problem? is it becuase of Android version or something like hardware issues?
private double x, y;
private LocationManager lm;
lm = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, locationListenerNetwork);
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
x = location.getLatitude();
y = location.getLongitude();
lm.removeUpdates(this);
Geocoder gcd = new Geocoder(getActivity(), Locale.getDefault());
List<Address> addresses;
addresses = gcd.getFromLocation(x, y, 1);
city = addresses.get(0).getLocality();
}
Try this
give latitude and longitude in FetchLocationTask class
latitude = 27.003434;
longitude = 23.458569;
new FetchLocationTask(getActivity(), latitude, longitude).execute();
public class FetchLocationTask extends AsyncTask<Void, Void, Void> {
public Context context;
// private ProgressDialog mProgressDialog;
public String addressUrl;
public BufferedReader in;
public FetchLocationTask(Context context, double lat, double longi) {
this.context = context;
addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + longi + "&sensor=true";
}
#Override
protected void onPreExecute() {
}
/**
* Call the webservice and parse the data from the service in
* background.
*/
#Override
protected Void doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(addressUrl));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
if (jsonObject.has("results")) {
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
if (jsonObject.has("formatted_address")) {
address = (String) jsonObject.get("formatted_address");
}
}
return null;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* onPostExecute method after called webService and Set the data into
* adapter after background task is complete.
*/
#Override
protected void onPostExecute(Void result) {
if (address != null && address.length() > 0) {
Log.i("map", "My:::" + address);
etx_address.setText(address.toString());
}
}
}

Service not available while calling geoCoder.getFromLocation()

I know sometimes google back-end service might not be available.
Hence a solution might be to loop until i get the data.
private class getLocationDetails extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.d("looping", "" + count + "");
count++;
double lat = Double.parseDouble(params[0]);
double lng = Double.parseDouble(params[1]);
List<Address> addresses = null;
try {
Geocoder gCoder = new Geocoder(ImageAndLocationActivity.this,
Locale.getDefault());
addresses = gCoder.getFromLocation(lat, lng, 1);
Address addr = addresses.get(0);
user_country = addr.getCountryName();
user_city = addr.getLocality();
user_district = addr.getSubAdminArea();
if (user_city == null) {
user_city = user_district;
}
} catch (Exception e) {
Log.e("Exception in getLocationDetails - ", e.getMessage());
return null;
}
return "";
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Log.d("user_city = ", "" + user_city);
} else {
new getLocationDetails().execute(CurrentLat + "", CurrentLng
+ "");
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
But i am not able to get the location at all:
LogCat:
02-27 16:29:49.568: D/looping(10966): 110355
02-27 16:29:49.568: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110356
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110357
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
and ofcourse i have added all the needed permissions:
<uses-permission android:name="android.permission.INTERNET" />
I am trying this on Samsung Galaxy Note GT-N7000 (4.0.4 version)
Am i missing any settings? related to device or application ? Or this usually happens? If so any better solution to resolve this??
Thank You
The actual reason why Geocoder was not working is because the NetworkLocator was killed in action. Probably due to less memory or maybe you used the Task Manager to kill all services?
I'm not sure but this is a guess. I've seen this before. Last year I wrote a reconnect mechanism to load the NetworkLocator.apk and bind to the GeocoderService. I think this change has not merged into JellyBean so this problem persists.
It can be only solved by reboot. (The NetworkLocationService is loaded at boot)
Edit: You won't see this problem in JBP or KK, this service is moved into the playstore app .
Workaround using direct access to google maps:
public static LatLng getLocationFromString(String address)
throws JSONException {
HttpGet httpGet = new HttpGet(
"http://maps.google.com/maps/api/geocode/json?address="
+ URLEncoder.encode(address, "UTF-8") + "&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(stringBuilder.toString());
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
return new LatLng(lat, lng);
}
public static List<Address> getStringFromLocation(double lat, double lng)
throws ClientProtocolException, IOException, JSONException {
String address = String
.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
+ Locale.getDefault().getCountry(), lat, lng);
HttpGet httpGet = new HttpGet(address);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
List<Address> retList = null;
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.getDefault());
addr.setAddressLine(0, indiStr);
retList.add(addr);
}
}
return retList;
}
Restart the device and it will fix the issue.
API will throw a "Service not Available exception" if such service is unavailable on the device. Use method isPresent() to check for the existence of the service.
See also: http://developer.android.com/reference/android/location/Geocoder.html
The best fix for this problem is to use the same like Google Geocoder class if the original Geocoder fail
List<Address> addresses = null;
Geocoder geocoder = new Geocoder(this);
addresses = geocoder.getFromLocation(...);
if (addresses == null || addresses.isEmpty())
addresses = MyGeocoder.getFromLocation(...);
import android.location.Address;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MyGeocoder {
public static List<Address> getFromLocation(double lat, double lng, int maxResult) {
String address = String.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language=" + Locale.getDefault().getCountry(), lat, lng);
HttpGet httpGet = new HttpGet(address);
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(AllClientPNames.USER_AGENT, "Mozilla/5.0 (Java) Gecko/20081007 java-geocoder");
client.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 5 * 1000);
client.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 25 * 1000);
HttpResponse response;
List<Address> retList = null;
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = new JSONObject(json);
retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
if (results.length() > 0) {
for (int i = 0; i < results.length() && i < maxResult; i++) {
JSONObject result = results.getJSONObject(i);
//Log.e(MyGeocoder.class.getName(), result.toString());
Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, result.getString("formatted_address"));
JSONArray components = result.getJSONArray("address_components");
String streetNumber = "";
String route = "";
for (int a = 0; a < components.length(); a++) {
JSONObject component = components.getJSONObject(a);
JSONArray types = component.getJSONArray("types");
for (int j = 0; j < types.length(); j++) {
String type = types.getString(j);
if (type.equals("locality")) {
addr.setLocality(component.getString("long_name"));
} else if (type.equals("street_number")) {
streetNumber = component.getString("long_name");
} else if (type.equals("route")) {
route = component.getString("long_name");
}
}
}
addr.setAddressLine(0, route + " " + streetNumber);
addr.setLatitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
addr.setLongitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
retList.add(addr);
}
}
}
} catch (ClientProtocolException e) {
Log.e(MyGeocoder.class.getName(), "Error calling Google geocode webservice.", e);
} catch (IOException e) {
Log.e(MyGeocoder.class.getName(), "Error calling Google geocode webservice.", e);
} catch (JSONException e) {
Log.e(MyGeocoder.class.getName(), "Error parsing Google geocode webservice response.", e);
}
return retList;
}
}
use this trick.
simply edit the project.properties
# Project target
target=Google Inc.:Google APIs:16
The reason is that the Geocoder class is present in the core Android framework, but depends on code contributed by the Google APIs to function properly. Even if your AVD includes the Google APIs, your project still needs to be built against that specific build target.
Service not Available - Geocoder Android when i get this error in some cooked roms i wrote this library i hope could be useful. https://github.com/dnocode/gapis
I'm using the code that is up (direct access to Google Maps) "merged" with Geocoder code, as shown below (Pay special attention to "try catch"):
...
//address is String
if (address != null) {
new GeocoderTask().execute(address);
}
...
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
private LatLng latLng;
private MarkerOptions markerOptions;
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
try {
addresses = getLocationFromString(locationName[0]);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0) {
CameraUpdate center = CameraUpdateFactory.newLatLng(latLng);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(13);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
}
}
}
public static LatLng getLocationFromString(String address)
throws JSONException {
HttpGet httpGet = new HttpGet(
"http://maps.google.com/maps/api/geocode/json?address="
+ URLEncoder.encode(address, "UTF-8") + "&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(stringBuilder.toString());
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
return new LatLng(lat, lng);
}
public static List<Address> getStringFromLocation(double lat, double lng)
throws ClientProtocolException, IOException, JSONException {
String address = String
.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
+ Locale.getDefault().getCountry(), lat, lng);
HttpGet httpGet = new HttpGet(address);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
List<Address> retList = null;
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.getDefault());
addr.setAddressLine(0, indiStr);
retList.add(addr);
}
}
return retList;
}
This worked excellent for me because when Geocoder not work, i use direct access to Google Maps.
Cheers!
You can go to a map app in your phone and clear cached and will find the address work correctly.
I had the same geocoder error but non of the above applied. It would not run one of my Android devices. Then I remembered that I had accedently killed some running service.
The solution was to remove the battery for some seconds and re-install it.
And it worked without changing the code :))
Some devices do not have suport for Geocoder, so what you need to do is create your own geocoder.
Basicaly you need create a async task to request google for the address and treat the json response.
Using aquery, i do something like this:
public void asyncJson(String address){
address = address.replace(" ", "+");
String url = "http://maps.googleapis.com/maps/api/geocode/json?address="+ address +"&sensor=true";
aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if(json != null){
//here you work with the response json
JSONArray results = json.getJSONArray("results");
Toast.makeText(context, results.getJSONObject(1).getString("formatted_address"));
}else{
//ajax error, show error code
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
}
For the following line
Geocoder gCoder = new Geocoder(context, Locale.getDefault());
Use Context of your Activity and don't use getApplicationContext()
I have also had trouble with this error. It happened when I updated my device to Marshmallow recently.
If I reboot, it works once, but then will fail, and not work at all thereafter.
I created an AsyncTask like other people, that only returns the address from the first result of the json response.
To use the code below, call it constructed with your api key, and you use a Location object as input to execute the AsyncTask. You can import Location with the following. import android.location.Location; You will have to get the current Location with the LocationManager, by requesting an update to it.
new ReverseGeoCodeTask(GOOGLE_API_KEY).execute(location);
Make sure you replace the api key with your own, and also make sure you enable it in the google cloud console. That is where you manage all the google apis for your particular project.
Copy this class as an Inner Class in the Activity that you are needing the reverse geocoded address.
/**
* Reverse geocode request - takes a Location in as parameters,
* and does a network request in the background to get the first address in
* json response. The address is returned in the onPostExecute so you
* can update the UI with it
*/
private class ReverseGeoCodeTask extends AsyncTask<Location, Void, String>{
private final static String GEOCODE_API_ENDPOINT_BASE = "https://maps.googleapis.com/maps/api/geocode/json?latlng=";
private final static String JSON_PROPERTY_RESULTS = "results";
private final static String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address";
private final static String JSON_PROPERTY_REQUEST_STATUS = "status";
private final static String STATUS_OK = "OK";
private String apiKey;
public ReverseGeoCodeTask(final String apiKey){
this.apiKey = apiKey;
}
#Override
protected String doInBackground(Location... params) {
if(apiKey == null){
throw new IllegalStateException("Pass in a geocode api key in the ReverseGeoCoder constructor");
}
Location location = params[0];
String googleGeocodeEndpoint = GEOCODE_API_ENDPOINT_BASE + location.getLatitude() + "," + location.getLongitude() + "&key=" + apiKey;
Log.d(TAG, "Requesting gecoding endpoint : " + googleGeocodeEndpoint);
try {
URL url = new URL(googleGeocodeEndpoint);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject json = new JSONObject(result.toString());
String requestStatus = json.getString(JSON_PROPERTY_REQUEST_STATUS);
if(requestStatus.equals(STATUS_OK)){
JSONArray results = json.getJSONArray(JSON_PROPERTY_RESULTS);
if(results.length() > 0){
JSONObject result1 = results.getJSONObject(0);
String address = result1.getString(JSON_PROPERTY_FORMATTED_ADDRESS);
Log.d(TAG, "First result's address : " + address );
return address;
}
else{
Log.d(TAG, "There were no results.");
}
}
else{
Log.w(TAG, "Geocode request status not " + STATUS_OK + ", it was " + requestStatus );
Log.w(TAG, "Did you enable the geocode in the google cloud api console? Is it the right api key?");
}
}catch ( IOException | JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String address) {
super.onPostExecute(address);
if(address != null){
// update the UI here with the address, if its not null
originEditText.setText(address);
}
else{
Log.d(TAG, "Did not find an address, UI not being updated");
}
}
}
Had the same issue on Android 6.
The problem was in App permissions.
Even if the maps works properly you must allow the "Get position" permission in app permissions.
The best case is always to check this permission allowed
when you expect to get the place in result.
I use this method to get the full address from place:
public Address getFullAddress(Place place){
Address address;
Locale aLocale = new Locale.Builder().setLanguage("en").build();
Geocoder geocoder = new Geocoder(this, aLocale);
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
address = addresses.get(0);
return address;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I had the same error, add below permissions to resolve it.
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
new Volly_Services(map, "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + mBinding.loc.getText().toString().trim() + "&key=Ap", getActivity()).vollyPostService().continueWithTask(task - > {
mBinding.progressBaar.setVisibility(View.GONE);
if (task.getResult() != null) {
Log.e("<<<", "" + task.getResult());
JSONObject jsonObject = new JSONObject("" + task.getResult());
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
if (results.length() > 0) {
mBinding.loc.setVisibility(View.GONE);
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.getDefault());
addr.setAddressLine(0, indiStr);
addr.setLocality(result.getString("name"));
JSONObject geometry = result.getJSONObject("geometry").getJSONObject("location");
addr.setLatitude(geometry.getDouble("lat"));
addr.setLongitude(geometry.getDouble("lng"));
addresses.add(addr);
}
adapter = new SerchLocationAdapter(getActivity(), addresses);
mBinding.serchreg.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "No result found", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), "No result found", Toast.LENGTH_LONG).show();
}
} else {
Log.e("<<<<<<", "" + task.getError().getMessage());
Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
}
return null;
});
I use Volley and it work fine
private void callAppFromUrl(final String strAddress, final String app, final boolean isGeo) {
try {
Volley.newRequestQueue(this).add(new StringRequest(0, String.format("https://www.google.com/maps?q=%s", URLEncoder.encode(strAddress, "UTF-8")), new Response.Listener<String>() {
public void onResponse(String response) {
try {
try {
Matcher m = Pattern.compile("null,null,(\\d+.\\d+),(\\d+.\\d+)").matcher(response);
String strLatLong = "";
if (m.find()) {
strLatLong = m.group(0).replace("null,null,", "");
}
String[] latlong = strLatLong.split(",");
LatLng latLng = new LatLng(Double.parseDouble(latlong[0]), Double.parseDouble(latlong[1]));
Log.d("OsK",String.valueOf(latLng));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Không tìm thấy địa chỉ", Toast.LENGTH_LONG).show();
}
} catch (Exception e2) {
Toast.makeText(getApplicationContext(), "Không tìm thấy địa chỉ", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
/* class com.cantho.roadtech.MainActivity.AnonymousClass5 */
#Override // com.android.volley.Response.ErrorListener
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("User-Agent", "Mozilla");
params.put("Accept-Language", "en-US,en;q=0.8");
params.put("Referer", "google.com");
return params;
}
});
} catch (Exception ex) {
}
}

How can I get the nearest Place (Village Or Street name)

In my application, when the user insert data i want to capture the user's exact place. I've tried so many methods. But none of them shown the exact place. (I meant that they display the country and admin area details only. I used getLocality and getFeatureName. If no Locality or Featurename found at that latitude and longitude then it will return a null value). My code is
Geocoder coder=new Geocoder(MainActivity.mContext,Locale.getDefault());
try
{
List<Address> listaddress=coder.getFromLocation(lat, lon, 1);
Address obj=listaddress.get(0);
String add=obj.getAddressLine(0);
add = add+"\n"+obj.getLatitude();
add = add+","+obj.getLongitude();
add = add + "," + obj.getCountryName();
add = add + "," + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();//null
add = add + "," + obj.getSubAdminArea();
add = add +","+obj.getFeatureName();//null
add = add+ "," +obj.getPremises();//null
add = add + "\n" + obj.getLocality();//null
add = add + "," + obj.getSubThoroughfare();//null
add = add+ "," +obj.getSubLocality();//null
add = add+"\n"+obj.getThoroughfare();
Log.v("IGA", "Address" + add);
//Toast.makeText(this, "Address=>" + add,Toast.LENGTH_SHORT).show();
t.setText(" "+add);
}
So I don't know how to solve it. But I have an idea. I need to find the nearest place to my exact latitude and longitude value, so that i can use that place. But I don't know how to find the nearest place (Nearest place means Village or Street not any others).
Also, In Android phones one application "Places" is there. It shows the correct area about where exactly I'm. Is there any possibilities to use the application "Places" to find my exact or nearest area. (I need the closest village or street, not subAdminArea (state). If yes, please explain.
Can anyone help me please
Using google reverse geocoding api you could get your actual street address by giving latitude and lantitude values.
Get Lat & Lan through GPS Receiver in Android
Then call google reverse geocoding api top fecth the actual street address:
MapManager in = new MapManager(
"http://maps.google.com/maps/geo?output=xml&oe=utf-8&ll="
+ lattitude + "%2C"
+ lantitude + "&key=get-key-from-google-map-api");
content = in.URLRequest();
System.out.println("Addrss:"+in.parseMapData(content));
Class MapManager{
String url ="";
MapManager(String url){
this.url = url;
}
public String parseMapData(String data) {
String addr = "";
try {
InputStream in = new ByteArrayInputStream(data.getBytes());
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in, null);
NodeList address = doc.getElementsByTagName("address");
addr = address.item(0).getTextContent();
} catch (Throwable t) {
Log.v("Exception", "Exception: " + t.toString());
}
return addr;
}
public String URLRequest() {
httpclient = new DefaultHttpClient();
try {
httpget = new HttpGet(url);
httpresponse = httpclient.execute(httpget);
httpentity = httpresponse.getEntity();
response = EntityUtils.toString(httpentity);
response = response.trim();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IsServerConn = false;
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
IsServerConn = false;
}
return response;
}
}
private class MatchingNearByLocationTask extends
AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonStr = getLocationInfo(latitude, longitude).toString(); // put longitude and latitude value from which u want find nearer palce
if (jsonStr != null) {
Log.i("location--??", jsonStr);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
JSONObject responseJsonObject = jsonObj
.getJSONObject("response");
JSONArray venues = responseJsonObject
.getJSONArray(("venues"));
for (int index = 0; index < venues.length(); index++) {
locationObject = new NearByLocationObject();
String id = "", name = "", longitude = "", latitude = "";
JSONObject venuesJsonObj = venues.getJSONObject(index);
id = venuesJsonObj.getString("id");
name = venuesJsonObj.getString("name");
JSONObject latLngJsonObj = venuesJsonObj
.getJSONObject("location");
longitude = latLngJsonObj.getString("lng");
latitude = latLngJsonObj.getString("lat");
locationObject.setId(id);
locationObject.setNameOfLocation(name);
locationObject.setLocationOfLatitude(latitude);
locationObject.setLocationOfLongitude(longitude);
nearByLocationArrayList.add(locationObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
adapter = new NearByLocationArrayAdapter(getContext(),
R.layout.nearby_location_item, nearByLocationArrayList);
nearByLocationListView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
private JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet(
"https://api.foursquare.com/v2/venues/search?ll="
+ lat
+ ","
+ lng
+ "&radius=100&oauth_token=TNFKWLITLCJYWPSLAXQNHCSDPHZ4IS5PWVDD45OI224JGFFM&v=20140407&intent=checkin");
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();
}
return jsonObject;
}
public class NearByLocationObject {
String id = "", nameOfLocation, locationOfLatitude, LocationOfLongitude;
public NearByLocationObject() {
super();
// TODO Auto-generated constructor stub
}
public NearByLocationObject(String id, String nameOfLocation,
String locationOfLatitude, String locationOfLongitude) {
super();
this.id = id;
this.nameOfLocation = nameOfLocation;
this.locationOfLatitude = locationOfLatitude;
LocationOfLongitude = locationOfLongitude;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNameOfLocation() {
return nameOfLocation;
}
public void setNameOfLocation(String nameOfLocation) {
this.nameOfLocation = nameOfLocation;
}
public String getLocationOfLatitude() {
return locationOfLatitude;
}
public void setLocationOfLatitude(String locationOfLatitude) {
this.locationOfLatitude = locationOfLatitude;
}
public String getLocationOfLongitude() {
return LocationOfLongitude;
}
public void setLocationOfLongitude(String locationOfLongitude) {
LocationOfLongitude = locationOfLongitude;
}
}

Categories

Resources