[OSM-dev] Mercator Magic (Javascript Lon/Lat to Mercator X/Y)
Christopher Schmidt
crschmidt at metacarta.com
Sat Dec 2 14:03:54 GMT 2006
One of the things that I have been having a lot of problems with is the
fact that OSM tools have not had a strong understanding of the
projection they are using. The 'converter' for Mercator to Lat Long that
is currently in use on the OSM slippy map page is woefully inaccurate --
as can be seen by the difference between the main slippy map and the WMS-C
implementation.
I tried to write something that would fix this problem a couple days ago
and failed. I've been using Proj4 for all my projection math, and
nothing has come closer than 50M.
However, I looked at some of the code I wrote over a year ago to
interact with OSM, and I found the solution: Norm Vine, a GIS expert of
many years, helped me write a Mercator conversion tool for Google maps
-- and the results from his Javascript code match Proj4's output
exactly.
So, for everyone's elucidation, here is the way to convert from latitude
and longitude to a simple mercator projection, in Javascript:
function deg_rad(ang) {
return ang * (Math.PI/180.0)
}
function merc_x(lon) {
var r_major = 6378137.000;
return r_major * deg_rad(lon);
}
function merc_y(lat) {
if (lat > 89.5)
lat = 89.5;
if (lat < -89.5)
lat = -89.5;
var r_major = 6378137.000;
var r_minor = 6356752.3142;
var temp = r_minor / r_major;
var es = 1.0 - (temp * temp);
var eccent = Math.sqrt(es);
var phi = deg_rad(lat);
var sinphi = Math.sin(phi);
var con = eccent * sinphi;
var com = .5 * eccent;
con = Math.pow(((1.0-con)/(1.0+con)), com);
var ts = Math.tan(.5 * ((Math.PI*0.5) - phi))/con;
var y = 0 - r_major * Math.log(ts);
return y;
}
function merc(x,y) {
return [merc_x(x),merc_y(y)];
}
The sooner people can start using this, the better off we'll all be.
Please let me know if you have any questions.
Regards,
--
Christopher Schmidt
MetaCarta
More information about the dev
mailing list