【问题标题】:CORS and Google Maps Places Autocomplete API calls [duplicate]CORS 和 Google Maps Places Autocomplete API 调用 [重复]
【发布时间】:2017-09-12 14:52:51
【问题描述】:

我正在尝试让 Angular 与 Google Maps Places Autocomplete API 进行对话。问题是服务器不允许 CORS 调用(它不返回 Access-Control-Allow-Origin 标头),而且 JSONP 调用似乎也是徒劳的,因为它返回纯 JSON 而不是 JSONP,导致语法错误。

这是我目前在服务功能中尝试的(_jsonpJsonp 对象):

return this._jsonp.request(url, { method: 'GET' });

这不起作用。响应到达,但 Angular 崩溃了,因为它不是 JSONP 而是 JSON。

这太疯狂了。如果 CORS 被禁用并且 JSONP 调用不起作用,我到底该如何访问它?

https://maps.googleapis.com/maps/api/place/autocomplete/json?key=ACCESS_KEY&types=(cities)&input=ber

有没有办法将 JSON 服务器响应转换为 Observable 管道中的 JSONP 数据对象?

【问题讨论】:

    标签: javascript angular google-maps-api-3 cors


    【解决方案1】:

    支持从网络应用调用地点自动完成 API 的方式是 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 标头并不重要。

    以这种方式使用 Maps JavaScript API(通过script 元素加载库,然后使用google.maps.Map 和其他google.maps.* 方法)是唯一受支持的方式。 Google 故意不允许通过使用 XHR 或 Fetch API 发送的请求来执行此操作。

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2017-01-23
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2021-03-01
      • 2020-05-11
      相关资源
      最近更新 更多