CORS和Google Maps Places自动完成API调用 [英] CORS and Google Maps Places Autocomplete API calls
问题描述
我正在尝试与Google Maps Places自动完成API进行Angular讨论.问题在于服务器不允许CORS调用(它不返回Access-Control-Allow-Origin
标头),并且JSONP调用也似乎是徒劳的,因为它返回纯JSON而不是JSONP,从而导致语法错误.
I am trying to get Angular talk to Google Maps Places Autocomplete API. The problem is that the server doesn't allow CORS calls (it doesn't return an Access-Control-Allow-Origin
header) and JSONP calls also seem to be futile as it returns plain JSON and not JSONP, causing a syntax error.
这是我目前正在服务功能中尝试的内容(_jsonp
是Jsonp
对象):
This is what I am currently trying in a service function (_jsonp
is a Jsonp
object):
return this._jsonp.request(url, { method: 'GET' });
这不起作用.响应到达,但是Angular崩溃,因为它不是JSONP而是JSON.
And this doesn't work. The response arrives, but Angular crashes because it's not JSONP but JSON.
这太疯狂了.如果禁用了CORS并且JSONP调用不起作用,我该如何访问呢?
This is crazy. How on earth can I access this if CORS is disabled and JSONP calls don't work?
https://maps.googleapis.com/maps/api/place/autocomplete/json?key=ACCESS_KEY&types=(cities)&input=ber
是否可以通过Observable管道将JSON服务器响应转换为JSONP数据对象?
Is there a way to convert a JSON server response into a JSONP data object in the Observable pipeline?
推荐答案
从网络应用程序调用Place Autocomplete API的受支持方法是
The supported way to call the Place Autocomplete API from a web app is using the Places library:
<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>
这样,响应中就没有Access-Control-Allow-Origin
标头就没关系了.
That way it doesn’t matter that the responses lack the Access-Control-Allow-Origin
header.
以这种方式使用Maps JavaScript API(通过script
元素加载库,然后使用google.maps.Map
和其他google.maps.*
方法)是唯一受支持的方法. Google故意不允许通过XHR或Fetch API发送的请求来执行此操作.
Using the Maps JavaScript API that way—by way of a script
element to load the library, and then using the google.maps.Map
and other google.maps.*
methods—is the only supported way. Google intentionally does not allow doing it by way of requests sent with XHR or the Fetch API.
这篇关于CORS和Google Maps Places自动完成API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!