Skip to content

Instantly share code, notes, and snippets.

@matsadler
Created October 7, 2012 20:29
Show Gist options
  • Save matsadler/3849491 to your computer and use it in GitHub Desktop.
Save matsadler/3849491 to your computer and use it in GitHub Desktop.
JavaScript mercator projection
/*jslint vars: true */
// adapted from http://wiki.openstreetmap.org/wiki/Mercator#JavaScript
(function () {
var project = {};
if (typeof exports === "object") {
module.exports = project;
} else {
this.project = project;
}
var DegRad = Math.PI / 180,
RMax = 6378137,
RMin = 6356752.3142,
LatMin = -89.5,
LatMax = 89.5,
Eccent = Math.sqrt(1 - ((RMin / RMax) * (RMin / RMax)));
function rad(x) {
return x * DegRad;
}
function mercLng(lng) {
return RMax * rad(lng);
}
function mercLat(lat) {
if (lat > LatMax) {
lat = LatMax;
}
if (lat < LatMin) {
lat = LatMin;
}
var phi = rad(lat),
con = Eccent * Math.sin(phi),
com = 0.5 * Eccent,
ts;
con = Math.pow((1 - con) / (1 + con), com);
ts = Math.tan(0.5 * (Math.PI * 0.5 - phi)) / con;
return -(RMax * Math.log(ts));
}
function fitLat(lat, height, latMin, latMax) {
latMin = latMin || LatMin;
latMax = latMax || LatMax;
var mercLatMin = mercLat(latMin),
mercLatMax = mercLat(latMax),
mercLatHeight = -mercLatMin + mercLatMax;
return (mercLatMax - lat) * (height / mercLatHeight);
}
function fitLng(lng, width, lngMin, lngMax) {
var mercLngMin = mercLng(lngMin);
return (lng + mercLngMin) * (width / (-mercLngMin + mercLng(lngMax)));
}
function mercatorRatio(latMin, latMax, lngMin, lngMax) {
var width = -mercLng(lngMin) + mercLng(lngMax),
height = -mercLat(latMin) + mercLat(latMax);
return width / height;
}
project.mercatorRatio = mercatorRatio;
function mercator(width, height, latMin, latMax, lngMin, lngMax, latLng) {
var x = fitLng(mercLng(last(latLng)), width, lngMin, lngMax),
y = fitLat(mercLat(head(latLng)), height, latMin, latMax);
return [x, y];
}
project.mercator = mercator;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment