Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AsyncTask that gets Lat/Long using Geocoder first, otherwise makes HTTP call to Google Geocoding API to do the same (inspired by @kentarosu)
class AsyncGetLocationForStoreTask extends AsyncTask<String, Integer, Location> {
private ProgressDialog pDialog;
private String str;
public AsyncGetLocationForStoreTask(String s) {
str = s;
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Setting up geofence...");
if (!pDialog.isShowing()) {
pDialog.show();
}
}
@Override
protected Location doInBackground(String... strings) {
Location result = null;
if (Geocoder.isPresent()) {
Geocoder coder = new Geocoder(getContext());
List<Address> addresses;
try {
addresses = coder.getFromLocationName(str, 5);
if (addresses == null) {
Log.e("Geocoder.getFromLocationName", "null");
} else {
if (addresses.size() > 0) {
Address location = addresses.get(0);
Location latLng = new Location("JNJ");
latLng.setLongitude(location.getLongitude());
latLng.setLatitude(location.getLatitude());
result = latLng;
} else {
Log.e("Geocoder.getFromLocationName", "size < 0");
}
}
} catch (IOException e) {
Log.e("IOException", e.getLocalizedMessage());
}
}
if (result == null) {
// Geocoder didn't work. Let's try this:
String uri = "http://maps.google.com/maps/api/geocode/json?address=" + str + "&sensor=false";
Log.d("str", str);
HttpGet httpGet = new HttpGet(uri);
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) {
Log.e("ClientProtocolException", e.getLocalizedMessage());
} catch (IOException e) {
Log.e("IOException", e.getLocalizedMessage());
}
JSONObject jsonObject;
try {
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");
Location location = new Location("JNJ");
location.setLongitude(lng);
location.setLatitude(lat);
result = location;
} catch (JSONException e) {
Log.e("JSONException", e.getLocalizedMessage());
}
}
return result;
}
@Override
protected void onPostExecute(Location result) {
if (result != null) {
// success
}
pDialog.dismiss();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.