Java Reference
In-Depth Information
Listing 3.6. A Groovy class for geocoding
class Geocoder {
def base = 'http://maps.google.com/maps/geo?'
void fillInLatLong(Location loc) {
def addressFields = loc.street ?
[loc.street,loc.city,loc.state] : [loc.city,loc.state]
def address = addressFields.collect {
URLEncoder.encode(it,'UTF-8')
}.join(',')
def params = [q:address,sensor:false,
output:'csv',key:'ABQIAAAAa...']
def url = base + params.collect { k,v -> "$k=$v" }.join('&')
def (code,level,lat,lng) = url.toURL().text.split(',')
loc.latitude = lat.toDouble()
loc.longitude = lng.toDouble()
}
}
The fillInLatLong method takes a Location as an argument. Strictly speaking, I
didn't have to declare a type for the parameter at all. I could have relied on duck typing
within the method and just been careful not to call it with anything other than an object
with street, city, and state properties. Still, I'm building the service with a Location in
mind, so it doesn't hurt to say so.
The addressFields variable uses the ternary operator to determine whether or not
a street has been supplied when returning the collection of address components. Note
that I'm appealing to the so-called “Groovy truth” here, in that I don't need to compare
loc.street to null or an empty string explicitly. Any non-blank value of the street
field as part of the loc argument will return true, so it will be added to the collection.
Therestoftheclass isthesame asthepreviousscript, thoughtomake theclass moreuseful
I went to the trouble of converting the string results to doubles before returning the loca-
tion.
One final issue is notable, and it highlights an important difference between a script and
a class. All of the variables, whether they are local variables or attributes, have to be de-
clared. There are no undefined variables, so there's also no binding to worry about any
more.
Search WWH ::




Custom Search