使用 Google Maps Distance Matrix API 获取两个地址之间的旅行时间

IT技术 javascript google-maps reactjs google-maps-api-3 react-native
2021-05-27 05:04:09

我正在设置一个例程,以使用Google Maps Distance Matrix API获取两个地点之间的旅行时间

来自他们页面的示例:

如果在Washington, DC之间New York City, NY,则请求应如下所示:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=“MY_API_KEY_HERE

如果我像任何 https 调用一样在 chrome 中正常调用上述内容,使用我的 API 密钥,它就可以正常工作。结果在这里

但是当我使用任何其他地址时,我总是在我的应用程序中得到INAVLID_REQUEST,但在 chrome 中工作正常。这是一个具有零评论/答案的副本

他们的文档

INVALID_REQUEST:提供的请求无效。这通常是由于缺少必填字段。请参阅上面的“支持的字段列表”。

我的用法:

export async function getDistance()
{
    // get location of base
    const BaseLocation = "555 E Lafayette St, Detroit, MI 48226";

    // get locations of targets
    const TargetLocation = "21000 W 10 Mile Rd, Southfield, MI 48075";

    // prepare final API call
    let ApiURL = "https://maps.googleapis.com/maps/api/distancematrix/json?";
    let params = `origins=${BaseLocation}&destinations=${TargetLocation}&key=${GOOGLE_DISTANCES_API_KEY}`;  
    let finalApiURL = `${ApiURL}${encodeURI(params)}`;

    console.log("finalApiURL:\n");
    console.log(finalApiURL);

    // get duration/distance from base to each target
    try {
            let response =  await fetch(ApiURL);
            let responseJson = await response.json();
            console.log("responseJson:\n");
            console.log(responseJson);
        } catch(error) {
            console.error(error);
        } 
}

我从另一个文件中调用它,如下所示:

constructor(props) {
    // ..
    getDistance();

}

结果在控制台(不工作 - INVALID_REQUEST):

finalApiURL:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=555%20E%20Lafayette%20St,%20Detroit,%20MI%2048226&destinations=21000%20W%2010%20Mile%20Rd,%20Southfield,%20MI%2048075&key="Can't Expose My Key On Stack Overflow"

responseJson:

Object {destination_addresses: Array[0], origin_addresses: Array[0], rows: Array[0], status: "INVALID_REQUEST"}

如果我finalApiURL在 Chrome 中复制和粘贴并使用它,它工作正常。结果:

{
   "destination_addresses" : [ "21000 W 10 Mile Rd, Southfield, MI 48075, USA" ],
   "origin_addresses" : [ "555 E Lafayette St, Detroit, MI 48226, USA" ],
   "rows" : [{
         "elements" : [{
               "distance" : {
                  "text" : "28.1 km",
                  "value" : 28073},
               "duration" : {
                  "text" : "23 mins",
                  "value" : 1367},
               "status" : "OK"}]}],
   "status" : "OK"
}

会有什么问题?请和谢谢

2个回答

这只是一个错字,这是正确的行:

let response = await fetch(finalApiURL);

ApiURL,这个没有参数,因此无效,正如文档所说的那样;)

我希望这会奏效。如果你没有等待支持,你可以试试这个。

setTimeout(() => {
      let response = await fetch(finalApiURL);

          });