如何从图书馆访问 Google 地图路线 API 客户端

How to access the Google Maps Directions API client-side from a library

我想根据 Google 方向 API 发送请求。 Google提供了一个Node.JS client library for the API. However, this AP is server-side only. Attempting to use it from a browser script results in a CORS failure. Multiple past answers (such as this one)表示这个库根本不能这样用

替代方法是使用 client-side JavaScript API。但是,这需要在文档根目录中添加一个 <script> 标记。那是我需要的错误抽象级别。我想改用库或 dot-js 文件中的方法。

按照的建议,我想问一下:有没有可以通过npm获得的模块,我可以用来查询Google路线API客户端?

https://developers.google.com/maps/documentation/directions

这是路线 API 网络服务不需要 添加 <script> 标签。

您可以按照示例直接向服务发出请求:

https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=YOUR_API_KEY

一旦您生成了 API 密钥并将请求中的 YOUR_API_KEY 替换为您自己的密钥。

不可能天真地从客户端访问 Google 地图路线 API。 Web 浏览器实施 Single-Origin 策略,该策略要求对域的任何请求都来自同一域。默认情况下不允许域之间的要求。 Cross-domain 请求可以通过在端点上设置正确的 CORS headers 在服务器上启用,但是 Google 地图服务器选择不这样做。

有两种解决方法。一种是使用 Google API Auth 库包装请求。但是,我无法让它工作。

有用的是使用 reverse proxy。 Google Directions API 介绍页面中实际上提到了此解决方法(尽管是倾斜的)。您需要设置一个服务器,将任何请求转发给 API 请求,然后 returns 将 API 请求转发给原始请求者。由于现在这是一个 server-side 请求,SOP 将不适用,您可以开始了。

有关实施示例,请查看 GitHub 上的 this repository