Skip to content

Commit 07f7e69

Browse files
authored
Update openlocationcode.cc
1 parent 8ea2867 commit 07f7e69

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

cpp/openlocationcode.cc

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -316,30 +316,31 @@ std::string RecoverNearest(const std::string &short_code,
316316
double resolution = pow_neg(
317317
internal::kEncodingBase, 2.0 - (padding_length / 2.0));
318318
// Distance from the center to an edge (in degrees).
319-
double area_to_edge = resolution / 2.0;
319+
double half_res = resolution / 2.0;
320320
// Use the reference location to pad the supplied short code and decode it.
321321
LatLng latlng = {latitude, longitude};
322322
std::string padding_code = Encode(latlng);
323323
CodeArea code_rect =
324324
Decode(std::string(padding_code.substr(0, padding_length)) +
325325
std::string(short_code));
326326
// How many degrees latitude is the code from the reference? If it is more
327-
// than half the resolution, we need to move it east or west.
327+
// than half the resolution, we need to move it north or south but keep it
328+
// within -90 to 90 degrees.
328329
double center_lat = code_rect.GetCenter().latitude;
329330
double center_lng = code_rect.GetCenter().longitude;
330-
if (center_lat - latitude > area_to_edge) {
331-
// If the center of the short code is more than half a cell east,
332-
// then the best match will be one position west.
331+
if (latitude + half_res < center_lat && center_lat - resolution > internal::kLatitudeMaxDegrees) {
332+
// If the proposed code is more than half a cell north of the reference location,
333+
// it's too far, and the best match will be one cell south.
333334
center_lat -= resolution;
334-
} else if (center_lat - latitude < -area_to_edge) {
335-
// If the center of the short code is more than half a cell west,
336-
// then the best match will be one position east.
335+
} else if (latitude - half_res > center_lat && center_lat + resolution < internal::kLatitudeMaxDegrees) {
336+
// If the proposed code is more than half a cell south of the reference location,
337+
// it's too far, and the best match will be one cell north.
337338
center_lat += resolution;
338339
}
339340
// How many degrees longitude is the code from the reference?
340-
if (center_lng - longitude > area_to_edge) {
341+
if (longitude + half_res < center_lng) {
341342
center_lng -= resolution;
342-
} else if (center_lng - longitude < -area_to_edge) {
343+
} else if (longitude - half_res > center_lng) {
343344
center_lng += resolution;
344345
}
345346
LatLng center_latlng = {center_lat, center_lng};
@@ -472,4 +473,4 @@ size_t CodeLength(const std::string &code) {
472473
return clean_code.size();
473474
}
474475

475-
} // namespace openlocationcode
476+
} // namespace openlocationcode

0 commit comments

Comments
 (0)