Created
May 26, 2011 03:55
-
-
Save rahulsom/992515 to your computer and use it in GitHub Desktop.
Demo to use Groovy, Grape, and Google Maps API to go from coast to coast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@groovy.lang.Grapes([ | |
@groovy.lang.Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.5.0-RC2') | |
]) | |
import groovyx.net.http.* | |
def http = new HTTPBuilder('https://maps.googleapis.com/maps/api/directions/') | |
http.get(path: 'json', | |
query: [ | |
origin: '1600 Amphitheatre Parkway, Mountain View, CA 94043', | |
destination: '1600 Pennsylvania Ave NW, Washington D.C., DC 20500', | |
sensor: 'true' | |
]) { resp, json -> | |
assert resp.status == 200 | |
json.routes[0].legs.each { leg -> | |
leg.steps.each { step -> | |
println "\n" + step.html_instructions | |
println "\tfrom: " + step.start_location + " to: " + step.end_location + " (" + step.distance + ") " | |
println "\t" + decodePoly(step.polyline.points).join(" --> ") | |
} | |
} | |
} | |
class GeoPoint { | |
double lat; | |
double lng; | |
public String toString() { | |
return "(" + | |
"lat:" + lat + | |
", lng:" + lng + | |
')'; | |
} | |
} | |
def List<GeoPoint> decodePoly(String encoded) { | |
List<GeoPoint> poly = new ArrayList<GeoPoint>(); | |
int index = 0, len = encoded.length(); | |
int lat = 0, lng = 0; | |
while (index < len) { | |
int b, shift = 0, result = 0; | |
while (true) { | |
b = encoded.charAt(index++) - 63; | |
result |= (b & 0x1f) << shift; | |
shift += 5; | |
if (b < 0x20) { | |
break; | |
} | |
} | |
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); | |
lat += dlat; | |
shift = 0; | |
result = 0; | |
while (true) { | |
b = encoded.charAt(index++) - 63; | |
result |= (b & 0x1f) << shift; | |
shift += 5; | |
if (b < 0x20) { | |
break; | |
} | |
} | |
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); | |
lng += dlng; | |
GeoPoint p = new GeoPoint(lat: (double) lat / 1E5, lng: (double) lng / 1E5); | |
poly.add(p); | |
} | |
return poly; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment