node.js - Node.js api - 我们可以根据谷歌地图获得两个纬度之间的准确距离,给出距离结果吗?
问题描述
在我们的移动应用程序中具有基于位置的功能。所以我实现了 npm geodist 来获取两个坐标之间的距离(由 hasrsine 公式使用)。geodist 距离结果与谷歌地图结果不同。我可以根据提供的相同谷歌地图在 npm geodist 中获得距离结果吗?请任何人对此提供帮助。提前致谢
var geodist = require('geodist')
var distance = geodist({lat: 11.0145, lon: 76.9864}, {lat: 11.0167, lon: 76.9774}, {exact: true, unit: 'km'})
我在精度模式下得到 1.01 公里的结果。
但我在谷歌地图中测试过的两个地方之间的相同 - 'Ukkadam Bus Shed, Ukkadam, Coimbatore, Tamil Nadu 641008' 和 'Noble Business Centre, Avinashi Rd, PN Palayam, Coimbatore, Tamil Nadu 641037' - 它给出的结果5.8公里
解决方案
我就是这样做的。首先,获得需要距离值的结果。
public static getDetails = async (req: Request, res: Response) => {
const id = req.params.id;
// Our application's user current position received from browser
const latitude = req.query.lat;
const longitude = req.query.long;
await new sql.ConnectionPool(CommonConstants.connectionString).connect().then(pool => {
return pool.request()
.input('Id', sql.Int, id)
.execute('GetSupplierDetails')
}).then(result => {
sql.close();
const rows = result.recordset.map(async (supplier) => {
const data = { origin: [latitude, longitude], destination: [supplier.Latitude, supplier.Longitude] }; // Setting coordinates here
const distance = await GetDistance(data) || 0;
Object.defineProperty(supplier, 'Distance', {
enumerable: true,
configurable: true,
writable: true,
value: distance
});
return supplier;
});
Promise.all(rows).then((values) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.status(200).json(values);
});
}).catch(err => {
res.status(500).send({ message: err })
sql.close();
});
sql.on('error', err => {
// ... error handler
});
}
这就是连接到 Google Distance Matrix API 的函数。
import { Constants } from "./constants";
const https = require('https');
export async function GetDistance(coords) {
const { origin, destination } = coords;
return new Promise((resolve, reject) => {
https.get(`${Constants.GoogleMapsUrl}?origins=${origin[0]},${origin[1]}
&destinations=${destination[0]},${destination[1]}
&key=${Constants.GoogleMapsApiKey}`, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
const distance = JSON.parse(data);
resolve(distance.rows[0].elements[0].distance.value);
});
}).on("error", (err) => {
reject("Error: " + err.message);
});
});
}
推荐阅读
- excel - 将 Evaluate 与字符串变量一起使用,而不是与范围对象一起使用
- javascript - 如何在 discord.js 中使用审核日志的成员角色更新部分
- azure-data-explorer - 从表中获取所有值但具有不同的 RunID
- databricks - Databricks 访问本地笔记本
- python - 循环产生不正确的统计数据和 P 值
- fb-hydra - Hydra:使用 Compose API 覆盖 hydra.run.dir/working 目录管理
- python - 熊猫`hash_pandas_object`不会为重复的整体产生重复的哈希值
- c++ - 收到错误“未定义对 MainWindow 的引用”
- html - 无序列表布局和之后的段落的问题
- reactjs - React Material-UI - TablePagination - onChangePage 不是函数