Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Created August 28, 2019 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiwenl/f37f54d9974fd6b73252a2cc81ca6a66 to your computer and use it in GitHub Desktop.
Save yiwenl/f37f54d9974fd6b73252a2cc81ca6a66 to your computer and use it in GitHub Desktop.
// compression.js
const defaultPrecision = 10;
const encode = (a, b, mPrecision=defaultPrecision) => {
const precision = mPrecision;
const base = Math.floor(Math.sqrt(Math.pow(93, precision)));
let lat = a, lng = b;
let lng935 = Math.floor( ( parseFloat(lng) +180)*base/360 );
let lat935 = Math.floor( ( parseFloat(lat) +90)*base/180 );
let result = lat935*base+lng935;
let code = "", sub, rank = 0;
for (let i=0; i<precision; i++) {
sub = Math.floor( result/Math.pow(93, i) )%93;
code += String.fromCharCode(33 + sub);
}
return code;
}
const decode = (str, mPrecision=defaultPrecision) => {
const precision = mPrecision;
const base = Math.floor(Math.sqrt(Math.pow(93, precision)));
let result = 0;
for (let i=0; i<precision; i++) {
result += ( str.charCodeAt(i)-33 )*Math.pow(93, i);
}
let lngBis = ( ( result%base )*360/base )-180;
let latBis = ( (result-lngBis*base)*180/base )/base-90;
return [latBis, lngBis];
}
module.exports = {
encode,
decode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment