Skip to content

Instantly share code, notes, and snippets.

@federecio
Created November 7, 2011 16:30
Show Gist options
  • Select an option

  • Save federecio/1345445 to your computer and use it in GitHub Desktop.

Select an option

Save federecio/1345445 to your computer and use it in GitHub Desktop.
@Module(name="googlemaps", schemaVersion="1.0")
public class GoogleMapsModule
{
private static final String PROTOTYPE_URL =
"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=%s&destinations=%s&units=%s&sensor=false";
private static final String DISTANCE_XPATH = "//DistanceMatrixResponse/row/element/distance/text/text()";
@Configurable
@Optional
@Default("MI")
private DistanceUnit defaultDistanceUnit;
@Processor
public String getDistance(String origin, String destination, @Optional DistanceUnit distanceUnit) throws Exception {
String effectiveUrl;
if(distanceUnit != null) {
effectiveUrl = String.format(PROTOTYPE_URL, origin, destination, distanceUnit);
} else {
effectiveUrl = String.format(PROTOTYPE_URL, origin, destination, defaultDistanceUnit);
}
InputStream responseStream = new URL(effectiveUrl).openConnection().getInputStream();
try {
return getXPath(responseStream, DISTANCE_XPATH);
} finally {
IOUtils.closeQuietly(responseStream);
}
}
public void setDefaultDistanceUnit(DistanceUnit defaultDistanceUnit)
{
this.defaultDistanceUnit = defaultDistanceUnit;
}
private String getXPath(InputStream inputStream, String xpath) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(inputStream);
XPathFactory factory = XPathFactory.newInstance();
XPathExpression expr = factory.newXPath().compile(xpath);
return (String) expr.evaluate(doc, XPathConstants.STRING);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment