首页 > 解决方案 > 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公里

标签: node.js

解决方案


我就是这样做的。首先,获得需要距离值的结果。

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);
        });
    });
}

推荐阅读