获取指定子级的全部Cell
/**
* 获取指定级别的全部子cell
*
* @param root 当前cellId
* @param desLevel 目标level, > root.level()
*/
public List<S2CellId> children(S2CellId root, int desLevel) {
if (root.level() < desLevel) {
long interval = (root.childEnd().id() - root.childBegin().id()) / 4;
List<S2CellId> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
long id = root.childBegin().id() + interval * i;
S2CellId cellId = new S2CellId(id);
List<S2CellId> childrenCellId = children(cellId, desLevel);
list.addAll(childrenCellId);
}
return list;
} else if (root.level() == desLevel) {
return Collections.singletonList(root);
} else {
return Collections.emptyList();
}
}
获取指定子级的边界Cell
/**
* 获取指定子级的边界Cell(当前cell内部)
*
* @param s2CellId 当前cellId
* @param desLevel 目标cellId的level 需大于当前cellId
*/
public List<S2CellId> childrenCellId(S2CellId root, S2CellId s2CellId, int desLevel) throws IOException {
if (s2CellId.level() < desLevel - 1) {
long interval = (s2CellId.childEnd().id() - s2CellId.childBegin().id()) / 4;
List<S2CellId> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
long id = s2CellId.childBegin().id() + interval * i;
S2CellId cellId = new S2CellId(id);
S2CellId[] neighbors = new S2CellId[4];
cellId.getEdgeNeighbors(neighbors);
boolean edge = Arrays.stream(neighbors).anyMatch(neighbor -> !root.contains(neighbor));
if (edge) {
List<S2CellId> childrenCellId = childrenCellId(root, cellId, desLevel);
list.addAll(childrenCellId);
}
}
return list;
} else if (s2CellId.level() == desLevel - 1) {
long interval = (s2CellId.childEnd().id() - s2CellId.childBegin().id()) / 4;
List<S2CellId> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
long id = s2CellId.childBegin().id() + interval * i;
S2CellId cellId = new S2CellId(id);
S2CellId[] neighbors = new S2CellId[4];
cellId.getEdgeNeighbors(neighbors);
boolean edge = Arrays.stream(neighbors).anyMatch(neighbor -> !root.contains(neighbor));
if (edge) {
list.add(cellId);
}
}
return list;
}
return Collections.emptyList();
}