I'm using the Google Maps APIs for a web application I'm writing, and now I'm running into cross-domain request issues. What's strange is that XMLHttpRequest.send()
succeeds when using "https://maps.googleapis.com/maps/api/geocode/json?address=..."
but fails with a NetworkError
when doing a GET request to "https://maps.googleapis.com/maps/api/directions/json?origin=...&destination=..."
.
Here is the code that I'm using:
// HTTP GET request
function httpGetJSON(url) {
var req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
return JSON.parse(req.responseText);
}
// lat/lon of street address
function locationOfAddress(address) {
var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" +
encodeURIComponent(address);
var response = httpGetJSON(url);
return response.results[0].geometry.location;
}
// driving distance between street addresses
function drivingDistance(addressFrom, addressTo) {
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
encodeURIComponent(addressFrom) + "&destination=" +
encodeURIComponent(addressTo);
var response = httpGetJSON(url);
return response.routes[0].legs[0].distance;
}
// getting lat/lon of White House works
var center = locationOfAddress("1600 Pennsylvania Ave NW, Washington, DC 20500");
// getting distance from White House to Capitol Building fails with NetworkError
var dist = drivingDistance(
"1600 Pennsylvania Ave NW, Washington, DC 20500",
"2 15th St NW, Washington, DC 20007");
The only difference between the two URLs is that one is accessing the geocode
API while the other uses the directions
API, and of course that the query strings are different.
Why would these differences make one HTTP GET
request succeed and the other fail?
(Note: I've checked both URLs and both get JSON responses when put into any web browser)