asaf
asaf

Reputation: 976

Get lat / lon of pixel with in tile in google maps in c#

How do i get the Lat / Lon of a pixel in a specific tile in google maps.

for example - i have zoom 5, x = 4, y = 5.

I want to get the Lat / Lon of each pixel in the 256 X 256 matrix of this tile

is there a a package or a formula to get it ?

Upvotes: 0

Views: 1091

Answers (1)

asaf
asaf

Reputation: 976

here is the answer in C#

the response was taken from https://help.openstreetmap.org/questions/747/given-a-latlon-how-do-i-find-the-precise-position-on-the-tile

    static void PixelXYToLatLongOSM(int pixelX, int pixelY, int zoomLevel, out float latitude, out float longitude)
    {
        int mapSize = (int)Math.Pow(2, zoomLevel) * 256;
        int tileX = (int)Math.Truncate((decimal)(pixelX / 256));
        int tileY = (int)Math.Truncate((decimal)pixelY / 256);

        float n = (float)Math.PI - ((2.0f * (float)Math.PI * (ClipByRange(pixelY, mapSize - 1) / 256)) / (float)Math.Pow(2.0, zoomLevel));

        longitude = ((ClipByRange(pixelX, mapSize - 1) / 256) / (float)Math.Pow(2.0, zoomLevel) * 360.0f) - 180.0f;
        latitude = (180.0f / (float)Math.PI * (float)Math.Atan(Math.Sinh(n)));
    }

    static float ClipByRange(float n, float range)
    {
        return n % range;
    }

    static float Clip(float n, float minValue, float maxValue)
    {
        return Math.Min(Math.Max(n, minValue), maxValue);
    }

    static void LatLongToPixelXYOSM(float latitude, float longitude, int zoomLevel, out int pixelX, out int pixelY)
    {
        float MinLatitude = -85.05112878f;
        float MaxLatitude = 85.05112878f;
        float MinLongitude = -180;
        float MaxLongitude = 180;
        float mapSize = (float)Math.Pow(2, zoomLevel) * 256;

        latitude = Clip(latitude, MinLatitude, MaxLatitude);
        longitude = Clip(longitude, MinLongitude, MaxLongitude);

        float X = (float)((longitude + 180.0f) / 360.0f * (float)(1 << zoomLevel));
        float Y = (float)((1.0 - Math.Log(Math.Tan(latitude * (Math.PI / 180.0)) + 1.0 / Math.Cos(latitude * (Math.PI / 180.0))) / Math.PI) / 2.0 * (1 << zoomLevel));

        int tilex = (int)(Math.Truncate(X));
        int tiley = (int)(Math.Truncate(Y));
        pixelX = (int)ClipByRange((tilex * 256) + ((X - tilex) * 256), mapSize - 1);
        pixelY = (int)ClipByRange((tiley * 256) + ((Y - tiley) * 256), mapSize - 1);
    }

Upvotes: 1

Related Questions