Reputation: 9407
I am setting up a routine to get travel time between two locations using The Google Maps Distance Matrix API.
Example from their page:
If between
Washington, DC
andNew York City, NY
, then request should look like this:https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key="MY_API_KEY_HERE"
If I call the above in chrome normally like any https call, with my API Key, it works fine. Result Here.
But when I use any other address, I always get INAVLID_REQUEST in my application, but works fine in chrome. Here is a duplicate that has zero comments/answers.
INVALID_REQUEST: The provided request was invalid. This is often due to missing required fields. See the "list of supported fields" above.
My usage:
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);
}
}
and I call it from another file like this:
constructor(props) {
// ..
getDistance();
}
Result in Console (Not working - 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"}
If I copy and paste finalApiURL
and use it in Chrome, it works fine. Results:
{
"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"
}
What would be the problem? Please and thanks
Upvotes: 1
Views: 4388
Reputation: 8945
I hope this will work . if you does not have await support you can try out this .
setTimeout(() => {
let response = await fetch(finalApiURL);
});
Upvotes: 0
Reputation: 20467
It's just a typo, here is the correct line:
let response = await fetch(finalApiURL);
Not ApiURL
, this one has no parameters and is therefore invalid, exactly as the doc says ;)
Upvotes: 2