Skip to content

Commit 9bf953a

Browse files
committed
Improve ChildrenInZoomRange implementation
1 parent cf84d0f commit 9bf953a

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

maptile/tile.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,11 @@ func (t Tile) Children() Tiles {
228228

229229
// ChildrenInZoomRange returns all the children tiles of tile from ranges [zoomStart, zoomEnd], both ends inclusive.
230230
func ChildrenInZoomRange(tile Tile, zoomStart, zoomEnd Zoom) Tiles {
231-
if zoomStart < tile.Z || zoomEnd < tile.Z {
232-
panic("tile.Z is greater than zoomStart or zoomEnd")
231+
if !(zoomStart <= zoomEnd) {
232+
panic("zoomStart must be <= zoomEnd")
233+
}
234+
if !(tile.Z <= zoomStart) {
235+
panic("tile.Z is must be <= zoomStart")
233236
}
234237

235238
zDeltaStart := zoomStart - tile.Z
@@ -238,11 +241,11 @@ func ChildrenInZoomRange(tile Tile, zoomStart, zoomEnd Zoom) Tiles {
238241
res := make([]Tile, 0)
239242

240243
for d := zDeltaStart; d <= zDeltaEnd; d++ {
241-
xTopLeft := tile.X << d
242-
yTopLeft := tile.Y << d
243-
dim := uint32(math.Pow(2, float64(d)))
244-
for x := xTopLeft; x < xTopLeft+dim; x++ {
245-
for y := yTopLeft; y < yTopLeft+dim; y++ {
244+
xStart := tile.X << d
245+
yStart := tile.Y << d
246+
dim := uint32(1 << d)
247+
for x := xStart; x < xStart+dim; x++ {
248+
for y := yStart; y < yStart+dim; y++ {
246249
res = append(res, New(x, y, tile.Z+d))
247250
}
248251
}

maptile/tile_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,24 @@ func TestChildrenTilesSubRange(t *testing.T) {
235235
}
236236
}
237237

238+
func TestChildrenTilesSubRangeInvalidParams_ZoomStart_Larger_Than_ZoomEnd(t *testing.T) {
239+
// No need to check whether `recover()` is nil. Just turn off the panic.
240+
defer func() { _ = recover() }()
241+
tile := New(0, 0, 0)
242+
ChildrenInZoomRange(tile, 10, 8)
243+
// Never reaches here if `ChildrenInZoomRange` panics.
244+
t.Errorf("did not panic")
245+
}
246+
247+
func TestChildrenTilesSubRangeInvalidParams_TileZ_Larger_Than_ZoomStart(t *testing.T) {
248+
// No need to check whether `recover()` is nil. Just turn off the panic.
249+
defer func() { _ = recover() }()
250+
tile := New(0, 0, 10)
251+
ChildrenInZoomRange(tile, 9, 12)
252+
// Never reaches here if `ChildrenInZoomRange` panics.
253+
t.Errorf("did not panic")
254+
}
255+
238256
func TestRange(t *testing.T) {
239257
tile := New(4, 4, 5)
240258
min, max := tile.Range(3)

0 commit comments

Comments
 (0)