In the process of making a Firefox-extension, I'm testing out the Google Maps Directions API. Using the API I would like to make client-side requests to find directions between addresses from the extension.
I'm quite new to JavaScript, but as I understand, I should use the fetch
function to make http-requests.
I'm making a test request with the following 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
The URL works in my browser, and gives the JSON I'm expecting. However, when I'm trying to use JavaScript to make the request, I get errors. This is approximately the JS I'm using:
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) })
I'm running this from a test html file I'm simply opening in my Firefox browser.
This is giving me an error related to "Same Origin Policy" and CORS-headers.
I've googled around and attempted the no-cors
mode, which gives me an "opaque" response which I'm not able to use.
I've also attempted to add the following headers:
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) })
That results in the same error as earlier, with the CORS-headers missing.
My main questions are:
- What am I doing wrong so that I can't use the API?
- Is there a general guide on how to use this API from a client? Hopefully with JS examples - I've googled for several days without finding the simple things I'm looking for.
Hope someone will be able to help. Thanks!