I'm trying to convert a lat/lon pair to a pixel coordinate. I have found this mercator projection but I don't understand the code. What is the factor,x_adj, y_adj variable? When I run the code without those constants my lat/lon pair is not on my map and the x and y pixel coordinate is not what I want.
function get_xy(lat, lng)
{
var mapWidth=2058;
var mapHeight=1746;
var factor=.404;
var x_adj=-391;
var y_adj=37;
var x = (mapWidth*(180+lng)/360)%mapWidth+(mapWidth/2);
var latRad = lat*Math.PI/180;
var mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
var y = (mapHeight/2)-(mapWidth*mercN/(2*Math.PI));
return { x: x*factor+x_adj,y: y*factor+y_adj}
}
[2] Covert latitude/longitude point to a pixels (x,y) on mercator projection
Here's how to get the returned variables X and Y from the function you've found...
Now X and Y contain the coordinates.
Where did those variables come from
These variables are chosen to match the computed coordinates to the background image of the map. If the projection parameters of the map were known, they could be computed. But I believe it is far more likely that they were obtained through trial and error.
How to compute a Mercator projection
If you want a more general method to describe the section of the world a given (not transverse) Mercator map shows, you can use this code:
A demo run of this code is available at http://ideone.com/05OhG6.
Regarding aspect ratio
A setup with
$xFactor != $yFactor
produces a kind of stretched Mercator projection. This is not conformal (angle-preserving) any more. If one wants a true Mercator projection, one can omit any of the first six variable assignments, i.e. those defining the bounding box or those describing the size of the resulting map, and then use some computation too choose it satisfying$xFactor == $yFactor
. But since the choice which to omit is kind of arbitrary, I feel that the above code is the most symmetric way to describe things.