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();
}
Related
I was wondering if there is a better way to code this piece of code:
private void getLatitudeAndLongitudeFromZipcode() {
String zipcode = mSharedPreferences.getString("Zipcode", "");
try {
List<Address> address = geocoder.getFromLocationName(zipcode, 1);
if ((address != null ? address.size() : 0) > 0) {
Address first = address.get(0);
mLatitude = first.getLatitude();
mLongitude = first.getLongitude();
mCurrentLocationName = getLocationAsName();
mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
.apply();
mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
.apply();
} else {
getOldZipcodeLocation();//duplicate method call
}
} catch (IOException e) {
getOldZipcodeLocation();//duplicate method call
e.printStackTrace();
}
}
Basic idea is that if they don't have internet and an exception is thrown, I want to get the old coordinates from storage. However, I also want to get the old coordinates if they are currently in a place that doesn't give them coordinates. For example, if the geocoder returns null. What bothers me is the duplicate method call in the else block and catch block. Any way to make this code cleaner? I'll take any other tips as well!
Yes you can , 1st get address through IOException separately , then use address in your if..else statement . that's it .
private void getLatitudeAndLongitudeFromZipcode() {
String zipcode = mSharedPreferences.getString("Zipcode", "");
List<Address> address = null;
try {
address = new Geocoder(this).getFromLocationName(zipcode, 1);
} catch (IOException e) {
e.printStackTrace();
}
if ((address != null ? address.size() : 0) > 0) {
Address first = address.get(0);
mLatitude = first.getLatitude();
mLongitude = first.getLongitude();
mCurrentLocationName = getLocationAsName();
mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
.apply();
mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
.apply();
} else {
getOldZipcodeLocation();
}
}
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();
}
Getting this error when trying to get location from latlong using Geocoder.
Error
Caused by java.io.IOException: grpc failed
at android.location.Geocoder.getFromLocation(Geocoder.java:136)
at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:676)
at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:81)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Code
punch_button?.setOnClickListener {
createLocationRequest()
}
protected fun createLocationRequest() {
mLocationRequest = LocationRequest()
mLocationRequest?.interval = 10
mLocationRequest?.fastestInterval = 50
mLocationRequest?.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest!!)
mLocationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
mCurrentLocation = p0?.lastLocation
}
}
val client = LocationServices.getSettingsClient(context)
val task = client.checkLocationSettings(builder.build())
task.addOnSuccessListener(OnSuccessListener<LocationSettingsResponse> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askForPermission();
}
}) }
private fun askForPermission() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
} else {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
}
} else {
sendLocationData()
}
}
#SuppressLint("MissingPermission")
fun sendLocationData() {
try{
Log.e("lat", mCurrentLocation?.latitude.toString())
//mCurrentLocation?.latitude !=null && mCurrentLocation?.latitude !=null
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null)
mFusedLocationClient.lastLocation.addOnSuccessListener({ location ->
if (location != null) {
val address: List<Address> = geocoder?.getFromLocation(location.latitude, location.longitude, 1)!!
}
})
}catch(e:Exception){
Log.e("tag","error")
}
}
This is a know bug reported to Google, but unfortunately not solved yet. This bug happens for real devices and emulators. You can see the thread about this issue here:
https://issuetracker.google.com/issues/64418751
https://issuetracker.google.com/issues/64247769
A workround to try solved this bug in your case is try to use Geocoding API web service:
https://github.com/googlemaps/google-maps-services-java
Or you can try just catch the except and handle the exception like this:
try{
geocoder = new Geocoder(this, Locale.getDefault())
// ... your code that throws the exception here
}catch(e: IOException){
Log.e("Error", "grpc failed: " + e.message, e)
// ... retry again your code that throws the exeception
}
I faced this issue while getting Addresses List using geocoder.getFromLocation() method, the problem is that getting addresses list from latitude,longitude takes time or on some slow devices it takes more time and, also sometimes it give me the java-io-ioexception-grpc-failed.
I fix this problem using Rx Java.
public class AsyncGeocoder {
private final Geocoder geocoder;
public AsyncGeocoder(Context context) {
geocoder = new Geocoder(context);
}
public Disposable reverseGeocode(double lat, double lng, Callback callback) {
return Observable.fromCallable(() -> {
try {
return geocoder.getFromLocation(lat, lng, 1);
} catch (Exception e) {
AppLogger.d("throwable,", new Gson().toJson(e));
e.printStackTrace();
}
return false;
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
//Use result for something
AppLogger.d("throwable,", new Gson().toJson(result));
callback.success((Address) ((ArrayList) result).get(0));
}, throwable -> AppLogger.d("throwable,", new Gson().toJson(throwable)));
}
public interface Callback {
void success(Address address);
void failure(Throwable e);
}
}
Calling Position
mViewModel.getLocation(asyncGeocoder, getLat(), getLng(), this);
ViewModel Method
public void getLocation(AsyncGeocoder geocoder, Double lat, Double lng, AsyncGeocoder.Callback callback) {
getCompositeDisposable().add(geocoder.reverseGeocode(lat, lng, callback));
}
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 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.