@@ -316,30 +316,31 @@ std::string RecoverNearest(const std::string &short_code,
316
316
double resolution = pow_neg (
317
317
internal::kEncodingBase , 2.0 - (padding_length / 2.0 ));
318
318
// Distance from the center to an edge (in degrees).
319
- double area_to_edge = resolution / 2.0 ;
319
+ double half_res = resolution / 2.0 ;
320
320
// Use the reference location to pad the supplied short code and decode it.
321
321
LatLng latlng = {latitude, longitude};
322
322
std::string padding_code = Encode (latlng);
323
323
CodeArea code_rect =
324
324
Decode (std::string (padding_code.substr (0 , padding_length)) +
325
325
std::string (short_code));
326
326
// 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.
328
329
double center_lat = code_rect.GetCenter ().latitude ;
329
330
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 .
333
334
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 .
337
338
center_lat += resolution;
338
339
}
339
340
// 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 ) {
341
342
center_lng -= resolution;
342
- } else if (center_lng - longitude < -area_to_edge ) {
343
+ } else if (longitude - half_res > center_lng ) {
343
344
center_lng += resolution;
344
345
}
345
346
LatLng center_latlng = {center_lat, center_lng};
@@ -472,4 +473,4 @@ size_t CodeLength(const std::string &code) {
472
473
return clean_code.size ();
473
474
}
474
475
475
- } // namespace openlocationcode
476
+ } // namespace openlocationcode
0 commit comments