Skip to content

Instantly share code, notes, and snippets.

@fiddyschmitt
Created December 9, 2020 01:14
Show Gist options
  • Save fiddyschmitt/7dedf83c05b6b3df6ccf81a68e46734b to your computer and use it in GitHub Desktop.
Save fiddyschmitt/7dedf83c05b6b3df6ccf81a68e46734b to your computer and use it in GitHub Desktop.
I used (converted from Python):
public static (int X, int Y) Deg2Tile(double latDeg, double lonDeg, int zoom)
{
var latRad = (latDeg * Math.PI) / 180;
var n = Math.Pow(2.0, zoom);
var xtile = (int)((lonDeg + 180.0) / 360.0 * n);
var ytile = (int)((1.0 - Math.Log(Math.Tan(latRad) + (1 / Math.Cos(latRad))) / Math.PI) / 2.0 * n);
return (xtile, ytile);
}
From:
https://gis.stackexchange.com/questions/190966/export-arcgis-tiles-data-to-any-image-format
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
To convert between lat/long and tile number using C#:
int long2tilex(double lon, int z)
{
return (int)(Math.Floor((lon + 180.0) / 360.0 * (1 << z)));
}
int lat2tiley(double lat, int z)
{
return (int)Math.Floor((1 - Math.Log(Math.Tan(ToRadians(lat)) + 1 / Math.Cos(ToRadians(lat))) / Math.PI) / 2 * (1 << z));
}
double tilex2long(int x, int z)
{
return x / (double)(1 << z) * 360.0 - 180;
}
double tiley2lat(int y, int z)
{
double n = Math.PI - 2.0 * Math.PI * y / (double)(1 << z);
return 180.0 / Math.PI * Math.Atan(0.5 * (Math.Exp(n) - Math.Exp(-n)));
}
Alternatively:
public PointF WorldToTilePos(double lon, double lat, int zoom)
{
PointF p = new Point();
p.X = (float)((lon + 180.0) / 360.0 * (1 << zoom));
p.Y = (float)((1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) +
1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom));
return p;
}
public PointF TileToWorldPos(double tile_x, double tile_y, int zoom)
{
PointF p = new Point();
double n = Math.PI - ((2.0 * Math.PI * tile_y) / Math.Pow(2.0, zoom));
p.X = (float)((tile_x / Math.Pow(2.0, zoom) * 360.0) - 180.0);
p.Y = (float)(180.0 / Math.PI * Math.Atan(Math.Sinh(n)));
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment