javascript - Javascript - 在两组数字之间添加缺失值
问题描述
我脑子里有一个概念,但不完全确定实现它的最佳方式。
我正在研究(在 JavaScript 中)填充两点之间缺失的坐标数据值(以纬度/经度对)的方法。
我在下面有两个坐标对:
Point A lat="32.7188350" lon="-16.7611710"
Point B lat="32.711461" lon="-16.911347"
我首先需要将每对的纬度和经度提取到一个单独的值中。
所以...
latA="32.718835"
lonA="-16.761171"
latB="32.711461"
lonB="-16.911347"
我想以该精度在 latA 和 latB 之间插入附加(缺失)值。在此示例中,我们将创建 7373 个附加数字/纬度点
32.718835 - 32.711461 = 0.007374
然后我想为每个纬度点插入相同数量的相应纵向点(7373)。
最终结果将是 7373 个额外的坐标对 - 从而填补空白。
任何关于如何实现这一点的建议都非常感谢。
解决方案
注意:我假设您想要 A 和 B 之间的线上的点列表
无论两个点如何相互关联,以下代码都将运行,即 latA 是否大于或小于 latB,以及 lonA 是否大于或小于 lonB 的任意组合
这可能有点令人费解,“整数”的使用可能有点过分,但这应该让您了解如何进行
var latA=32.718835,
lonA=-16.761171,
latB=32.711461,
lonB=-16.911347,
lat = Math.floor(latA * 1e6), // use integers
lon = Math.floor(lonA * 1e6),
count = Math.floor(Math.abs(latA-latB)*1e6)+1, // count is always positive, and we add 1 so the following is correct
lonDiff = (lonB-lonA) / count * 1e6, // this can be either positive or negative, we don't care, it's multiplied by 1e6 so we use integers
latSign = Math.sign(latB - latA), // so we go in the right direction
arr = [];
for (let i = 0; i <= count; i++) { // use <= so we have both A and B in the array
arr.push({
lat: (lat / 1e6).toFixed(6),
lon: (lon / 1e6).toFixed(6)
});
lat += latSign;
lon += lonDiff;
}
console.log(arr[0], arr.slice(-1)); // just to show that first/last points are correct
但是,使用此代码,点数始终由纬度差异决定 - 在这种情况下,对于纬度的每 1/1000000 度,经度大约有 20/1000000 度的变化 - 不确定是否要插入点取决于纬度与经度的最大或最小差异
下面的代码是通用的——事实上,它将选择更大的差异来循环——代码中的注释显示了要更改的两个地方,以使其行为与上面的代码完全相同
var latA=32.718835,
lonA=-16.761171,
latB=32.711461,
lonB=-16.911347,
lat = Math.floor(latA * 1e6), // use integers
lon = Math.floor(lonA * 1e6),
countLat = Math.floor(Math.abs(latA-latB)*1e6)+1,
countLon = Math.floor(Math.abs(lonA-lonB)*1e6)+1,
count = Math.max(countLat, countLon), // change to Math.min to use least number of points
lonDiff = (lonB-lonA) / countLat * 1e6,
latDiff = (latB-latA) / countLon * 1e6,
latSign = Math.sign(latB - latA),
lonSign = Math.sign(lonB - lonA),
arr = [];
if (countLat < countLon) { // change to > to use least number of points
lonDiff = lonSign;
} else {
latDiff = latSign;
}
for (let i = 0; i <= count; i++) {
arr.push({
lat: (lat / 1e6).toFixed(6),
lon: (lon / 1e6).toFixed(6)
});
lat += latDiff;
lon += lonDiff;
}
console.log(arr.length, arr[0], arr.slice(-1)[0]);
推荐阅读
- java - 如何在 Kotlin 中为当前祈祷设置背景
- c++ - 如何在 sudo 环境中使用 dbus?
- javascript - 使用 configuration.json 中的标志覆盖反应组件的测试用例
- r - 如果 R 脚本的执行被中断,如何自动重新启动它的执行
- wolfram-mathematica - Mathematica 不会将单元格评估为数值
- sql - 将具有 Json 值的列拆分为 Postgres 中的多个列
- reactjs - React 覆盖子元素样式
- python - 基于excel文件在Django中批量创建或更新数据库模型中的对象
- java - Javafx 按钮悬停效果
- reactjs - 扩展参数必须具有元组类型或传递给剩余参数 React