我正在尝试使用 Google API 获取两个位置之间的距离,并在 node.js 中进行编码。我想将值存储在变量中,该怎么做?
最佳答案
如果您知道他们的名字,您可以尝试以下示例,该示例以 JSON 格式请求华盛顿特区和纽约市之间的距离矩阵数据
var request = require('request');
request.get('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=YOUR_API_KEY'
, function (error, response) {
if(error){
//Error handling
}else{
/*
the response will be in a "JSON" format, you can see it in
details by entering the previous URL into your web browser
(be sure to replace YOUR_API_KEY with your actual API key)
*/
}
})
或者您可以使用此模块node-googlemaps它包装了 api。
如果你知道它们的经度和纬度,我认为没有 npm 包包含所需的 google 库,所以我建议你使用此 npm 模块 Haversine formula 通过半正弦公式计算距离这是一个简单的例子:
var haversine = require('haversine-distance')
var a = { latitude: 37.8136, longitude: 144.9631 }
var b = { latitude: 33.8650, longitude: 151.2094 }
// 714504.18 (in meters)
console.log(haversine(a, b))
关于node.js - 如何让 Google API 返回 node.js 上两点之间的距离并将其存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737576/