Skip to content

Instantly share code, notes, and snippets.

@rishav-rohit
Created September 30, 2014 16:08
Show Gist options
  • Save rishav-rohit/a7d1a8f2084707c63b2c to your computer and use it in GitHub Desktop.
Save rishav-rohit/a7d1a8f2084707c63b2c to your computer and use it in GitHub Desktop.
Helper class to get latitude and longitude for a location
package com.rishav.hadoop.hive.ql.udf.utils;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class GeoLatLng {
public static Float[] getLatLng(String location) {
// String geoPoints = null;
Float[] geoPoints = new Float[] {null, null};
// if input is null return null array
if (location == null ) return null;
String loc_uri = null;
try {
loc_uri = URIUtil.encodeQuery("http://maps.googleapis.com/maps/api/geocode/json?address=" + location);
} catch (URIException e) {
System.err.println("ERROR: URI encoding failed");
e.printStackTrace();
System.exit(1);
}
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(loc_uri);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
String responseStr = new String(responseBody);
JSONObject response = new JSONObject(responseStr);
JSONObject latlng = response.getJSONArray("results")
.getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location");
try {
geoPoints[0] = new Float(latlng.get("lat").toString());
geoPoints[1] = new Float(latlng.get("lng").toString());
} catch (Exception e) {
geoPoints[0] = null;
geoPoints[1] = null;
}
return geoPoints;
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} catch (JSONException e) {
return geoPoints;
} finally {
// Release the connection.
method.releaseConnection();
}
return geoPoints;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment