Skip to content

Commit

Permalink
webmercator_tile_info.py: added parent and ancestors
Browse files Browse the repository at this point in the history
  • Loading branch information
dsparber committed Oct 26, 2023
1 parent b28bc26 commit 05eb7a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tiles/tests/test_webmercator_tile_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,11 @@ def test_descendants(self) -> None:
set(root.descendants(max_zoom=1)), {root}.union(root.children)
)

def test_ancestors(self) -> None:
switzerland = WebmercatorTileInfo(zoom=6, x=33, y=22)
self.assertEqual(WebmercatorTileInfo(zoom=5, x=16, y=11), switzerland.parent)
ancestors = set(switzerland.ancestors())
self.assertEqual(len(ancestors), 7)

def test_path(self) -> None:
self.assertEqual(WebmercatorTileInfo(zoom=3, x=2, y=1).path, "3/2/1")
18 changes: 18 additions & 0 deletions tiles/webmercator_tile_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ def children(self) -> set[WebmercatorTileInfo]:
WebmercatorTileInfo(zoom=zoom, x=x0 + 1, y=y0 + 1),
}

@property
def parent(self) -> WebmercatorTileInfo:
return WebmercatorTileInfo(zoom=self.zoom - 1, x=self.x // 2, y=self.y // 2)

def descendants(self, max_zoom: int, min_zoom: int = 0) -> Iterable[TileInfo]:
if self.zoom > max_zoom:
return []
Expand All @@ -67,3 +71,17 @@ def descendants(self, max_zoom: int, min_zoom: int = 0) -> Iterable[TileInfo]:
for child in self.children:
for descendant in child.descendants(min_zoom=min_zoom, max_zoom=max_zoom):
yield descendant

def ancestors(self, min_zoom: int = 0, max_zoom: int = 30) -> Iterable[TileInfo]:
if self.zoom <= max_zoom:
yield self

if self.zoom > min_zoom:
yield self.parent
for ancestor in self.parent.ancestors(min_zoom, max_zoom):
yield ancestor

def overlapping(self, min_zoom: int = 0, max_zoom: int = 30) -> Iterable[TileInfo]:
return set(self.ancestors(min_zoom=min_zoom, max_zoom=max_zoom)).union(
self.descendants(min_zoom=min_zoom, max_zoom=max_zoom)
)

0 comments on commit 05eb7a5

Please sign in to comment.