向多个Google自动填充广告位

时间:2017-02-02 01:04:38

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

我有一个包含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'
        };

并添加了两个名为this id(sublocality和sublocality2)的字段。虽然这些从未被填写过,即使地址中确实存在了一个sublocality ..

修改

这是第一次自动完成的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]" />

1 个答案:

答案 0 :(得分:1)

问题是现有代码只查看类型数组中的第一个类型。要找到sublocality,它需要处理整个数组:

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>