-
Notifications
You must be signed in to change notification settings - Fork 16
/
geo3x3.nelua
61 lines (58 loc) · 1.24 KB
/
geo3x3.nelua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
require 'math'
require 'string'
global function encode(lat: number, lng: number, level: number): string
if level < 1 then
return ""
end
local res = ""
if lng >= 0.0 then
res = "E"
else
res = "W"
lng = lng + 180.0
end
lat = lat + 90.0
local unit = 180.0
for i = 1, level - 1 do
unit = unit / 3
local x = math.floor(lng / unit)
local y = math.floor(lat / unit)
res = res .. string.format("%d", x + y * 3 + 1)
lng = lng - x * unit
lat = lat - y * unit
end
return res
end
global function decode(code: string): [4]number
local c = string.sub(code, 1, 1)
local begin = 0
local flg = false
if c == "-" or c == "W" then
flg = true
begin = 1
elseif c == "+" or c == "E" then
begin = 1
end
local unit = 180.0
local lat = 0.0
local lng = 0.0
local level = 1
for i = begin, string.len(code) - 1 do
local n = tonumber(string.sub(code, i + 1, i + 1))
if n == 0 then
break
end
unit = unit / 3
n = n - 1
lng = lng + math.floor(n % 3) * unit
lat = lat + math.floor(n / 3) * unit
level = level + 1
end
lat = lat + unit / 2
lng = lng + unit / 2
lat = lat - 90.0
if flg then
lng = lng - 180.0
end
return {lat, lng, level, unit}
end