javascript - 当按位或具有破坏性时,如何解码谷歌折线?
问题描述
我正在寻找解码编码的谷歌折线:
`~oia@
但是,要反转其中一个步骤需要反转按位或运算,这是破坏性的。
我看到它在这里完成了:如何解码 Google 的折线算法?但我看不到如何在 Javascript 中做到这一点。
这是我到目前为止所拥有的:
const partialDecodedPolyline = "`~oia@".split('').map(char => (char.codePointAt()-63).toString(2))
console.log(partialDecodedPolyline)
下一步是反转按位或……这怎么可能?
解决方案
有一个图书馆https://github.com/mapbox/polyline/blob/master/src/polyline.js
/*
https://github.com/mapbox/polyline/blob/master/src/polyline.js
*/
const decode = function(str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, Number.isInteger(precision) ? precision : 5);
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Reset shift, result, and byte
byte = null;
shift = 0;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
shift = result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += latitude_change;
lng += longitude_change;
coordinates.push([lat / factor, lng / factor]);
}
return coordinates;
};
console.log(decode("`~oia@"));
推荐阅读
- python - Python`str`子类不调用`__add__`
- angular - 永远不会在带有单元测试 angular + jasmine 和 SpyOn 的 switchMap 中调用函数
- excel - 日历中的员工缺勤(vlookup?)
- ios - 运行单元测试时每隔一次Xcode 10“无法安装此应用程序”
- sql-server - 在分子和/或分母中添加转换为小数?
- django - 从 Django 表单中清除“ChoiceField”
- airflow - 使用环境变量在 Airflow 中设置 Google Cloud 连接
- reactjs - React Select 与 Custom MultiValueContainer 和 Apollo Mutation 不合作
- spring-cloud - Spring Cloud Gateway——通过调度刷新路由
- typescript - TypeScript:多维数组参数的正确方法