Java Reference
In-Depth Information
2
. Convert a map with the key's address and sensor into a query string.
3
. Transmit the resulting URL to the Google geocoder.
4
. Parse the results into the desired values.
The first step uses the
collect
method from Groovy, which takes a closure as an ar-
gument, applies the closure to each element of a collection, and returns a new collection
containing the results. I take the resulting collection and joined each of its elements into a
single string, using “,” as a separator:
String address = [street,city,state].collect {
URLEncoder.encode(it,'UTF-8')
}.join(',')
Undeclared variables
The street, city, and state are not declared in the script. This adds them to the binding, mak-
ing them available to the caller.
To build a query string I add all the required parameters to a map called
params
. I'm also
requesting comma-separated values for the output, which is not available in the version 3
geocoder:
def params = [q:address, sensor:false, output:'csv', key:'ABQIAAAAaUT...']
Thevalueof
sensor
shouldbe
true
ifthisrequestiscomingfromaGPS-enableddevice
and
false
otherwise. The
key
is determined at registration (version 3 doesn't require a
key). The
output
is here set to CSV, so that the result is a string of comma-separated
values composed of the response code (hopefully 200), the magnification level, and the lat-
itude and longitude.
To convert the map into a query string, the
collect
method is used again. On a map, if a
collect
is applied with a two-argument closure, the method automatically separates the
keys from the values. What I want here is to replace expressions like
key:value
with
strings like
key=value
. The complete URL is then found by concatenating the query
string to the base URL: