📜  google place api online example - 任何代码示例

📅  最后修改于: 2022-03-11 15:00:19.084000             🧑  作者: Mango

代码示例2
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
    // for the country, get the country code (the "short name") also
    if (addressType == "country") {
      document.getElementById("country_code").value = place.address_components[i].short_name;
    }
  }
}

var placeSearch, autocomplete;
var componentForm = {
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement}     */
    (document.getElementById('autocomplete')), {
      
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  // Get Latitude and longitude
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    document.getElementById('lat').value = place.geometry.location.lat();
    document.getElementById('lng').value = place.geometry.location.lng();
    fillInAddress();
  });
}
google.maps.event.addDomListener(window, 'load', initAutocomplete);