首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Google自动完成地址

使用Google自动完成地址
EN

Stack Overflow用户
提问于 2018-04-10 16:24:09
回答 1查看 3.2K关注 0票数 2

我正在尝试使用Google API中的Places来获得完成部分英国地址的建议列表。这是一个到目前为止我的进度演示。调用的代码是:

代码语言:javascript
复制
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);

如果我提交了“洛瑟路”这样的部分地址,我会得到以下建议:

  • 英国伯恩茅斯洛瑟路
  • 英国丹斯特洛瑟路
  • 英国斯坦莫尔洛瑟路

我的问题是我想要一个匹配地址的列表,而不是地点。即使我把房号包括在内,例如通过提交部分地址“洛瑟路79号”,返回的建议仍然没有完整的地址,因为邮编丢失了。

  • 英国伯恩茅斯洛瑟路79号
  • 英国丹斯特洛瑟路79号
  • 英国斯坦莫尔洛瑟路79号

是否可以向Google提交部分地址,并获得匹配(完整)地址的列表?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-12 10:49:09

如果您对通过AutocompleteService得到的每个预测执行一个place请求,您就可以获得完整的地址。您应该创建一个google.maps.places.PlacesService实例,并对预测中的每个位置ID执行getDetails()

注意,get details异步工作,因此您应该使用承诺获取所有细节,并在<ul>列表中显示它们。

看看我根据您的代码创建的这个示例。

代码语言:javascript
复制
// 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);
}
代码语言:javascript
复制
/* 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;
}
代码语言:javascript
复制
<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>

您还可以在https://jsfiddle.net/xomena/z9tndphr/2/上查看此示例

我希望这能帮到你!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49758581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档