Code Snippet

using System;

namespace LatToYConverter

{

internal class Program

{

private static void Main(string[] args)

{

int y = LatitudeToYAtZoom(43.1, 19);

Console.WriteLine(YToLatitudeAtZoom(y, 19));

}

private const double earthRadius = 6378137; //The radius of the earth - should never change!

private const double earthCircum = earthRadius*2.0*Math.PI; //calulated circumference of the earth

private const double earthHalfCirc = earthCircum/2; //calulated half circumference of the earth

private const int pixelsPerTile = 256;

public static int LatitudeToYAtZoom(double lat, int zoom)

{

int y;

double arc = earthCircum/((1 << zoom)*pixelsPerTile);

double sinLat = Math.Sin(DegToRad(lat));

double metersY = earthRadius/2*Math.Log((1 + sinLat)/(1 - sinLat));

y = (int) Math.Round((earthHalfCirc - metersY)/arc);

return y;

}

public static double YToLatitudeAtZoom(int y, int zoom)

{

double arc = earthCircum/((1 << zoom)*pixelsPerTile);

double metersY = earthHalfCirc - (y*arc);

double a = Math.Exp(metersY*2/earthRadius);

double result = RadToDeg(Math.Asin((a - 1)/(a + 1)));

return result;

}

private static double DegToRad(double d)

{

return d*Math.PI/180.0;

}

public static double RadToDeg(double d)

{

return d/Math.PI*180.0;

}

}

}