Last active
August 29, 2015 14:02
-
-
Save petrbela/8282fc5188210a588b07 to your computer and use it in GitHub Desktop.
ApiTools SFPark geo distance middleware
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
return function(request, next_middleware) | |
local function geo_distance(lat1, lon1, lat2, lon2) | |
if lat1 == nil or lon1 == nil or lat2 == nil or lon2 == nil then | |
return nil | |
end | |
local dlat = math.rad(lat2-lat1) | |
local dlon = math.rad(lon2-lon1) | |
local sin_dlat = math.sin(dlat/2) | |
local sin_dlon = math.sin(dlon/2) | |
local a = sin_dlat * sin_dlat + math.cos(math.rad(lat1)) * math.cos(math.rad(lat2)) * sin_dlon * sin_dlon | |
local c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) | |
-- 6378 km is the earth's radius at the equator. | |
-- 6357 km would be the radius at the poles (earth isn't a perfect circle). | |
-- Thus, high latitude distances will be slightly overestimated | |
-- To get miles, use 3963 as the constant (equator again) | |
local d = 6378 * c | |
return d | |
end | |
local function split(str, sep) | |
local sep, fields = sep or ":", {} | |
local pattern = string.format("([^%s]+)", sep) | |
str:gsub(pattern, function(c) fields[#fields+1] = c end) | |
return fields | |
end | |
-- every middleware has to call next_middleware, | |
-- so others have chance to process the request/response | |
-- deal with request | |
local response = next_middleware() | |
send.notification({msg=response.status, level='info'}) | |
local body = json.decode(response.body) | |
-- if AVL is an object, wrap it in an array | |
if #body['AVL'] == 0 then | |
body['AVL'] = { body['AVL'] } | |
end | |
local current_place = { lat = tonumber(request.args.lat), lng = tonumber(request.args.long) } | |
console.log("Current Place lat: " .. current_place.lat .. ", lng: " .. current_place.lng) | |
for i = 1, #body['AVL'] do | |
local place = body['AVL'][i] | |
local location = split(place['LOC'], ',') | |
local latlng = { lat = tonumber(location[2]), lng = tonumber(location[1]) } | |
console.log("Place #" .. i .. " lat: " .. latlng.lat .. ", lng: " .. latlng.lng) | |
place['DISTANCE'] = geo_distance(current_place.lat, current_place.lng, latlng.lat, latlng.lng) | |
place['LAT'] = latlng.lat | |
place['LNG'] = latlng.lng | |
console.log("Distance: " .. place['DISTANCE']) | |
end | |
-- deal with response | |
response.body = json.encode(body) | |
return response | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment