Skip to content

Instantly share code, notes, and snippets.

@Bobsans
Created July 23, 2020 21:55
Show Gist options
  • Select an option

  • Save Bobsans/6da60dbab82912592297afbd03b6a9d4 to your computer and use it in GitHub Desktop.

Select an option

Save Bobsans/6da60dbab82912592297afbd03b6a9d4 to your computer and use it in GitHub Desktop.
Maps polygon coordinates encoder/decoder
export default class CoordinatesEncoder {
static SCALE = 1000000;
static encode(polygons) {
const result = [];
const intToCodes = (number) => {
const result = [];
for (let i = 0; i < 4; i++) {
result[i] = 255 & (number >> 8 * i); // eslint-disable-line no-bitwise
}
return result;
};
for (const polygon of polygons) {
let charCodes = [];
let previous = [0, 0];
for (let [x, y] of polygon) {
x = x * this.SCALE - previous[0];
y = y * this.SCALE - previous[1];
previous = [x + previous[0], y + previous[1]];
charCodes = charCodes.concat(intToCodes(x), intToCodes(y));
}
result.push(charCodes);
}
const encodeCharCodes = (charCodes) => {
return btoa(String.fromCharCode(...charCodes)).replace(/\//g, '_').replace(/\+/g, '-');
};
return result.map(encodeCharCodes).join(';');
}
static decode(string) {
return string.split(';').map((component) => {
component = atob(component.replace(/_/g, '/').replace(/-/g, '+'));
const points = [];
let last = [0, 0];
for (let i = 0; i < component.length; i += 8) {
let lat = 0;
let lng = 0;
const part = component.substr(i, 8);
for (let j = 0; j < 4; j++) {
lat |= part.charCodeAt(j) << 8 * j; // eslint-disable-line no-bitwise
lng |= part.charCodeAt(j + 4) << 8 * j; // eslint-disable-line no-bitwise
}
const point = [Number(((lat / this.SCALE) + last[0]).toFixed(6)), Number(((lng / this.SCALE) + last[1]).toFixed(6))];
last = point;
points.push(point);
}
return points;
});
}
}
// test
let encoded = 'dJGjAREYNgPFEQAA6_P__5UOAACCCQAAEikAAAYIAABDLQAAhRIAAA4KAADhAQAArgIAALcIAAAY8___HAkAANsDAADIAQAAa_H__xkKAACZ8___xvj__weu___n4P__GvT___Lw__8=';
let decoded = CoordinatesEncoder.decode(encoded);
let encoded2 = CoordinatesEncoder.encode(decoded);
console.log(encoded === encoded2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment