Skip to content

Commit

Permalink
Fix for geohash neighbors when geohash length is even.
Browse files Browse the repository at this point in the history
We don't have to set XLimit and YLimit depending on the level (even or odd), since semantics of x and y are already swapped on each level.
XLimit is always 7 and YLimit is always 3.

Close elastic#8526
  • Loading branch information
Clément Tourrière committed Nov 18, 2014
1 parent fd8a56d commit 6ed0c07
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java
Expand Up @@ -159,15 +159,13 @@ private final static String neighbor(String geohash, int level, int dx, int dy)
final int nx = ((level % 2) == 1) ? (x + dx) : (x + dy);
final int ny = ((level % 2) == 1) ? (y + dy) : (y + dx);

// define grid limits for current level
final int xLimit = ((level % 2) == 0) ? 7 : 3;
final int yLimit = ((level % 2) == 0) ? 3 : 7;

// if the defined neighbor has the same parent a the current cell
// encode the cell directly. Otherwise find the cell next to this
// cell recursively. Since encoding wraps around within a cell
// it can be encoded here.
if (nx >= 0 && nx <= xLimit && ny >= 0 && ny <= yLimit) {
// xLimit and YLimit must always be respectively 7 and 3
// since x and y semantics are swapping on each level.
if (nx >= 0 && nx <= 7 && ny >= 0 && ny <= 3) {
return geohash.substring(0, level - 1) + encode(nx, ny);
} else {
String neighbor = neighbor(geohash, level - 1, dx, dy);
Expand Down
Expand Up @@ -104,5 +104,35 @@ public void testNeighbours() {
Collection<? super String> neighbors = new ArrayList<>();
GeoHashUtils.addNeighbors(geohash, neighbors );
assertEquals(expectedNeighbors, neighbors);

// Border odd geohash
geohash = "u09x";
expectedNeighbors = new ArrayList<>();
expectedNeighbors.add("u0c2");
expectedNeighbors.add("u0c8");
expectedNeighbors.add("u0cb");
expectedNeighbors.add("u09r");
expectedNeighbors.add("u09z");
expectedNeighbors.add("u09q");
expectedNeighbors.add("u09w");
expectedNeighbors.add("u09y");
neighbors = new ArrayList<>();
GeoHashUtils.addNeighbors(geohash, neighbors );
assertEquals(expectedNeighbors, neighbors);

// Border even geohash
geohash = "u09tv";
expectedNeighbors = new ArrayList<>();
expectedNeighbors.add("u09wh");
expectedNeighbors.add("u09wj");
expectedNeighbors.add("u09wn");
expectedNeighbors.add("u09tu");
expectedNeighbors.add("u09ty");
expectedNeighbors.add("u09ts");
expectedNeighbors.add("u09tt");
expectedNeighbors.add("u09tw");
neighbors = new ArrayList<>();
GeoHashUtils.addNeighbors(geohash, neighbors );
assertEquals(expectedNeighbors, neighbors);
}
}

0 comments on commit 6ed0c07

Please sign in to comment.