Java Reference
In-Depth Information
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</
formatted_address>
...
<geometry>
<location>
<lat>37.4217550</lat>
<lng>-122.0846330</lng>
</location>
...
</geometry>
</result>
</GeocodeResponse>
A lot of child elements have been omitted from this response in order to focus on what I ac-
tually want. The latitude and longitude values are buried deep inside the output. Of course,
digging to that point is easy enough for Groovy. Here's a script that creates the required
HTTP request, transmits it to Google, and extracts the response, all in less than a dozen
lines:
String street = '1600 Ampitheatre Parkway'
String city = 'Mountain View'; state = 'CA'
String base = 'http://maps.google.com/maps/api/geocode/xml?'
String url = base + [sensor:false,
address:[street, city, state].collect { v ->
URLEncoder.encode(v,'UTF-8')
}.join(',')].collect {k,v -> "$k=$v"}.join('&')
def response = new XmlSlurper().parse(url)
latitude = response.result[0].geometry.location.lat
longitude = response.result[0].geometry.location.lng
The code strongly resembles the version 2 client presented earlier, in that I have a base
URL for the service (note that it includes the response type, XML, as part of the URL) and
aparametersmapthatIconvertintoaquerystring.Transmittingtherequestandparsingthe
result is done in one line of code, because the XmlSlurper class has a parse method
that takes a URL. Then extracting the latitude and longitude is simply a matter of walking
the tree.
Search WWH ::




Custom Search