-
Notifications
You must be signed in to change notification settings - Fork 16
/
geo3x3.rb
70 lines (56 loc) · 1.14 KB
/
geo3x3.rb
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
62
63
64
65
66
67
68
69
70
module Geo3x3
module_function
def encode(lat, lng, level)
raise ArgumentError 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
result
end
def decode(code)
if code.is_a? Integer
code = code < 0 ? "W#{-code}" : "E#{code}"
elsif code.is_a? String
code = nil if code.length == 0
else
code = nil
end
raise ArgumentError unless code
c = code[0]
flg = true if c == "-" or c == "W"
code = code[1..-1] if flg or c == "+" or 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 * unit
level += 1
end
lat += unit / 2
lng += unit / 2
lat -= 90
lng -= 180.0 if flg
[lat, lng, level, unit]
end
end