2017-02-03 11 views
1

Каждый раз, когда я пытаюсь получить данные из API-интерфейсов, я получаю заголовок «Access-Control-Allow-Origin» на запрашиваемом ресурсе. Я попытался сделать тот же запрос в API геокода, и он работает. Это код, который я использую:Запрос CORS не работает с указателями google 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(); 
+0

Это, по-видимому, не поддерживает кросс-XHR происхождения/Fetch запросов от JavaScript http://stackoverflow.com/questions/29834185/how-do-i-get -json-из-Google-направлений-апи-используя-JQuery – sideshowbarker

ответ

3

Вы не можете получить доступ к Directions API с запросом AJAX, потому что это апи не поддерживающие 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>