4

We have an old mapping system we are needing to convert some data to and from.

We need to convert from Lng/lat to XY and from XY to Lng/Lat.

We can convert from Lng/Lat to XY Using the following:

MapWidth and MapHeight = 8192

x = (LngX + 180) * (mapWidth / 360)
y = (mapHeight / 2) - (mapWidth * Math.Log(Math.Tan((Math.PI / 4) + ((LatY * Math.PI / 180) / 2))) / (2 * Math.PI))

What we can't get right is the conversion back, we have the X right:

lng = (X - (mapWidth / 2)) / (mapWidth / 360)

But the Y is incorrect,

lat = (Math.Exp(-(Y - (mapHeight / 2)) / mapWidth * (2 * Math.PI)) - Math.Tan((Math.PI / 4)) * 2) / (Math.PI / 180)
Jean Marie
  • 88,997
LiamB
  • 143

2 Answers2

3

You have so many parentheses in your latitude formula that it’s hard to see what goes with what.

Let $\phi = \mathrm{LatY} \times \frac\pi{180},$ that is, if LatY is the latitude in degrees then $\phi$ is the latitude in radians. Let $h$ be mapHeight and let $w$ be mapWidth. Then your formula for $y$ becomes this in mathematical notation: $$ y = \frac h2 - \frac{w \ln\left(\tan\left(\frac\pi4 + \frac\phi2\right)\right) }{2 \pi} $$

This is similar to the formula found at http://mathworld.wolfram.com/MercatorProjection.html except for the scaling and translation factors (which you want in order to fit the output on the display).

Solving the equation for $\phi$ (still in radians), $$ \phi = 2 \arctan\left(\exp\left(\frac{2\pi}{w} \left(\frac h2 - y \right) \right)\right) - \frac\pi2. $$ Multiply by $\frac{180}{\pi}$ to get the answer in degrees.

Again it’s hard to be sure due to the profusion of parentheses, but the attempted formula seems to be equivalent to the mathematical equation

$$ \mathrm{lat} = \frac{\exp\left(-\frac{\left(Y - \frac h2 \right)}{w} \times 2 \pi \right) - \tan\left(\frac\pi4\right) \times 2}{\pi / 180}, $$

which is clearly quite different. The fact that $\tan\left(\frac\pi4\right)$ (which is just equal to $1$) occurs in there should be a red flag indicating that something was done in the wrong order.

David K
  • 108,155
1

Can't spot the issue with the final equation but reverse engineering the y = equation will work. Doing that you end up with the following:

lat = ((Math.arctan(Math.exp((((mapHeight / 2) -y) / mapWidth) * (2 * Math.PI))) - (Math.PI / 4))*2)/(Math.PI/180)
JamieM23
  • 126