Skip to content

Commit 91880c0

Browse files
authored
Update shorten.go
1 parent 933247f commit 91880c0

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

go/shorten.go

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ func RecoverNearest(code string, lat, lng float64) (string, error) {
114114
resolution := math.Pow(20, float64(2-(padLen/2)))
115115

116116
// Distance from the center to an edge (in degrees).
117-
areaToEdge := float64(resolution) / 2
117+
halfRes := float64(resolution) / 2
118118

119119
// Use the reference location to pad the supplied short code and decode it.
120120
area, err := Decode(Encode(lat, lng, 0)[:padLen] + code)
@@ -123,24 +123,23 @@ func RecoverNearest(code string, lat, lng float64) (string, error) {
123123
}
124124

125125
// 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.
127128
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.
132132
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.
136136
centerLat += resolution
137137
}
138138

139139
// How many degrees longitude is the code from the reference?
140-
degDiff = centerLng - lng
141-
if degDiff > areaToEdge {
140+
if lng + halfRes < centerLng {
142141
centerLng -= resolution
143-
} else if degDiff < -areaToEdge {
142+
} else if lng - halfRes > centerLng {
144143
centerLng += resolution
145144
}
146145

0 commit comments

Comments
 (0)