Transforming lat and long to Mercator x and y

I've been trying to plot a set of lat and long coordinates to a Mercator map using the following set of equations:

x = long - long0
y = ln(tan(pi/4 + lat/2))

These equations are from a page on Wolfram.

I'm using a Mercator map from Wikipedia, it's from 82 N to 82 S. Based on this I've got the current set of equations to fully map the lat/long to the image:

height = image height in pixels
width = image width in pixels

x = long * PI/180
x = x * width/(2 * PI) + width/2

latRange = 2 * 82 * PI/180
y = ln(tan(PI/4 + lat/2))
y = -(y*height/latRange - height/2)

However when I make the image I get points on my map that are higher than expected (I try to plot the tropic of cancer and I hit the north coast of Algeria).

So, can someone please tell me where I'm going wrong?

• Why not simply use the adequate Python modules: pyproj or GDAL/OGR – gene Jan 17 '16 at 8:50
• @gene At the moment I'm less interested in getting an output and more interested in the inner workings of making these types on map. I could use a python module, but I'd like to make my own. – FraserOfSmeg Jan 17 '16 at 8:52
• I see you converted your ´long´ to radians but not your ´lat´, maybe that's the issue. Also, have you tried with another Mercator map (just to be sure)? – ArMoraer Jan 17 '16 at 10:57
• @ArMoraer Sorry, I should have shown that line in the question, I do convert the lat to radians. I've tried with 4 or 5 maps :/ – FraserOfSmeg Jan 17 '16 at 11:03
• heigh/2 seems like a typo – barrycarter Jan 17 '16 at 15:56

The link you are using is a map transform and not a coordinate pair transform. The correct transform is on the main Stack Overflow site at:

https://stackoverflow.com/questions/14329691/convert-latitude-longitude-point-to-a-pixels-x-y-on-mercator-projection

latitude = φ and longitude = λ are:

E = FE + R (λ – λₒ)
N = FN + R ln[tan(π/4 + φ/2)]

where λO is the longitude of natural origin and FE and FN are false easting and false northing.

The formulae are best simplified to (as FE and FH are ignored in most use cases): The stack overflow link provides pseudocode for use in all languages as well.