我有一个带有2种表单的页面,其中包含我在互联网上挖过的带有适当Javascript的地址自动完成功能

这是代码:

var placeSearch, autocomplete, autocomplete2;
        var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name',
            latitude: 'long_name',
            longitude: 'short_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')), {
                        types: ['geocode']
                    });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function () {
                fillInAddress(autocomplete, "");
            });

            autocomplete2 = new google.maps.places.Autocomplete(
                    /** @type {!HTMLInputElement} */
                    (document.getElementById('autocomplete2')), {
                        types: ['geocode']
                    });
            autocomplete2.addListener('place_changed', function () {
                fillInAddress(autocomplete2, "2");
            });

        }

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

            for (var component in componentForm) {
                if (!!document.getElementById(component + unique)) {
                    document.getElementById(component + unique).value = '';
                    document.getElementById(component + unique).disabled = false;
                }
            }

            // 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] && document.getElementById(addressType + unique)) {
                    var val = place.address_components[i][componentForm[addressType]];
                    document.getElementById(addressType + unique).value = val;
                }
            }
            document.getElementById('latitude' + unique).value = place.geometry.location.lat();
            document.getElementById('longitude' + unique).value = place.geometry.location.lng();
        }

        google.maps.event.addDomListener(window, "load", initAutocomplete);


选择地址后,它可以很好地填充所有字段。虽然我缺少一种叫做sublocality的地方

然后,我将其添加到componentForm数组中:

var componentForm = {
            sublocality: 'long_name',
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name',
            latitude: 'long_name',
            longitude: 'short_name'
        };


并添加了两个称为此非常ID的字段(sublocality和sublocality2)。尽管这些地址从未填写过,即使地址中确实存在子地区。

编辑

这是第一个自动完成的HTML。

<div class="form-group">
      <label>Adresse</label>
      <input id="autocomplete" class="form-control" placeholder="Votre adresse..." type="text" name="professionnel[addressfull]" />
 </div>

          <div id="adressmoredetails1">
            <input id="street_number" class="form-control" placeholder="Numéro" type="text" name="professionnel[addressnumber]" />
            <input id="route" class="form-control" placeholder="Rue" type="text" name="professionnel[addressstreet]" />
            <input id="sublocality" class="form-control" placeholder="Complément destinataire: résidence, lieu dit, ..." type="text" name="professionnel[complementname]" />
            <input id="postal_code" class="form-control" placeholder="Code Postal" type="text" name="professionnel[addresspostalcode]" />
            <input id="locality" class="form-control" placeholder="Ville" type="text" name="professionnel[addresscity]" />
            <input id="country" class="form-control" placeholder="Pays" type="text" name="professionnel[addresscountry]" />

            <input id="latitude" class="form-control" type="hidden" name="professionnel[addresslat]" />
            <input id="longitude" class="form-control" type="hidden" name="professionnel[addresslong]" />
          </div>


尝试代码段



var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  sublocality: 'long_name',
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_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')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

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

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // 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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="autocomplete" class="form-control" placeholder="Votre adresse..." type="text" name="professionnel[addressfull]" />
<input id="street_number" class="form-control" placeholder="Numéro" type="text" name="professionnel[addressnumber]" />
            <input id="route" class="form-control" placeholder="Rue" type="text" name="professionnel[addressstreet]" />
            <input id="sublocality" class="form-control" placeholder="Complément destinataire: résidence, lieu dit, ..." type="text" name="professionnel[complementname]" />
            <input id="postal_code" class="form-control" placeholder="Code Postal" type="text" name="professionnel[addresspostalcode]" />
            <input id="locality" class="form-control" placeholder="Ville" type="text" name="professionnel[addresscity]" />
            <input id="country" class="form-control" placeholder="Pays" type="text" name="professionnel[addresscountry]" />

最佳答案

问题在于,现有代码仅查看类型数组中的第一个类型。要找到子位置,它需要处理整个数组:

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

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // 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 addressTypes = place.address_components[i].types;
    // process the complete array of types
    for (var j = 0; j < addressTypes.length; j++) {
      var addressType = addressTypes[j];
      if (componentForm[addressType] && document.getElementById(addressType + unique)) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType + unique).value = val;
      }
    }
  }
  document.getElementById('latitude' + unique).value = place.geometry.location.lat();
  document.getElementById('longitude' + unique).value = place.geometry.location.lng();
}


proof of concept fiddle

代码段:



var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  sublocality: 'short_name',
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name',
  latitude: 'long_name',
  longitude: 'short_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')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

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

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // 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 addressTypes = place.address_components[i].types;
    for (var j = 0; j < addressTypes.length; j++) {
      var addressType = addressTypes[j];
      if (componentForm[addressType] && document.getElementById(addressType + unique)) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType + unique).value = val;
      }
    }
  }
  document.getElementById('latitude' + unique).value = place.geometry.location.lat();
  document.getElementById('longitude' + unique).value = place.geometry.location.lng();
}

google.maps.event.addDomListener(window, "load", initAutocomplete);

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="autocomplete" />
<input id="autocomplete2" />

<div id="addressone">
  <label>number</label>
  <input type="text" id="street_number" name="street_number" />
  <br>
  <label>street</label>
  <input type="text" id="route" name="street_name" />
  <br>
  <label>town</label>
  <input type="text" id="locality" name="town_city" />
  <br>
  <label>sublocality</label>
  <input type="text" id="sublocality" name="sublocatlity" />
  <br>
  <label>adm1</label>
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <br>
  <label>postcode</label>
  <input type="text" id="postal_code" name="postcode" />
  <br>
  <label>country</label>
  <input type="text" id="country" name="country" />
  <br>
  <label>lat</label>
  <input type="text" id="latitude" />
  <label>lng</label>
  <input type="text" id="longitude" />
  <br>
</div>
<br>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="sublocality2" name="sublocatlity2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
  <input type="text" id="latitude2" />
  <input type="text" id="longitude2" />
</div>
<div id="map_canvas"></div>

10-06 00:02