使用Google Maps API自动填充地址

时间:2018-04-10 16:24:10

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

我尝试使用Google Maps JavaScript API中的Places库来获取完成部分英国地址的建议列表。这是demo of my progress to date。调用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,Dunstable,UK
  • Lowther Road,Stanmore,UK

我的问题是我需要一个匹配地址的列表,而不是地方。即使我包括门牌号码,例如通过提交部分地址" 79 Lowther Road",返回的建议仍然不是完整的地址,因为缺少邮政编码

  • 英国伯恩茅斯,Lowther Road 79号
  • 79 Lowther Road,Dunstable,UK
  • 79 Lowther Road,Stanmore,UK

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

1 个答案:

答案 0 :(得分:2)

如果您对通过AutocompleteService获得的每个预测执行地点详细信息请求,则可以获取完整地址。您应该为预测中的每个地点ID创建google.maps.places.PlacesService的实例并执行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>

您还可以在https://jsfiddle.net/xomena/z9tndphr/2/

查看此示例

我希望这有帮助!