CORS 和 Google Maps Places Autocomplete API 调用 [英] CORS and Google Maps Places Autocomplete API calls
问题描述
我正在尝试与 Google Maps Places Autocomplete 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?
推荐答案
从 Web 应用程序调用 Place Autocomplete API 的支持方式是 使用 Places 库:
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 Autocomplete API 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!