CORS request is not working on google directions API

此生再无相见时 提交于 2019-12-24 06:37:56

问题


Every time I try to get data from the directions API, I get No 'Access-Control-Allow-Origin' header is present on the requested resource. I've tried to do the same request to the geocode API and it works. This is the code that I'm using:

    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();

回答1:


You cannot access to the directions api with ajax request because this api dont support CORS. But, you can use the library to access to the Direction API data.

Here a example taken from 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>


来源:https://stackoverflow.com/questions/42024771/cors-request-is-not-working-on-google-directions-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!