Mercator projection: formula for latitude based on pixels?

I am basing this question on knowledge from Mercator projection: problem with latitude formula

In that question/answer, the formula is given for working out how many pixels above/below the equator a given latitude will be, assuming you know the total size of the map. The formula is:

``````Pixel Shift = Width / (2 * pi) * ln(tan(pi / 4 + (Latitude / 2) * pi / 180))
``````

For example, on a 5000 pixels wide map, the latitude 38 would be 571.36 pixels above the equator. I have built a script using this formula and it works perfectly.

What I would like is a similar formula, but which provides a latitude based on a given pixel shift. So I could feed it the answer from above (571.36) and it would give me the answer 38.

I have spent some hours now trying to figure out (based on scraps of remembered high school math) how to balance and switch the formula around but it's beyond me.

Can anyone help me with this?

Here is the code I am trying, based on Russell's answer:

``````function getPixelShift ( pxWidth, map_latitude )
{
var pi = Math.PI;
var pixelShift = (pxWidth / ( 2 * pi) ) * Math.log( Math.tan( pi / 4 + (map_latitude/2) * pi / 180 ) );
return pixelShift.toFixed(2);
}

getPixelShift (5000, 38); // Returns 571.36

function getLatitude ( pxWidth, pixelShift )
{
var pi = Math.PI;
var a = 1 / ( pxWidth / (2 * pi ) );
a = Math.exp( ( pixelShift * 2) * a );
var lat = (Math.asin( ( a - 1 ) / (a + 1) ) ) * ( pi / 180.0 );
return lat;
}

getLatitude (5000, 571.36); // Returns 0.01157551908131
``````

I'm probably implementing what you suggested wrong, sorry! I'm needing the result of `getLatitude` to be 38.

What am I doing wrong?

• My bad, in the last step try (180.0 / Math.PI) instead of (Math.PI / 180) Commented Sep 25, 2014 at 16:36

1 Answer

Try something like (taken from some C# code that converts merc coords to lat)

a = 1 / (Width / (2 * pi))

a = Math.Exp((PixelShift * 2) * a)

lat = (Math.Asin((a - 1) / (a + 1))) * (180.0 / Math.PI)