@@ -48,23 +48,31 @@ def encode(latitude, longitude, code_length = PAIR_CODE_LENGTH)
48
48
end
49
49
50
50
code_length = MAX_CODE_LENGTH if code_length > MAX_CODE_LENGTH
51
- latitude = clip_latitude ( latitude )
52
- longitude = normalize_longitude ( longitude )
53
- latitude -= precision_by_length ( code_length ) if latitude == 90
54
-
55
- code = ''
56
51
57
52
# Compute the code.
58
53
# This approach converts each value to an integer after multiplying it by
59
54
# the final precision. This allows us to use only integer operations, so
60
55
# avoiding any accumulation of floating point representation errors.
61
- lat_val = 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
62
- lat_val += latitude * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
63
- lng_val = 180 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
64
- lng_val += longitude * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
65
- lat_val = lat_val . to_i
66
- lng_val = lng_val . to_i
56
+ lat_val = ( latitude * PAIR_CODE_PRECISION * LAT_GRID_PRECISION ) . round
57
+ lat_val += 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
58
+ if lat_val . negative?
59
+ lat_val = 0
60
+ elsif lat_val >= 2 * 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
61
+ lat_val = 2 * 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION - 1
62
+ end
63
+ lng_val = ( longitude * PAIR_CODE_PRECISION * LNG_GRID_PRECISION ) . round
64
+ lng_val += 180 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
65
+ if lng_val . negative?
66
+ # Ruby's % operator differs from other languages in that it returns
67
+ # the same sign as the divisor. This means we don't need to add the
68
+ # range to the result.
69
+ lng_val %= ( 360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION )
70
+ elsif lng_val >= 360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
71
+ lng_val %= ( 360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION )
72
+ end
67
73
74
+ # Initialise the code string.
75
+ code = ''
68
76
# Compute the grid part of the code if necessary.
69
77
if code_length > PAIR_CODE_LENGTH
70
78
( 0 ..MAX_CODE_LENGTH - PAIR_CODE_LENGTH - 1 ) . each do
0 commit comments