gpt4 book ai didi

javascript - CORS 请求不适用于 google directions API

转载 作者:行者123 更新时间:2023-11-30 11:42:44 26 4
gpt4 key购买 nike

每次我尝试从方向 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com