0

このコードは、住所コンポーネントを個別のフォーム フィールドに抽出することで正しく機能しますが、問題は、HTML 入力 ID に住所コンポーネントと同じ名前を付ける必要があることです。たとえば、以下の .js コードが必要です。

<html>
<input id="postal_code"> and
<input id="locality">
</html>

.js 構文を変更して、「postal_code」コンポーネントと「locality」コンポーネントを引き続き取得するが、名前を付けたフォーム フィールドにそれらを挿入するにはどうすればよいですか。

<html>
<input id="zip_code"></input> and
<input id="city"></input>
</html>

これが(完全な)JavaScriptです。私の元の投稿には、これのスニペットしかありませんでした:

  var placeSearch, autocomplete;
  var componentForm = {
    street_number: 'short_name',
    postal_code: 'long_name',
    locality: 'long_name',
    country: 'short_name',
   };
 var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(40.790908, -79.766323),
    new google.maps.LatLng(-28.246058, 22.318632));

 function initAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete(
  (document.getElementById('typeaddress')),
  {bounds: defaultBounds,
  types: ['address']});
  autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();
    for (var component in componentForm) {
      document.getElementById(component).value = '';
      document.getElementById(component).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]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  } 
4

2 に答える 2