Now I'm trying to get a location's country name but I cannot pass LatLng in getFromLocation().
How can I fix this?
public void checkCountry(LatLng location) {
Geocoder gcd = new Geocoder(this, Locale.getDefaut());
List<Address> addresses = gcd.getFromLocation(location.latitude, location.logtitude, 1); //error here
String country = addresses.get(0).getCountryName();
The error says
Unhandled Exception: java.IO.Exception
getFromLocation() cannot be applied to:
latitude double location.latitude
longtitude double location.longtitude
What am I wrong with this?
just handle the exception. either throw it or catch it.
public void checkCountry(LatLng location) {
Geocoder gcd = new Geocoder(this, Locale.getDefaut());
List<Address> addresses=new ArrayList<>();
try{
addresses= gcd.getFromLocation(location.latitude, location.longitude, 1); //error here
}catch (Exception e){
e.printStackTrace();
}
String country;
if(addresses!=null)if(addresses.size()!=0) country= addresses.get(0).getCountryName();
}
Related
I'm using android studio.
I'm trying to get location name from googlemaps when clicked.
I'm using geocoder.
Everytime i click somewhere on the map , marker goes there but i cant get the city name and i get a grpc failed error.
What should i do ?I tried this with api 23,24,25 none of them worked.
My onMapClick function :
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title("Konum"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Geocoder geocoder = new Geocoder(MapsActivity.this.getBaseContext(), Locale.getDefault());
try {
List<Address> city = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (city != null && city.size() > 0){
Log.i("Info",city.get(0).getLocality());
}
} catch (IOException e) {
e.printStackTrace();
}
}
W/System.err: java.io.IOException: grpc failed
W/System.err: at com.example.umut.googlemapstest.MapsActivity$override.onMapClick(MapsActivity.java:127)
Which shows
List<Address> city = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
This code
I have solution for exception "java.io.ioexception grpc failed":
try {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List addresses = geocoder.getFromLocation(latitude, longitude, 1);
List<Address> addresslist = addresses;
String address = addresslist.get(0).getAddressLine(0);
Log.d("add",address);
} catch (IOException e) {
e.printStackTrace();
}
In my Android app I have this code:
LatLng[] branches;
String[] branchesArray = HomeActivity.branches.toArray(new String[HomeActivity.branches.size()]);
for (int i = 0; i < HomeActivity.branches.size(); i++) {
branches[i] = getLocationFromAddress(branchesArray[i]);
}
getLocationFromAddress method:
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(this);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 1);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng((double) (location.getLatitude()), (double) (location.getLongitude()));
} catch (IOException e) {
Log.e("Error", e.getMessage());
}
return p1;
}
This code supposed to create an array of LatLng, extracted from an array of string addresses. The problem is that whenever I'm running this code, I get java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 in the log. It refers to line 137 as the problematic line, which is this line:
Address location = address.get(0);
How can I fix that?
The probleme is you are forgetting to initialize "branches" variable with the correct size that's why your are getting "size 0 index 0"
String[] branches = HomeActivity.branches.toArray(new String[HomeActivity.branches.size()]);
getLocationFromName documentation says:
returns a list of Address objects. Returns null or empty list if no
matches were found or there is no backend service available.
In your case it is returning an empty list, so you should add an additional check:
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(this);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 1);
if (address == null || address.isEmpty()) {
return null;
}
Address location = address.get(0);
p1 = new LatLng(location.getLatitude(), location.getLongitude());
} catch (IOException e) {
Log.e("Error", e.getMessage());
}
return p1;
}
I'm currently trying to implement JsonObjectRequest. I'm looking for a location and trying to get the place's information. However, there is a problem with jsObjRequest (of type JsonObjectRequest)--it throws a null pointer exception even though it's not null when I check on the watchlist. I'm confused as to why. Here's the code:
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final String API_KEY = "AIzaSyBlOhVQWuyQGwlAGZnDo81Aeg50UJbFrfw";
private static final String PLACES_SEARCH_URL =
"https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_TEXT_SEARCH_URL =
"https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL =
"https://maps.googleapis.com/maps/api/place/details/json?";
private double _latitude;
private double _longitude;
private double _radius;
/**
* Searching places
* #param latitude - latitude of place
* #params longitude - longitude of place
* #param radius - radius of searchable area
* //#param types - type of place to search
* #return list of places
* */
public PlacesList search(double latitude, double longitude, double radius/*, String types*/)
throws Exception {
String url = PLACES_SEARCH_URL + "key=" + API_KEY + "&location=" + latitude + "," + longitude + "&radius=" + radius;
System.out.println(url);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("SEARCH", "Part 1");
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
Log.d("SEARCH", "Part 2 - Exception called");
e.printStackTrace();
}
catch (Exception e)
{
System.out.println("Exception caught in JsonObjectRequest");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("SEARCH", "Part 3");
VolleyLog.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(jsObjRequest);
return new PlacesList();
}
It throws on the line that contains: ApplicationController.getInstance().addToRequestQueue(jsObjRequest);
The following block of code is where we catch the exception:
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Double lat = location.getLatitude();
Double lon = location.getLongitude();
PlacesList myPlaces = new PlacesList();
try {
myPlaces = finder.search(lat, lon, 10);
} catch (Exception e) {
System.out.println("Could not find place. Exception in search.");
}
if (myPlaces.getMostLikelyPlace() != null) {
if (myPlaces.getMostLikelyPlace().getId() != null) {
Log.d("PLACEID", myPlaces.getMostLikelyPlace().getId());
System.out.println(myPlaces.getMostLikelyPlace().getId());
}
}
}
The error that we catch looks like this:
I/System.out: https://maps.googleapis.com/maps/api/place/search/json?key=AIzaSyBlOhVQWuyQGwlAGZnDo81Aeg50UJbFrfw&location=43.816,-111.78199833333335&radius=10.0
I/System.out: Could not find place. Exception in search.
Here is what the documentation says about JsonObjectRequest: https://developer.android.com/training/volley/request.html#request-json
I feel like I'm following the instructions on the documentation exactly. Is there any reason as to why it's throwing on that line of code?
try this setup for volley..
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
maybe something went wrong with the volley setup for the project .. happens with me all the time..
I want to return a string array from Async class back to the activity that is calling this asynchronous class that is job is to do the reverse geocoding.
So, from my activity I call the constructor of the class like this:
Double[] lat_long = new Double[] { Double.parseDouble(map_lat), Double.parseDouble(map_long) };
ReverseGeocodingTask reverseGeocoding = new ReverseGeocodingTask(getActivity().getApplicationContext());
reverseGeocoding.execute(lat_long);
And this is the code of the class:
class ReverseGeocodingTask extends AsyncTask<Double, Void, List<String>> {
public static List<String> LIST = new ArrayList<String>();
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected List<String> doInBackground(Double... params) {
Geocoder gc= new Geocoder(mContext, Locale.getDefault());
List<Address> addrList = null;
double latitude = params[0].doubleValue();
double longitude = params[1].doubleValue();
Log.d("LATLONG", latitude + ":" + longitude);
try {
addrList = gc.getFromLocation(latitude, longitude, 1);
if (addrList.size() > 0) {
//format location info
Address address = addrList.get(0);
LIST.add(address.getLocality());
LIST.add(address.getSubAdminArea());
LIST.add(address.getCountryName());
Log.d("LIST", LIST.get(0));
}
else{
Log.d("addrList SIZE", "=0");
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return LIST;
}
#Override
protected void onPostExecute(List<String> result) {
if (result != null) {
Log.d("ON POST", result.get(0));
}
}
}
This is the logcat:
02-28 19:20:04.323 12275-14109/guide_me_for_all.guide_me_for_all D/LATLONG﹕ 34.681377999999995:33.039339
02-28 19:20:05.434 12275-14109/guide_me_for_all.guide_me_for_all D/addrList SIZE﹕ =0
I get correctly the latitude and longitude point as you can see from the Log.d(), BUT getFromLocation.size() is always 0.
This may be a problem with your GeoCoder service. If you're backend service for the device is not present or has other problems, you will get this response.
use isPresent to check if an implementation is present.
Also, see this post here:
Geocoder.getFromLocation throws IOException on Android emulator
And the docs mention that you need a backend service:
http://developer.android.com/reference/android/location/Geocoder.html
I am trying to get the zip code of the users current location.I have a teditText in MyActivity which should get populated based on the zip code I get from this activity.
public class LocationActivity extends MyActivity {
double LATITUDE;
double LONGITUDE;
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
{
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedZip = addresses.get(0);
StringBuilder currentZip = new StringBuilder("Address:\n");
for(int i=0; i<returnedZip.getMaxAddressLineIndex(); i++) {
strcurrentZip.append(returnedZip.getPostalCode());
}
m_zip.setText(strcurrentZip.toString());
}
else {
m_zip.setText("No zip returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
m_zip.setText("zip not found!");
}
}
}
I am not getting any response,the app logcat does not show any errors but the the editText field I want to populate remains blank.
Here ...
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//GeocodeResponse/result/address_component[type=\"postal_code\"]/long_name/text()";
InputSource inputSource = new InputSource("https://maps.googleapis.com/maps/api/geocode/xml?latlng="+VARIABLECONTAININGLATITUDE+","+VARIABLECONTAININGLONGITUDE+"&sensor=true");
String zipcode = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
where VARIABLECONTAININGLATITUDE and VARIABLECONTAININGLONGITUDE are latitudes and longitudes from GPS or whatever location provider you choose.
also you need permission internet in manifest and location permission in manifest
Please write below code for get zip code
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(currentlat, currentlng, 1);
Now the list of Address contains the closest known areas. The Address object has the getPostalCode() function. Grab the first object and find it's Postal code.