Created
January 22, 2014 15:09
-
-
Save thingsinjars/8560312 to your computer and use it in GitHub Desktop.
Useful geo functions
This file contains hidden or 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
function haversineDistance(lat1, lon1, lat2, lon2) { | |
'use strict'; | |
var R = 6378100; // metres | |
var dLat = this.deg2rad(lat2 - lat1); | |
var dLon = this.deg2rad(lon2 - lon1); | |
var a = | |
Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * | |
Math.sin(dLon / 2) * Math.sin(dLon / 2); | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
var d = R * c; | |
return d; | |
} | |
function deg2rad(deg) { | |
'use strict'; | |
return deg * (Math.PI / 180); | |
} |
This file contains hidden or 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
//Convert Latitude/Longitude to Quadkey | |
function tileXYToQuadKey(tile, zoom) { | |
var quadKey='', i, digit, mask; | |
for (i = zoom; i > 0; i--) { | |
digit = '0'; | |
mask = 1 << (i - 1); | |
if ((tile.x & mask) !== 0) { | |
digit++; | |
} | |
if ((tile.y & mask) !== 0) { | |
digit++; | |
digit++; | |
} | |
quadKey+= "" + digit; | |
} | |
return quadKey; | |
} | |
function tileSystem(latitude, longitude) { | |
var sinLatitude = Math.sin(latitude * Math.PI/180); | |
var x = ((longitude + 180) / 360) * 256 * Math.pow(2,16); | |
var y = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) * 256 * Math.pow(2, 16); | |
return {x: Math.round(x/256), y: Math.round(y/256)}; | |
} | |
var quadkey = tileXYToQuadKey(tileSystem(latitude, longitude), 16); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment