Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Created Aug 28, 2019
Embed
What would you like to do?
// 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