javascript - 向多个 Google 自动完成位置添加额外组件

标签 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'
        };

并添加了 2 个字段,称为该 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>

关于javascript - 向多个 Google 自动完成位置添加额外组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992656/

相关文章:

javascript - JS 和 Prototype : mouseover influencing overlying element, 为什么?

javascript - 基本 JavaScript : How can I link my HTML and Javascript on a Highcharts example?

jquery - Google map 多边形渲染不正确

ios - 无法集成 Google Places API

javascript - setTimeout 函数缺少形式参数

javascript - JQuery移动 ListView 过滤器初始化

javascript - 如何使用 photoshop 脚本修改混合选项?

google-maps - 如何以像素为单位偏移 Google map (API v3)的中心?

javascript - Google map - 更改图 block 叠加层的 Pane 顺序?

google-maps - Google 放置的 API 与 Bing 的 API 类似吗?