Reputation:
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?
Upvotes: 4
Views: 3291
Reputation: 19051
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:
Upvotes: 5