Last active
December 18, 2015 08:29
-
-
Save mancdevcarl/5754340 to your computer and use it in GitHub Desktop.
Reverse GEO to get City(locality)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ReverseGeoAsync extends AsyncTask<String, String, String> { | |
public interface AsyncDone { | |
void networkRequestCompleted(String res); | |
} | |
private AsyncDone _listener; | |
public ReverseGeoAsync(AsyncDone listenerParam) { | |
_listener = listenerParam; | |
} | |
@Override | |
protected String doInBackground(String... uri) { | |
String resString = ""; | |
try { | |
HttpClient client = new DefaultHttpClient(); | |
HttpGet get = new HttpGet(uri[0]); | |
HttpResponse responseGet = client.execute(get); | |
HttpEntity resEntityGet = responseGet.getEntity(); | |
if (resEntityGet != null) { | |
try { | |
sourceString = new String( | |
EntityUtils.toString(resEntityGet)); | |
for (String line : sourceString.split("\n")) | |
Log.v("!", "LINE: " + line); | |
} catch (ParseException exc) { | |
exc.printStackTrace(); | |
} catch (IllegalStateException exc) { | |
exc.printStackTrace(); | |
} | |
} | |
} catch (Exception ex) { | |
} | |
return resString; | |
} | |
@Override | |
protected void onPostExecute(String result) { | |
super.onPostExecute(result); | |
if (_listener != null) { | |
String locality = ""; | |
try { | |
JSONObject jsonObj = new JSONObject(result); | |
JSONArray addressComp = jsonObj.getJSONArray("results") | |
.getJSONObject(0).getJSONArray("address_components"); | |
for (int x = 0; x < addressComp.length(); x++) { | |
JSONArray types = addressComp.getJSONObject(x) | |
.getJSONArray("types"); | |
if (types.getString(0).matches("locality")) { | |
locality = addressComp.getJSONObject(x).getString( | |
"long_name"); | |
} | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
_listener.networkRequestCompleted(locality); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Using the Async like this - | |
URI uri = null; | |
try { | |
uri = new URI( | |
"http://maps.googleapis.com/maps/api/geocode/json?latlng=53.438212,-2.208012&sensor=true");// | |
} catch (URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
String req = uri.toASCIIString(); | |
ReverseGeoAsync request = new ReverseGeoAsync(this); | |
request.execute(req); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment