@@ -114,7 +114,7 @@ func RecoverNearest(code string, lat, lng float64) (string, error) {
114
114
resolution := math .Pow (20 , float64 (2 - (padLen / 2 )))
115
115
116
116
// Distance from the center to an edge (in degrees).
117
- areaToEdge := float64 (resolution ) / 2
117
+ halfRes := float64 (resolution ) / 2
118
118
119
119
// Use the reference location to pad the supplied short code and decode it.
120
120
area , err := Decode (Encode (lat , lng , 0 )[:padLen ] + code )
@@ -123,24 +123,23 @@ func RecoverNearest(code string, lat, lng float64) (string, error) {
123
123
}
124
124
125
125
// How many degrees latitude is the code from the reference? If it is more
126
- // than half the resolution, we need to move it east or west.
126
+ // than half the resolution, we need to move it south or north but keep it
127
+ // within -90 to 90 degrees.
127
128
centerLat , centerLng := area .Center ()
128
- degDiff := centerLat - lat
129
- if degDiff > areaToEdge {
130
- // If the center of the short code is more than half a cell east,
131
- // then the best match will be one position west.
129
+ if lat + halfRes < centerLat && centerLat - resolution >= - latMax {
130
+ // If the proposed code is more than half a cell north of the reference location,
131
+ // it's too far, and the best match will be one cell south.
132
132
centerLat -= resolution
133
- } else if degDiff < - areaToEdge {
134
- // If the center of the short code is more than half a cell west ,
135
- // then the best match will be one position east .
133
+ } else if lat - halfRes > centerLat && centerLat + resolution <= latMax {
134
+ // If the proposed code is more than half a cell south of the reference location ,
135
+ // it's too far, and the best match will be one cell north .
136
136
centerLat += resolution
137
137
}
138
138
139
139
// How many degrees longitude is the code from the reference?
140
- degDiff = centerLng - lng
141
- if degDiff > areaToEdge {
140
+ if lng + halfRes < centerLng {
142
141
centerLng -= resolution
143
- } else if degDiff < - areaToEdge {
142
+ } else if lng - halfRes > centerLng {
144
143
centerLng += resolution
145
144
}
146
145
0 commit comments