node.js - 如何让 Google API 返回 node.js 上两点之间的距离并将其存储在变量中?

标签 node.js api google-api

我正在尝试使用 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/

相关文章:

java - 使用服务器帐户模拟用户以访问其 Google Drive 时出现 401 Unauthorized 错误

html - NodeJS + HTML5 + Telnet = 可能吗?

javascript - 适用于 Firefox/Google Chrome 的 Socket.io 客户端插件

javascript - 以编程方式删除 Spotify 播放列表

python - Tweepy API 搜索方法不起作用

java - 使用 gdata 检索 Youtube 缩略图 URL?

php - Google Calendar API v3 - 使用硬编码凭据进行身份验证

node.js - peer.on ('calll' ) 永远不会被调用

javascript - 使用 JS 和 NodeJS 上传文件 post 请求

google-api - 谷歌API : Not a valid origin for the client: url has not been whitelisted for client ID "ID"