4

I'm trying to calculate the Y position on a map with mercator projection given the latitude in degrees. Here's what I need:

//mapHeight might be 600 (pixels), for example
//latitudeInDegrees ranges from -90 to 90
public double CalculateY(double mapHeight, double latitudeInDegrees)
{
    //what on earth do I do here to calculate the Y offset on the map?
    return ???;
}

I've tried all sorts of things I've found online (including wikipedia and stackoverflow), but none of it has worked for me. I'm probably doing something stupid but I can't figure out what. Can anyone save my sanity?

Kara
  • 6,115
  • 16
  • 50
  • 57

1 Answers1

5
public double CalculateY(double mapHeight, double latitudeInDegrees)
{
    return Math.Log(Math.Tan(latitudeInDegrees / 360d * Math.PI + Math.PI / 4));
}

Don't remember scale y with mapHeight (you should know max and min value of latitudeInDegrees for taht)

Quote from Wikipedia:

At latitudes higher than 70° north or south, the Mercator projection is practically unusable.

You should write code like this:

private double CalculateYRelative(double latitudeInDegrees)
{
    return Math.Log(Math.Tan(latitudeInDegrees / 360d * Math.PI + Math.PI / 4));
}
...
minY = CalculateYRelative(MinLatitudeInDegrees);
maxY = CalculateYRelative(MaxLatitudeInDegrees);
...
public double CalculateY(double mapHeight, double latitudeInDegrees)
{
    return mapHeight*
           (CalculateYRelative(latitudeInDegrees) - minY) / (maxY - minY);
}

For more information:

Wikipedia

Same question

Same question 2

Community
  • 1
  • 1
AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
  • Your comment about scaling makes no sense to me. Can you please clarify? Once I know max and min latitudes, how do I use that to adjust according to the mapHeight? –  Oct 10 '09 at 19:52
  • Thanks so much. I had seen all your linked answers, but none explained sufficiently for me to get this working. Your edits helped me understand this. –  Oct 10 '09 at 20:03
  • @spanks, see my new edit. MinLatitudeInDegrees & MaxLatitudeInDegrees are your const. You should calculate minY & maxY with this const and use results in CalculateY. CalculateY returns value in [0, maxHeight] – AndreyAkinshin Oct 10 '09 at 20:04