如何在Google地图自动填充建议中显示其他信息?

时间:2018-02-08 13:22:21

标签: google-maps google-maps-api-3 geocoding googleplacesautocomplete

我正在使用Google商家信息自动填充功能按名称选择城市。目前,它仅在建议下拉列表中显示城市名称及其所属的国家/地区。

我已检查并发现" address_components"在选择城市时填充的对象,具有州/省和地址的其他部分等其他属性。因此,很明显Google的API除了提供城市和国家/地区名称外,还提供了其他信息。

我想要实现的是,在建议下拉列表中显示其他几项数据。

有办法吗?

(我在屏幕截图上标明了我需要显示其他属性的内容)enter image description here

这是代码。

 <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete&query=locality" async defer></script>

 <script>
   var searchBox;
   function initAutocomplete() {

   var options = {types: ['(cities)']};

   var input = document.getElementById('placeAuto');
    searchBox = new google.maps.places.Autocomplete(input);
   searchBox.addListener('place_changed', fillInAddress);
   }

  function fillInAddress()
  {
      var place = searchBox.getPlace();
      console.log(place);
  }

  </script>

1 个答案:

答案 0 :(得分:3)

正如我已经评论过的那样,您可以使用自动填充和地方服务以及getPlacePredictions方法来实现这一点,但我不会推荐这种方法,因为它会产生大量的对API的请求(每个结果一个,每次用户在地址字段中键入内容时)。

以全屏模式查看该片段,因为它不适用于此处或在JSFiddle上查看。

在此示例中,我在自动填充结果中添加了地点纬度和经度。

var autocompleteService, placesService, results, map;

function initialize() {

  results = document.getElementById('results');

  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(50, 50)
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Bind listener for address search
  google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {

    results.style.display = 'block';
    getPlacePredictions(document.getElementById('address').value);
  });

  // Show results when address field is focused (if not empty)
  google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {

    if (document.getElementById('address').value !== '') {

      results.style.display = 'block';
      getPlacePredictions(document.getElementById('address').value);
    }
  });

  // Hide results when click occurs out of the results and inputs
  google.maps.event.addDomListener(document, 'click', function(e) {

    if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {

      results.style.display = 'none';
    }
  });

  autocompleteService = new google.maps.places.AutocompleteService();
  placesService = new google.maps.places.PlacesService(map);
}

// Get place predictions
function getPlacePredictions(search) {

  autocompleteService.getPlacePredictions({
    input: search,
    types: ['geocode']
  }, callback);
}

// Place search callback
function callback(predictions, status) {

  // Empty results container
  results.innerHTML = '';

  // Place service status error
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
    return;
  }

  // Build output for each prediction
  for (var i = 0, prediction; prediction = predictions[i]; i++) {

    // Get place details to inject more details in autocomplete results
    placesService.getDetails({
      placeId: prediction.place_id
    }, function(place, serviceStatus) {

      if (serviceStatus === google.maps.places.PlacesServiceStatus.OK) {

        // Create a new result element
        var div = document.createElement('div');

        // Insert inner HTML
        div.innerHTML += '<span class="pac-icon pac-icon-marker"></span>' + place.adr_address + '<div class="pac-item-details">Lat: ' + place.geometry.location.lat().toFixed(3) + ', Lng: ' + place.geometry.location.lng().toFixed(3) + '</div>';

        div.className = 'pac-item';

        // Bind a click event
        div.onclick = function() {

          var center = place.geometry.location;
          var marker = new google.maps.Marker({
            position: center,
            map: map
          });

          map.setCenter(center);
        }

        // Append new element to results
        results.appendChild(div);
      }
    });
  }
}

google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
  font-family: Arial, sans-serif;
  padding: 0;
  margin: 0;
  height: 100%;
}

#map-canvas {
  height: 150px;
  margin-bottom: 5px;
}

table {
  border-collapse: collapse;
  margin-left: 20px;
}

table td {
  padding: 3px 5px;
}

label {
  display: inline-block;
  width: 160px;
  font-size: 11px;
  color: #777;
}

input {
  border: 1px solid #ccc;
  width: 170px;
  padding: 3px 5px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}

.pac-container {
  background-color: #fff;
  z-index: 1000;
  border-radius: 2px;
  font-size: 11px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
  width: 350px;
}

.pac-icon {
  width: 15px;
  height: 20px;
  margin-right: 7px;
  margin-top: 6px;
  display: inline-block;
  vertical-align: top;
  background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
  background-size: 34px;
}

.pac-icon-marker {
  background-position: -1px -161px;
}

.pac-item {
  cursor: pointer;
  padding: 0 4px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 30px;
  vertical-align: middle;
  text-align: left;
  border-top: 1px solid #e6e6e6;
  color: #999;
}

.pac-item:hover {
  background-color: #efefef;
}

.pac-item-details {
  color: lightblue;
  padding-left: 22px;
}

.pac-item-error,
.pac-item-error:hover {
  color: #aaa;
  padding: 0 5px;
  cursor: default;
  background-color: #fff;
}
<div id="map-canvas"></div>
<table>
  <tr>
    <td>
      <label for="address">Address:</label>
    </td>
  </tr>
  <tr>
    <td>
      <input id="address" placeholder="Enter address" type="text" tabindex="1" />
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <div id="results" class="pac-container"></div>
    </td>
  </tr>
</table>


<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>