-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathGeo3x3.cr
61 lines (50 loc) · 1.11 KB
/
Geo3x3.cr
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
class Geo3x3
def Geo3x3.encode(lat : Float64, lng : Float64, level : Int32) : String | Nil
if level > 1
lat = lat.to_f
lng = lng.to_f
if lng >= 0
result = "E"
else
result = "W"
lng += 180
end
lat += 90
unit = 180.0
(level - 1).times do
unit /= 3
x = (lng / unit).to_i
y = (lat / unit).to_i
result += "#{x + y * 3 + 1}"
lng -= x * unit
lat -= y * unit
end
end
result
end
def Geo3x3.decode(code : String) : Tuple(Float64, Float64, Int32, Float64) | Nil
if code.bytesize > 0
c = code[0]
flg = true if c == 'W'
code = code[1..-1] if flg || c == 'E'
unit = 180.0
lat = 0.0
lng = 0.0
level = 1
code.each_char do |c|
n = c.to_i
break if n == 0
unit = unit / 3
n -= 1
lng += n % 3 * unit
lat += (n / 3).to_i * unit
level += 1
end
lat += unit / 2
lng += unit / 2
lat -= 90
lng -= 180.0 if flg
{ lat, lng, level, unit }
end
end
end