Search code examples
javascriptgoogle-mapsxmlhttprequestgoogle-roads-api

Google Maps' Roads API not working with XHR


I need to snap a Polyline to a road, and I found an example from google that works really well. I tweak it a little bit, and then I get a NetworkError from JavaScript, saying that the response headers don't have an "Access-Control-Allow-Origin" header. If I inspect the responseText from my XHR, it gives me the standard Google 404 page.

Question is, how am I supposed to use the Roads API if it doesn't allow for cross-origin requests?

Code:

getSnappedPoints: function (path) { //path is an array of latlng
    var xhr = new XMLHttpRequest();
    var snappedCoords = new Array();
    var pathValues = new Array();
    for (var i = 0; i < path.getLength(); i++)
        pathValues.push(path.getAt(i).toUrlValue());

    console.log(pathValues.join("|"));
    xhr.open("GET", "https://roads.googleapis.com/v1/snapToRoads?interpolate=true&path=" + pathValues.join("|") + "&key=MY_API_KEY", false);
    xhr.send();
    for (var i = 0; i < JSON.parse(xhr.responseText).snappedPoints.length; i++)
        snappedCoords.push(new google.maps.LatLng(JSON.parse(xhr.responseText).snappedPoints[i].location.latitude, JSON.parse(xhr.responseText).snappedPoints[i].location.longitude));
    return snappedCoords;
}

("MY_API_KEY" is just there because I don't want anyone using my quotas, I have replaced it with my browser key.)


Solution

  • It works on the documentation which is https:, if I try to access the web service from jsfiddle on https using http: or http: using https, I get the error you report. It only works if you access the API via https: if your page is secure (running over https:), if your page is running over http: use http: to access the API.