Skip to content

Instantly share code, notes, and snippets.

@habibutsu
Created May 13, 2016 10:21
Show Gist options
  • Save habibutsu/1a7bd1b3b90b35c469cc641f4cad6f8b to your computer and use it in GitHub Desktop.
Save habibutsu/1a7bd1b3b90b35c469cc641f4cad6f8b to your computer and use it in GitHub Desktop.
Mercator projection
// https://en.wikipedia.org/wiki/Mercator_projection
function MercatorProjection(){
this.EARTH_RADIUS = 6378137 // WGS-84
this.EARTH_HALF_CIRCUMFERENCE = Math.PI * this.EARTH_RADIUS // 20037508.342789244
this.EARTH_METERS_PER_DEGREE = (Math.PI * this.EARTH_RADIUS) / 180 // 111319.49079327358
this.RADIAN = Math.PI / 180
this.DEGREE = 180 / Math.PI
}
MercatorProjection.prototype.toDegree = function(radian){
return this.DEGREE * radian
}
MercatorProjection.prototype.toRadian = function(degree){
return this.RADIAN * degree
}
MercatorProjection.prototype.LatLonToMeters = function(lat, lon){
// for radians
//mx = this.toRadian(EARTH_RADIUS * lon)
//my = EARTH_RADIUS * Math.log( Math.tan(Math.PI / 4.0 + (lat*this.RADIAN) / 2.0))
// for degrees
var mx = this.EARTH_METERS_PER_DEGREE * lon
var my = this.EARTH_RADIUS * Math.log(Math.tan(this.toRadian(45 + lat / 2.0)))
return [mx, my]
}
MercatorProjection.prototype.MetersToLatLon = function(mx, my){
// for degrees
var lon = mx / this.EARTH_METERS_PER_DEGREE
//lat = this.DEGREE * (2.0 * Math.atan(Math.exp((my/this.EARTH_METERS_PER_DEGREE)*this.RADIAN)) - Math.PI / 2.0)
// for radians
//lon = (mx / this.EARTH_RADIUS) * this.DEGREE
var lat = this.toDegree(2.0 * Math.atan(Math.exp(my/this.EARTH_RADIUS)) - Math.PI / 2.0)
return [lat, lon]
}
MercatorProjection.prototype.MoveTo = function(lat, lon, distance, heading){
var heading_rad = this.toRadian(heading)
var [mx, my] = this.LatLonToMeters(lat, lon)
var scale_factor = Math.cos(this.toRadian(lat))
var map_distance = scale_factor * distance
mx = mx + map_distance * Math.sin(heading_rad)
my = my + map_distance * Math.cos(heading_rad)
return this.MetersToLatLon(mx, my)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment