使用谷歌地图API自动完成地址输入

3

我正在尝试使用Google Maps JavaScript API中的Places库来获取完成英国地址的建议列表。这是我到目前为止的进展演示。调用Google Places API的代码如下:

var service = new google.maps.places.AutocompleteService();
var query = document.getElementById("address").value;
var restrictions = {country: 'uk'};
service.getPlacePredictions({ 
    input: query, 
    types: ['address'], 
    componentRestrictions: restrictions},  displaySuggestions);

如果我提交一个部分地址,例如“Lowther Road”,我会得到以下建议:
  • 英国伯恩茅斯的Lowther Road
  • 英国邓斯特布尔的Lowther Road
  • 英国斯坦莫的Lowther Road
我的问题是,我想要匹配的是地址列表,而不是地点。即使我包括房屋号码,例如通过提交部分地址“79 Lowther Road”,返回的建议仍然不是完整的地址,因为邮政编码缺失。
  • 英国伯恩茅斯的79 Lowther Road
  • 英国邓斯特布尔的79 Lowther Road
  • 英国斯坦莫的79 Lowther Road
是否可以向Google提交部分地址并获取匹配的(完整)地址列表?
1个回答

6
如果您使用AutocompleteService获得预测结果,执行每个预测结果的地点详情请求可获取完整地址。您需要创建一个google.maps.places.PlacesService实例,并为所有预测结果中包含的地点ID执行getDetails()方法。
请注意,getDetails方法是异步的,因此您应该使用Promises获取所有细节,并在<ul>列表中显示它们。
请参考我根据您的代码创建的示例。

// This example retrieves autocomplete predictions programmatically from the
// autocomplete service, and displays them as an HTML list.

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

function search() {
  var displaySuggestions = function(predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
      alert(status);
      return;
    }

  document.getElementById("results").innerHTML = '';
    
    var arrPr = []; 
    predictions.forEach(function (prediction) {
      arrPr.push(getPredictionDetails(prediction.place_id));
    });
    
    Promise.all(arrPr).then(function(results) {
     results.forEach(function(result) {
        //console.info('Result: ' + JSON.stringify(result, 4));
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(result.formatted_address));
          document.getElementById('results').appendChild(li);
        }); 
  }).catch(err => {
      console.log(err);
    });
  };
  
  function getPredictionDetails(placeId) {
   let promise = new Promise( (resolve, reject) => {
  placeService.getDetails({
          placeId: placeId
        }, function(result, status) {
          if (status === google.maps.places.PlacesServiceStatus.OK) {
              resolve(result);
            } else {
              reject(status);
            }
        });        
    });
    
    return promise;
  }

  var query = document.getElementById("address").value;
  var restrictions = {country: 'uk'};
  var service = new google.maps.places.AutocompleteService();
  var placeService = new google.maps.places.PlacesService(document.getElementById("results"));
  service.getPlacePredictions({ input: query, types: ['address'], componentRestrictions: restrictions },  displaySuggestions);
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#right-panel {
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select, #right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}
<div id="right-panel">

  <input id="address" placeholder="UK address" value="79 Lowther Road"/>
  <button type="button" onclick="search()">Submit</button>

  <p>Results:</p>
  <ul id="results"></ul>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places"
        async defer></script>

您还可以在此处查看示例。

希望这能帮助到您!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接