CORS请求不工作的谷歌API的方向(CORS request is not working on

2019-09-28 08:18发布

每次我试图从方向API数据,我没有得到任何“访问控制允许来源”标头出现在所请求的资源。 我试着做了地址解析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();

Answer 1:

您不能访问的方向API使用Ajax请求,因为此API不支持CORS。 但是,你可以使用库访问的方向API数据。

从这里迈出了例如谷歌地图API的例子 :

<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>


文章来源: CORS request is not working on google directions API