Convert lat/lon to pixel coordinate?

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:

// This map would show Germany:
$south = deg2rad(47.2);
$north = deg2rad(55.2);
$west = deg2rad(5.8);
$east = deg2rad(15.2);

// This also controls the aspect ratio of the projection
$width = 1000;
$height = 1500;

// Formula for mercator projection y coordinate:
function mercY($lat) { return log(tan($lat/2 + M_PI/4)); }

// Some constants to relate chosen area to screen coordinates
$ymin = mercY($south);
$ymax = mercY($north);
$xFactor = $width/($east - $west);
$yFactor = $height/($ymax - $ymin);

function mapProject($lat, $lon) { // both in radians, use deg2rad if neccessary
  global $xFactor, $yFactor, $west, $ymax;
  $x = $lon;
  $y = mercY($lat);
  $x = ($x - $west)*$xFactor;
  $y = ($ymax - $y)*$yFactor; // y points south
  return array($x, $y);
}

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.

Leave a Comment