【问题标题】:Basic usage of Google Maps Directions API in client-side JavaScript [duplicate]Google Maps Directions API 在客户端 JavaScript 中的基本用法 [重复]
【发布时间】:2021-08-26 19:51:39
【问题描述】:

在制作 Firefox 扩展程序的过程中,我正在测试 Google Maps Directions API。 使用 API,我想发出客户端请求以从扩展程序中查找地址之间的方向。

我对 JavaScript 很陌生,但据我所知,我应该使用 fetch 函数来发出 http 请求。 我正在使用以下 URL 发出测试请求:https://maps.googleapis.com/maps/api/directions/json?key=<my_api_key>&origin=Ca%C3%B1on+City%2C+Colorado&destination=Royal+Gorge+Bridge+%26+Park%2C+Colorado

该 URL 在我的浏览器中有效,并提供了我期望的 JSON。 但是,当我尝试使用 JavaScript 发出请求时,我得到了错误。 这大约是我正在使用的 JS:

const listing_address = "Cañon City, Colorado"
const goal_address = "Royal Gorge Bridge & Park, Colorado"
const google_maps_base_url = "https://maps.googleapis.com/maps/api/directions/json?"

let query_data = new URLSearchParams({
    key: api_key,
    origin: listing_address,
    destination: goal_address,
})

let query_url = google_maps_base_url + query_data.toString()
console.debug(query_url)

fetch(query_url)
    .then(data => { return data })
    .then(res => { console.log(res) })

我从一个测试 html 文件运行它,我只是在我的 Firefox 浏览器中打开它。 这给了我一个与“同源策略”和 CORS 标头相关的错误。 我四处搜索并尝试了no-cors 模式,这给了我一个我无法使用的“不透明”响应。 我还尝试添加以下标题:

let headers = new Headers()
headers.append("Access-Control-Allow-Origin", "*")
headers.append("Access-Control-Allow-Headers", "*")

fetch(query_url, {
    headers: headers
})
    .then(data => { return data })
    .then(res => { console.log(res) })

这会导致与之前相同的错误,缺少 CORS 标头。

我的主要问题是:

  1. 我做错了什么导致我无法使用 API?
  2. 是否有关于如何从客户端使用此 API 的一般指南?希望有 JS 示例 - 我已经用谷歌搜索了好几天,但没有找到我正在寻找的简单东西。

希望有人能够提供帮助。 谢谢!

【问题讨论】:

标签: javascript google-directions-api


【解决方案1】:

您必须使用 maps/directions api 而不是 fetch。查看文档和 Google.maps.directionsservice。

Good answer for a similar question

【讨论】:

  • 这看起来很相关,但是否可以在没有地图对象的情况下做到这一点?我根本不需要视觉效果,只需要路线 API。
【解决方案2】:

const directionsService = new google.maps.DirectionsService();

directionsService
    .route({
      origin: {
        query: "California",
      },
      destination: {
        query: "Idaho"
      },
    })
    .then((response) => {
      console.log(response);
    })
    .catch((e) => window.alert("Directions request failed due to " + e));

来自https://developers.google.com/maps/documentation/javascript/examples/directions-simple

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-12
    • 2016-10-22
    • 2015-12-12
    • 1970-01-01
    • 2014-08-25
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多