Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created February 8, 2012 08:26
Show Gist options
  • Save joshmcarthur/1766776 to your computer and use it in GitHub Desktop.
Save joshmcarthur/1766776 to your computer and use it in GitHub Desktop.
GET /geocode
app.get '/geocode', (req, resp) ->
# Set the content type of the response
resp.contentType("application/json")
# Assemble the base URL to Google's geocoding service
geocode_url = {
host: 'maps.googleapis.com',
port: 80,
path: '/maps/api/geocode/json?sensor=true'
}
# The remainder of the Google geocoding URL depends on whether a lat/lng or an address
# has been passed to the web service - basically, the URL is constructed to make sure
# that the geocoding results contain enough information to fill the gaps - i.e.
# an address to go with the lat/lng, or vice-versa
if (req.query['latlng'])
geocode_url.path += "&latlng=#{req.query['latlng']}"
else if (req.query['address'])
geocode_url.path += "&address=#{req.query['address']}"
# Try and retrieve the geocoding results. Once we reach the end of the response
# parse them into a JSON object, which we then use to assemble a 'location' object
# to send back to the frontend
try
http.get geocode_url, (res) ->
geocode_results = ""
res.on 'data', (chunk) ->
geocode_results += chunk
res.on 'end', ->
geocode_results = JSON.parse(geocode_results)
result = geocode_results.results[0]
if (result)
location = {
name: result.formatted_address,
latitude: result.geometry.location.lat,
longitude: result.geometry.location.lng
}
else
resp.send(error_json())
return false
resp.send(JSON.stringify(location))
catch error
resp.send(error_json(), 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment