CORS要求不适用于Google Directions API [英] CORS request is not working on google directions API

查看:104
本文介绍了CORS要求不适用于Google Directions API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次尝试从Directions API获取数据时,请求的资源上都没有 Access-Control-Allow-Origin标头。我尝试对地址解析API进行相同的请求,并且可以正常工作。这是我正在使用的代码:

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


推荐答案

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

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.

以下示例摘自 Google Maps 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要求不适用于Google Directions API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆