Skip to content

Instantly share code, notes, and snippets.

@randallwhitman
Last active December 17, 2015 17:19
Show Gist options
  • Save randallwhitman/5645461 to your computer and use it in GitHub Desktop.
Save randallwhitman/5645461 to your computer and use it in GitHub Desktop.
Trip Discovery - Grid Cell Containing Location
private int queryGrid(double longitude, double latitude) {
int cellIndex; // xIdx + xCount * yIdx
if (longitude >= lonMin && longitude <= lonMax &&
latitude >= latMin && latitude <= latMax) { // avoid outliers
int xIdx = (int)((longitude-lonMin)/arcLon);
if (xIdx >= 0 && xIdx < xCount) {
int yIdx = (int)(yCount*(latitude-latMin)/latExtent); // approximate, to refine
yIdx = yIdx < yCount ? yIdx : yCount - 1;
cellIndex = xIdx + xCount * yIdx;
// Expect either correct, or one of either too high or too low, not both
while (grid.get(cellIndex)[1] > latitude) { // bottom too high
yIdx--;
cellIndex -= xCount;
}
while (grid.get(cellIndex)[3] < latitude) { // top too low
yIdx++;
cellIndex += xCount;
}
if (yIdx < 0 || yIdx >= yCount) { // bug
cellIndex = -3;
}
} else { // bug
cellIndex = -2;
}
} else { // outlier
cellIndex = -1;
}
return cellIndex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment