javascript - CORS 请求不适用于 Google Directions API

标签 javascript google-api cors google-directions-api

每次我尝试从路线 API 获取数据时,都会收到请求的资源上不存在“Access-Control-Allow-Origin” header 。我尝试对地理编码 API 执行相同的请求并且它有效。这是我正在使用的代码:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://maps.googleapis.com/maps/api/directions/json?origin='+encodeURIComponent(data.origin)+'&destination='+encodeURIComponent(data.destination)+'&key='+encodeURIComponent(data.key), true);
    xhr.send();

最佳答案

您无法使用ajax请求访问路线api,因为该api不支持CORS。但是,您可以使用该库来访问 Direction API 数据。

这里是一个取自Google Maps API Examples的例子:

<style>
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    #map {
        height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
</style>
<div id="map" style="position: relative; overflow: hidden;">
    <div style="height: 100%; width: 100%; position: absolute; top: 0px; left: 0px; background-color: rgb(229, 227, 223);"></div>
</div>
<script>
    function initMap() {
        var directionsService = new google.maps.DirectionsService;
        // Optionally create a map
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 7,
            center: {lat: 41.85, lng: -87.65}
        });
        directionsDisplay.setMap(map);

        directionsService.route({
                origin: 'oklahoma city, ok',
                destination: 'chicago, il',
                travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
                // Pass data to the map
                directionsDisplay.setDirections(response);

                // See the data in the console
                console.log(response);
            } else {
                window.alert('Directions request failed due to ' + status);
            }
        });
    }
</script>
<script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

关于javascript - CORS 请求不适用于 Google Directions API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024771/

相关文章:

javascript - 在网格元素内垂直居中文本

javascript - Google 脚本将 23.000 行的颜色转换为十六进制代码

具有自托管和身份验证的 SignalR 跨域连接

node.js - NodeJS Express 应用程序未调用 app.use

ajax - 在带有基本身份验证请求的 ajax cors 的情况下,浏览器身份验证弹出窗口不显示

javascript - 为什么 BigInt(largeNumber) 仍然不精确?

php - 成功为假时如何停止 jQuery .ajax() 执行?

JavaScript 运行一个又一个函数

iOS 谷歌地图方法 UIView 动画不起作用

javascript - 在 Google 日历中保持签名状态