Skip to content

Instantly share code, notes, and snippets.

@code-4-fun
Last active April 10, 2017 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-4-fun/63c18768785a85b89c6c8ff41b8f4b27 to your computer and use it in GitHub Desktop.
Save code-4-fun/63c18768785a85b89c6c8ff41b8f4b27 to your computer and use it in GitHub Desktop.
Sample Boilerplate Code to Parse GeoCode API Response and extract necessary parameter values.
/**
Dependencies Used:
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
</dependencies>
*/
public class GoogleGeoCodeExample {
private final static String REQ_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670," +
"151.1957&radius=500&types=food&name=cruise";
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(REQ_URL + "&key=" + args[0]);
HttpResponse response = httpClient.execute(request);
System.out.println("Response Status Code: " + response.getStatusLine().getStatusCode());
final String responseStr = EntityUtils.toString(response.getEntity());
System.out.println("Response Body: " + responseStr);
JSONObject responseJson = new JSONObject(responseStr);
if (responseJson.has("results")) {
JSONArray results = responseJson.getJSONArray("results");
JSONObject result = null;
for (int i = 0; i < results.length(); i++) {
result = results.getJSONObject(i);
System.out.println("Location-" + i + " : Geometry - " + result.query("/geometry/location"));
System.out.println("Location-" + i + " : Name - " + result.query("/name"));
System.out.println("Location-" + i + " : Rating - " + result.query("/rating"));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment