Skip to content

Instantly share code, notes, and snippets.

@raine
Created September 28, 2011 17:48
Show Gist options
  • Select an option

  • Save raine/1248639 to your computer and use it in GitHub Desktop.

Select an option

Save raine/1248639 to your computer and use it in GitHub Desktop.
TILE_SIZE = 256
lat = 41.850033
lon = -87.65005229999997
zoom = 10
numTiles = 1 << zoom
bound = (value, min, max) ->
if min then return Math.max value, min
if max then return Math.min value, max
degreesToRadians = (deg) ->
deg * (Math.PI / 180)
class MercatorProjection
constructor: ->
this.pixelOriginX = this.pixelOriginY = TILE_SIZE / 2
this.pixelsPerLonDegree = TILE_SIZE / 360
this.pixelsPerLonRadian = TILE_SIZE / (2 * Math.PI)
fromLatLngToPoint: (lat, lon) ->
x = this.pixelOriginX + lon * this.pixelsPerLonDegree
sinY = bound Math.sin(degreesToRadians(lat)), -0.9999, 0.9999
y = this.pixelOriginY + 0.5 * Math.log((1 + sinY) / (1 - sinY)) * -this.pixelsPerLonRadian
[ x, y ]
projection = new MercatorProjection
worldCoordinate = projection.fromLatLngToPoint lat, lon
pixelCoordinate = (c * numTiles for c in worldCoordinate)
tileCoordinate = (Math.floor(c / TILE_SIZE) for c in pixelCoordinate)
@raine
Copy link
Copy Markdown
Author

raine commented Sep 28, 2011

Ported some code from here to coffeescript, don't ask me how it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment