Google 地图的道路 API 不支持 XHR

Google Maps' Roads API not working with XHR

我需要将多段线捕捉到道路上,我找到了 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

问题是,如果 Roads API 不允许跨源请求,我该如何使用它?

代码:

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" 就在那里,因为我不想让任何人使用我的配额,我已将其替换为我的浏览器密钥。)

它适用于 documentation,即 https:,如果我尝试使用 http:http:https 上的 jsfiddle 访问 Web 服务使用 https,我收到了您报告的错误。只有当您通过 https: 访问 API 如果您的页面是安全的(运行 超过 https:),如果您的页面是 运行 超过 [=12],它才有效=] 使用 http: 访问 API.