Skip to content

Instantly share code, notes, and snippets.

@greghelton
Last active December 20, 2019 19:58
Show Gist options
  • Save greghelton/c5337daff87034a5608e to your computer and use it in GitHub Desktop.
Save greghelton/c5337daff87034a5608e to your computer and use it in GitHub Desktop.
Signing the URL and parsing the JSON are the challenges to the programmer using google for the first time.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonGeoService {
JsonParser p = new JsonParser();
String results;
Double[] latLng = new Double[2];
String county;
private final static Logger LOGGER = LogManager.getLogger(JsonGeoService.class.getName());
static final String key = "get this from google";
static final String id = "get this from google";
URL getGeoDataURL(String address) throws Exception {
String apiUrl = "https://maps.googleapis.com/"
+ "maps/api/geocode/json"
+ "?address="
+ URLEncoder.encode(address, "UTF-8")
+ "&client=" + id;
UrlSigner signer = new UrlSigner(key);
URL url = new URL(apiUrl);
String request = signer.signRequest(url.getPath(),url.getQuery());
url = new URL(apiUrl + request);
return url;
}
public String connectWithURL(URL url) throws Exception {
int timeout = 0;
HttpURLConnection http = null;
http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-length", "0");
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setConnectTimeout(timeout);
http.setReadTimeout(timeout);
http.connect();
int status = http.getResponseCode();
LOGGER.debug("http response code = " + status);
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(
new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
return null;
}
void setCounty() throws Exception {
String countyKey = "administrative_area_level_2";
JsonElement x = p.parse(results);
JsonArray y = x.getAsJsonObject().get("results").getAsJsonArray();
JsonObject z = y.get(0).getAsJsonObject();
JsonArray alpha = z.get("address_components").getAsJsonArray();
for (final JsonElement comp : alpha) {
JsonObject compo = (JsonObject)comp;
JsonArray types = compo.get("types").getAsJsonArray();
for(final JsonElement type : types) {
if (type.getAsString().equals(countyKey)) {
this.county = compo.get("long_name").getAsString();
}
}
}
}
void setLatLng() {
JsonElement pResults = p.parse(results);
JsonArray resultsArray = pResults.getAsJsonObject()
.get("results")
.getAsJsonArray();
JsonObject location = resultsArray.get(0).getAsJsonObject()
.get("geometry").getAsJsonObject()
.get("location").getAsJsonObject();
latLng[0] = location.get("lat").getAsDouble();
latLng[1] = location.get("lng").getAsDouble();
}
public void setLatLngAndCountyForAddress(String address) throws Exception {
URL url = getGeoDataURL(address);
results = connectWithURL(url);
setCounty();
setLatLng();
}
public String toString() {
return "lat/lng=" + latLng[0] + "/" + latLng[1] + " and county=" + county;
}
public static void main(String[] args) throws Exception {
JsonGeoService geo = new JsonGeoService();
geo.setLatLngAndCountyForAddress("123 Main Street, Frisco, TX");
System.out.println(geo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment