1

この質問は複数の人から聞いたことがありますが、答えはどれも私のために働いていません。Google Maps API:要求されたリソースに「Access-Control-Allow-Origin」ヘッダーがありません

私はreact/axiosでgoogle maps apiにAPI呼び出しをしようとしています。私は皆のポイントへ https://www.html5rocks.com/en/tutorials/cors/

が、記事のコンCORSを読んだ

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/js? 
key=xxxxxxxxx/. Response to preflight request doesn't pass access control 
check: No 'Access-Control-Allow-Origin' header is present on the 
requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

componentDidMount() { 
    axios({ 
    method : 'get', 
    url : `http://maps.googleapis.com/maps/api/js?key=${key}/`, 
    headers: { 
    "Access-Control-Allow-Origin": '*' 
    "Access-Control-Allow-Methods": 'GET', 
    }, 
    }) 
.then(function (response) { 
    console.log(response); 
}) 
.catch(function (error) { 
    console.log(error); 
}); 
} 

これはエラーMSGがある:

は、これは私のGETリクエストであります私はそこに私の問題に対する答えを見つけることができません。

答えて

5

https://maps.googleapis.com/maps/apiは、コードが使用しようとしている方法でWebアプリケーションで実行されているフロントエンドJavaScriptからのリクエストを取得することはサポートしていません。

代わりに、サポートされているGoogle Maps JavaScript APIを使用する必要があります。クライアント側のコードは、お試しのものとは異なります。 sample for the Distance Matrix serviceはより次のようになります。ロードするためにそのバイscript要素の方法のように地図のJavaScript APIを使用して

<script> 
    function initMap() { 
    var map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: -33.8688, lng: 151.2195}, 
     zoom: 13 
    }); 
    ... 
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card); 
    var autocomplete = new google.maps.places.Autocomplete(input); 
    autocomplete.bindTo('bounds', map); 
    var infowindow = new google.maps.InfoWindow(); 
    var infowindowContent = document.getElementById('infowindow-content'); 
    infowindow.setContent(infowindowContent); 
    var marker = new google.maps.Marker({ 
     map: map, 
     anchorPoint: new google.maps.Point(0, -29) 
    }); 
</script> 
<script 
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" 
    async defer></script> 

<script> 
    var service = new google.maps.DistanceMatrixService; 
    service.getDistanceMatrix({ 
    origins: [origin1, origin2], 
    destinations: [destinationA, destinationB], 
    travelMode: 'DRIVING', 
    unitSystem: google.maps.UnitSystem.METRIC, 
    avoidHighways: false, 
    avoidTolls: false 
},… 
</script> 

<script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> 
</script> 

そしてここでは、プレイスオートコンプリートAPI using the Places libraryを使用するための例ですライブラリを使用し、次にgoogle.maps.Mapと他のgoogle.maps.*のメソッドを使用する方法は、ブラウザを実行するフロントエンドJavaScriptコードからGoogle Maps APIへのリクエストを行う唯一の方法です。

Googleは意図的に、AxiosやAJAXメソッドを他のそのようなライブラリで送信したり、XHRやFetch APIで直接リクエストしたりすることによって、Google Maps APIへのアクセスを許可していません。

関連する問題