-
-
Save bartekupartek/b5900ff67adb14fe91b82ccc33ffdd4f to your computer and use it in GitHub Desktop.
Mercator Projection, from Google with Google-ly bits removed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Mercator = (function(){ | |
/** | |
Mercator Projection | |
ref: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1 | |
**/ | |
function MercatorProjection(tileSize) { | |
this.tileSize = tileSize || 256; | |
this.ONE_DEGREE = Math.PI / 180; | |
this.pixelOrigin_ = [this.tileSize / 2, this.tileSize / 2]; | |
this.pixelsPerLonDegree_ = this.tileSize / 360; | |
this.pixelsPerLonRadian_ = this.tileSize / (2 * Math.PI); | |
}; | |
MercatorProjection.prototype.bound = function(value, opt_min, opt_max){ | |
if (opt_min != null) value = Math.max(value, opt_min); | |
if (opt_max != null) value = Math.min(value, opt_max); | |
return value; | |
}; | |
MercatorProjection.prototype.radiansToDegrees = function(rad){ | |
return rad / this.ONE_DEGREE; | |
}; | |
MercatorProjection.prototype.degreesToRadians = function(deg){ | |
return deg * this.ONE_DEGREE; | |
}; | |
MercatorProjection.prototype.fromLatLngToPoint = function(latLng, zoom, opt_point) { | |
var me = this; | |
var point = opt_point || [0, 0]; | |
var origin = me.pixelOrigin_; | |
point[0] = origin[0] + latLng[1] * me.pixelsPerLonDegree_; | |
// Truncating to 0.9999 effectively limits latitude to 89.189. This is | |
// about a third of a tile past the edge of the world tile. | |
var siny = me.bound(Math.sin(me.degreesToRadians(latLng[0])), -0.9999, | |
0.9999); | |
point[1] = origin[1] + 0.5 * Math.log((1 + siny) / (1 - siny)) * | |
-me.pixelsPerLonRadian_; | |
var n = 1 << zoom; | |
point[0] = point[0] * n; | |
point[1] = point[1] * n; | |
return point; | |
}; | |
MercatorProjection.prototype.fromPointToLatLng = function(point) { | |
var me = this; | |
var origin = me.pixelOrigin_; | |
var lng = (point[0] - origin[0]) / me.pixelsPerLonDegree_; | |
var latRadians = (point[1] - origin[1]) / -me.pixelsPerLonRadian_; | |
var lat = me.radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - | |
Math.PI / 2); | |
return [lat, lng]; | |
}; | |
return new MercatorProjection(256); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment