From 064fe2b9ed3633c4eecb19a63a0a88c6814969ad Mon Sep 17 00:00:00 2001 From: xivk Date: Fri, 15 Apr 2022 17:03:49 +0200 Subject: [PATCH] Added option to get children and parent tiles. --- src/TilesMath/Tile.cs | 46 ++++++++++++++++++++++++++++++++++ src/TilesMath/TileChildren.cs | 31 +++++++++++++++++++++++ src/TilesMath/TilesMath.csproj | 2 +- 3 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 src/TilesMath/TileChildren.cs diff --git a/src/TilesMath/Tile.cs b/src/TilesMath/Tile.cs index 031b133..330a762 100644 --- a/src/TilesMath/Tile.cs +++ b/src/TilesMath/Tile.cs @@ -54,6 +54,52 @@ private Tile(int x, int y, byte zoom) /// public TileNeighbours Neighbours => new TileNeighbours(this); + /// + /// The parent tile, if any. + /// + public Tile? Parent + { + get + { + if (this.Zoom == 0) return null; + + return Tile.Create(this.X / 2, this.Y / 2, this.Zoom - 1); + } + } + + /// + /// The children. + /// + public TileChildren Children => new TileChildren(this); + + public IEnumerable ChildrenAtZoom(int zoom) + { + if (zoom < this.Zoom) throw new Exception("Cannot calculate sub tiles for a smaller zoom level"); + + if (zoom == this.Zoom) + { + yield return this; + yield break; + } + + if (zoom - 1 == this.Zoom) + { + foreach (var child in this.Children) + { + yield return child; + } + yield break; + } + + foreach (var childOneLevelLess in this.ChildrenAtZoom(zoom - 1)) + { + foreach (var child in childOneLevelLess.Children) + { + yield return child; + } + } + } + /// /// Creates a new tile from x-y coordinate and zoom level. /// diff --git a/src/TilesMath/TileChildren.cs b/src/TilesMath/TileChildren.cs new file mode 100644 index 0000000..ceab69b --- /dev/null +++ b/src/TilesMath/TileChildren.cs @@ -0,0 +1,31 @@ +using System.Collections; + +namespace TilesMath; + +public struct TileChildren : IEnumerable +{ + private readonly int _x; + private readonly int _y; + private readonly int _z; + + internal TileChildren(Tile tile) + { + _x = tile.X * 2; + _y = tile.Y * 2; + _z = tile.Zoom + 1; + } + + + public IEnumerator GetEnumerator() + { + yield return Tile.Create(_x, _y, _z); + yield return Tile.Create(_x + 1, _y, _z); + yield return Tile.Create(_x + 1, _y + 1, _z); + yield return Tile.Create(_x, _y + 1, _z); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} \ No newline at end of file diff --git a/src/TilesMath/TilesMath.csproj b/src/TilesMath/TilesMath.csproj index deee167..089933c 100644 --- a/src/TilesMath/TilesMath.csproj +++ b/src/TilesMath/TilesMath.csproj @@ -4,7 +4,7 @@ net6.0 enable enable - 0.0.1 + 0.0.2 TilesMath ANYWAYS BV A tiny library for tiles math.