Skip to content

Commit

Permalink
Added option to get children and parent tiles.
Browse files Browse the repository at this point in the history
  • Loading branch information
xivk committed Apr 15, 2022
1 parent 2f2f7ab commit 064fe2b
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/TilesMath/Tile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,52 @@ private Tile(int x, int y, byte zoom)
/// </summary>
public TileNeighbours Neighbours => new TileNeighbours(this);

/// <summary>
/// The parent tile, if any.
/// </summary>
public Tile? Parent
{
get
{
if (this.Zoom == 0) return null;

return Tile.Create(this.X / 2, this.Y / 2, this.Zoom - 1);
}
}

/// <summary>
/// The children.
/// </summary>
public TileChildren Children => new TileChildren(this);

public IEnumerable<Tile> 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;
}
}
}

/// <summary>
/// Creates a new tile from x-y coordinate and zoom level.
/// </summary>
Expand Down
31 changes: 31 additions & 0 deletions src/TilesMath/TileChildren.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Collections;

namespace TilesMath;

public struct TileChildren : IEnumerable<Tile>
{
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<Tile> 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();
}
}
2 changes: 1 addition & 1 deletion src/TilesMath/TilesMath.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PackageVersion>0.0.1</PackageVersion>
<PackageVersion>0.0.2</PackageVersion>
<Title>TilesMath</Title>
<Authors>ANYWAYS BV</Authors>
<Description>A tiny library for tiles math.</Description>
Expand Down

0 comments on commit 064fe2b

Please sign in to comment.