在自动完成中使用 Google 地图地点 API; API 不工作

Using Google Maps Places API in autocomplete; API not working

我正在尝试将 Google 地图地点 API 连接到搜索框。为了测试 jquery 自动完成,我用这个简单的例子让它工作:

function bindAutocomplete() {
    var locationSearch = $("input#Location");

    locationSearch.autocomplete({
        source: ["Massachusetts", "New Hampshire", "Boston"],
        minLength: 2
    });
}

虽然我正在尝试弄清楚如何使用 google 地图 API 的结果作为来源,但我不确定该怎么做。我可以在我的浏览器中从 API 获得结果:

https://maps.googleapis.com/maps/api/place/autocomplete/xml?types=(regions)&input=mas&key=xxx

这些是我尝试过的东西:

locationSearch.autocomplete({
    source: function (request, response) {
     $.getJSON("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&key=xxx&input=mass", {
            term: "mass"
        }, response),
    minLength: 2
});

但我收到 "Access Control Allow Origin" 安全错误。我试过这样 jsonp:

locationSearch.autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&key=xxx&input=mass",
            type: "GET",
            dataType: 'jsonp',
            cache: false,
            success: function (response) {
                console.log(response);
            }
        });
    },
    minLength: 2
});

但我在尝试记录响应时遇到错误,因为响应是 json 但它期望 jsonp。 (此外,即使这确实有效,我也不确定如何将 ajax 调用的输出设置为源)

我最后尝试的是:

locationSearch.autocomplete({
    source: new google.maps.places.Autocomplete("mass"),
    minLength: 2
});

在我的页面上使用这些脚本:

<script src='http://maps.googleapis.com/maps/api/js?libraries=places&key=xxx'></script>
<script>$(bindAutocomplete)</script>

但是当页面加载时我收到错误 "google is not defined" 以及一堆错误 "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience" 和 "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened"

当你想通过 JS 请求这些数据时,你必须使用 AutocompleteService of the Places-library

实施示例:

function bindAutocomplete() {

  var acService = new google.maps.places.AutocompleteService(),
    placesService = new google.maps.places.PlacesService(document.createElement('div'));

  $("input#location").autocomplete({
    source: function(req, resp) {

      acService.getPlacePredictions({
        input: req.term,
        types:['(regions)']
      }, function(places, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          var _places = [];
          for (var i = 0; i < places.length; ++i) {
            _places.push({
              id: places[i].place_id,
              value: places[i].description,
              label: places[i].description
            });
          }
          resp(_places);
        }
      });
    },
    select: function(e, o) {
      placesService.getDetails({
        placeId: o.item.id
      }, function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          alert(o.item.value +
            '\n is located at \n ' +
            place.geometry.location.toUrlValue());
        }
      });


    }
  });
}
$(window).load(bindAutocomplete);
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<input id="location" />

注意:此服务不支持类型过滤器

但是:places-library 还包括一个 Autocomplete