Google 自动完成搜索框的自定义地址

Custom Address for Google Autocomplete Search Box

我的网站上有一个自动完成功能(由 Google 自动完成的地方),它工作正常并且仅限于我的边界。但是当有人在搜索框中键入它时,有些位置会丢失,即使这些位置确实存在于实际的 Google 地图上。自动完成的 javascript 实现如下。

function initAutocomplete(){
      var areaboundary = new google.maps.LatLngBounds(
          new google.maps.LatLng(51.377809, -3.508688),
          new google.maps.LatLng(51.628119, -2.954925)
      );


  var options = {
    bounds: areaboundary,
    strictBounds: true,
    types: ['geocode'],
    componentRestrictions: {country: 'uk'}
  };
  var input = document.getElementById('property-location');
  autocomplete = new google.maps.places.Autocomplete(input, options);



  autocomplete.addListener('place_changed', function(){
    var place = autocomplete.getPlace();

    if(place.length === 0){
      return;
    }

    if(place.formatted_address == "Cardiff, UK"){
      jQuery("#property-radius-sale option[value=5]").prop("selected", true);
      jQuery("#property-radius-rent option[value=5]").prop("selected", true);
    }

    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    var coordinates = [lat, lng];

    var hidden_input = document.getElementById("lat-lng-location");
    hidden_input.value = coordinates;
  });
}

我要添加的位置是这个:

Location to be added

我需要这个特定地址的原因是网站上出现的地址也包括卡迪夫湾。

我的问题是,如何将带有 lng 和 lat 的自定义 address/location 添加到地点自动完成?

您遇到的 Cardiff Bay, UK 的具体问题是由 types 参数引起的。该地点被视为 自然特征 ,如果您指定 geocode 类型,则 API 不会返回该地点。

如果您不指定类型,或使用 types: ['geocode', 'establishment']according to the docs 等同于不指定类型,它将被列出。

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      componentRestrictions: {
        country: 'uk'
      }
    });

  ac.addListener('place_changed', function() {

    var place = ac.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    var html = '<div>Latitude: ' + place.geometry.location.lat() + '</div>';
    html += '<div>Longitude: ' + place.geometry.location.lng() + '</div>';

    document.getElementById('geometry').innerHTML = html;
  });
}
body,
html {
  padding: 10px;
}

#autocomplete {
  width: 400px;
}

#geometry {
  margin-top: 10px;
  background: lightblue;
  padding: 10px 20px;
}
<input id="autocomplete" value="Cardiff Bay" type="text">
<div id="geometry">

</div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initialize">
</script>