I am trying to use Geocoder class in my App and found that Geocoder.getFromLocationName returns null if the address is intersection of two streets. Ex. "Quail Ave and Dunford Way, Sunnyvale, CA 94087" . However, the method works perfect for any other type address. During Debug session, I could see the address parameter passed and reflects correctly, but "geocodeMatches" returns size(0) zero. Appreciate any Help!!
public static List<Address> getGeoCode(@NonNull Context context, @NonNull String address){
try {
geocodeMatches = new Geocoder(context).getFromLocationName(address, 1);
if (!geocodeMatches.isEmpty())
{
return geocodeMatches;
}
} catch (IOException e) {
Log.e("ERROR", "Error to retrieve geocode" + e);
e.printStackTrace();
}
return geocodeMatches;
}
GeoCoder is working on NetworkLocationService. In some cases, NetworkLocationService is stopped working due to some reason. I don't know exact reason. But you can get address from google api in that case. Hope below code will help you!
public static String GetLocationAddressFromLatLong(Context context, double latitude, double longitude) {
String finalAddress = "";
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
finalAddress = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1);
} else {
//Get address from Google api
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
+ longitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject location = Results.getJSONObject(0);
finalAddress = location.getString("formatted_address");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return finalAddress;
}