Hi all,
I have been working on a piece of code I’d like to share with you. Its not a question, the code really works!
Features:
-
Calculate distance between 2 points
-
Sort points (longitude, latitude) by your ‘GPS position’
I used two sources aswell, because I am not so good at math you know ;p
Have fun with it!
-- source print\_r function: https://gist.github.com/nrk/31175 -- source distance between 2 points: http://awesome.naquadah.org/wiki/Kooky\_geo function print\_r ( t ) local print\_r\_cache={} local function sub\_print\_r(t,indent) if (print\_r\_cache[tostring(t)]) then print(indent.."\*"..tostring(t)) else print\_r\_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then print(indent.."["..pos.."] =\> "..tostring(t).." {") sub\_print\_r(val,indent..string.rep(" ",string.len(pos)+8)) print(indent..string.rep(" ",string.len(pos)+6).."}") else print(indent.."["..pos.."] =\> "..tostring(val)) end end else print(indent..tostring(t)) end end end sub\_print\_r(t," ") end -- Locals local cos = math.cos local sin = math.sin local pi = math.pi local sqrt = math.sqrt local min = math.min local asin = math.asin local abs = math.abs -- Calculate distance function distance(from, to) local distance = 0 local radius = 6367000 local radian = pi / 180 local deltaLatitude = sin(radian \* (from.latitude - to.latitude) /2) local deltaLongitude = sin(radian \* (from.longitude - to.longitude) / 2) local circleDistance = 2 \* asin(min(1, sqrt(deltaLatitude \* deltaLatitude + cos(radian \* from.latitude) \* cos(radian \* to.latitude) \* deltaLongitude \* deltaLongitude))) distance = abs(radius \* circleDistance) return distance end -- Markers local markers = { { title='Nova Scotia', latitude = -62.937013, longitude = 45.367584}, -- will become position 3 { title='Brooklyn', latitude = -73.949204, longitude = 40.644178}, -- will become position 1 { title='South Philadelphia West', latitude = -75.181275, longitude = 39.918163} -- will become position 2 } -- Center; could be your current GPS location centerPoint = {latitude = -73.995895, longitude = 40.718119} -- new york -- Set distances in markers for i, Prop in ipairs(markers) do Prop['distance'] = distance(centerPoint, markers[i]) end -- Sort by distance function compare(a,b) return a['distance'] \< b['distance'] end table.sort(markers, compare) -- Print sorted markers print\_r(markers)
Output:
[1] =\> table: 002ABBC0 { [longitude] =\> 40.644178 [latitude] =\> -73.949204 [title] =\> Brooklyn [distance] =\> 5662.823745369 } [2] =\> table: 002ABBC0 { [longitude] =\> 39.918163 [latitude] =\> -75.181275 [title] =\> South Philadelphia West [distance] =\> 133824.02894993 } [3] =\> table: 002ABBC0 { [longitude] =\> 45.367584 [latitude] =\> -62.937013 [title] =\> Nova Scotia [distance] =\> 1242546.4018208 }