【发布时间】:2017-10-06 15:53:57
【问题描述】:
我正在设置一个例程,使用The 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 密钥,它可以正常工作。 Result Here.
但是当我使用任何其他地址时,我总是在我的应用程序中得到 INAVLID_REQUEST,但在 chrome 中可以正常工作。 Here is a duplicate that has zero comments/answers.
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"
}
会有什么问题?请和谢谢
【问题讨论】:
-
如果您使用
curl访问该 URL,您是否也会收到相同的错误?我用自己的密钥尝试了curl -i $finalApiURL,它对我有用。 -
抱歉,我可能误读了某些内容(或者可能是在您编辑之前……不重要)。如果您将该 URL 粘贴到 Chrome 的地址栏并且它可以工作,那么您不需要使用
curl进行测试(它只是一个命令行工具)。您与副本有一个共同点:您正在从非浏览器程序访问 API,但这不应该有所作为。嗯... -
@HuguesMoreau 是的,对不起,我想我在您的评论之后添加了重复的部分。确实很奇怪,我编辑并添加了我的确切用法,也许看看? async/wait 跟这个有什么关系?
标签: javascript google-maps reactjs google-maps-api-3 react-native