Я использую Google API для автозаполнения адреса в моей HTML-форме. Мне удалось заставить его работать, однако, когда я пытаюсь передать автоматически заполненный адрес в разные поля, такие как номер улицы, улица ...

-2
Hubert Jeffrey 14 Янв 2021 в 09:11

1 ответ

Лучший ответ

Пример в документации зависит от идентификаторов элементы такие же, как и в данных ответа.

Самое простое решение - вернуть объект componentForm к тому, что было в примере:

const componentForm = {
  street_number: "short_name",
  route: "long_name",
  locality: "long_name",
  administrative_area_level_1: "short_name",
  country: "long_name",
  postal_code: "short_name",
};

И измените идентификаторы ваших элементов, чтобы они соответствовали:

  <TR>
    <TD>
      <SPAN ID=_Datalead_enteryouraddress class=VIEWBOX>
        <input type="text" CLASS=EDIT ID="autocomplete" name="lead_enteryouraddress" value="" maxlength=40 placeholder='Enter your address:*' onFocus="geolocate()" required>
        <input type="hidden" name="_HIDDENlead_enteryouraddress" id="_HIDDENlead_enteryouraddress" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID=_Datalead_companyaddress1 class=VIEWBOX>
        <input type="text" CLASS=EDIT ID="street_number" disabled="true" name="street_number" value="" maxlength=40 placeholder='Street Number:*' required>
        <input type="hidden" name="_HIDDENlead_companyaddress1" id="_HIDDENlead_companyaddress1" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID=_Datalead_companyaddress2 class=VIEWBOX>
        <input type="text" CLASS=EDIT ID="route" disabled="true" name="route" value="" maxlength=40 placeholder='Street Name:*' required>
        <input type="hidden" name="_HIDDENlead_companyaddress2" id="_HIDDENlead_companyaddress2" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID=_Datalead_companycity class=VIEWBOX>
        <input type="text" CLASS="jointodesc" disabled="true" ID="locality" name="locality" value="" maxlength=30 placeholder='Suburb:*' required>
        <input type="hidden" name="_HIDDENlead_companycity" id="_HIDDENlead_companycity" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID=_Datalead_companystate class=VIEWBOX>
        <input type="text" CLASS="EDIT" disabled="true" ID="administrative_area_level_1" name="administrative_area_level_1" value="" maxlength=30 placeholder='State:*' required>
        <input type="hidden" name="_HIDDENlead_companystate" id="_HIDDENlead_companystate" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID=_Datalead_companypostcode class=VIEWBOX>
        <input type="text" CLASS=EDIT ID="postal_code" disabled="true" name="country" value="" maxlength=10 placeholder='Post Code:*' required>
        <input type="hidden" name="_HIDDENlead_companypostcode" id="_HIDDENlead_companypostcode" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>
  <TR>
    <TD>
      <SPAN ID="_Datalead_companycountry" class=VIEWBOX>
        <input type="text" CLASS=EDIT ID="country" disabled="true" name="country" value="" maxlength=10 placeholder='Country:*' required>
        <input type="hidden" name="_HIDDENlead_companycountry" id="_HIDDENlead_companycountry" value="" entryType="10">
      </SPAN>
    </TD>
  </TR>

доказательство концепции скрипки

screen shot of result

фрагмент кода:

var placeSearch, autocomplete;
const componentForm = {
  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', 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;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
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());
    });
  }
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#description {
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
}

#infowindow-content .title {
  font-weight: bold;
}

#infowindow-content {
  display: none;
}

#map #infowindow-content {
  display: inline;
}

.pac-card {
  margin: 10px 10px 0 0;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  background-color: #fff;
  font-family: Roboto;
}

#pac-container {
  padding-bottom: 12px;
  margin-right: 12px;
}

.pac-controls {
  display: inline-block;
  padding: 5px 11px;
}

.pac-controls label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}

#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

#pac-input:focus {
  border-color: #4d90fe;
}

#title {
  color: #fff;
  background-color: #4d90fe;
  font-size: 25px;
  font-weight: 500;
  padding: 6px 12px;
}

#target {
  width: 345px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Places Search Box</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocomplete&libraries=places&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <table>
    <TR>
      <TD>
        <SPAN ID=_Datalead_enteryouraddress class=VIEWBOX>
            <input type="text" CLASS=EDIT ID="autocomplete" name="lead_enteryouraddress" value="" maxlength=40 placeholder='Enter your address:*' onFocus="geolocate()" required>
            <input type="hidden" name="_HIDDENlead_enteryouraddress" id="_HIDDENlead_enteryouraddress" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID=_Datalead_companyaddress1 class=VIEWBOX>
            <input type="text" CLASS=EDIT ID="street_number" disabled="true" name="street_number" value="" maxlength=40 placeholder='Street Number:*' required>
            <input type="hidden" name="_HIDDENlead_companyaddress1" id="_HIDDENlead_companyaddress1" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID=_Datalead_companyaddress2 class=VIEWBOX>
            <input type="text" CLASS=EDIT ID="route" disabled="true" name="route" value="" maxlength=40 placeholder='Street Name:*' required>
            <input type="hidden" name="_HIDDENlead_companyaddress2" id="_HIDDENlead_companyaddress2" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID=_Datalead_companycity class=VIEWBOX>
            <input type="text" CLASS="jointodesc" disabled="true" ID="locality" name="locality" value="" maxlength=30 placeholder='Suburb:*' required>
            <input type="hidden" name="_HIDDENlead_companycity" id="_HIDDENlead_companycity" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID=_Datalead_companystate class=VIEWBOX>
            <input type="text" CLASS="EDIT" disabled="true" ID="administrative_area_level_1" name="administrative_area_level_1" value="" maxlength=30 placeholder='State:*' required>
            <input type="hidden" name="_HIDDENlead_companystate" id="_HIDDENlead_companystate" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID=_Datalead_companypostcode class=VIEWBOX>
            <input type="text" CLASS=EDIT ID="postal_code" disabled="true" name="country" value="" maxlength=10 placeholder='Post Code:*' required>
            <input type="hidden" name="_HIDDENlead_companypostcode" id="_HIDDENlead_companypostcode" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>
    <TR>
      <TD>
        <SPAN ID="_Datalead_companycountry" class=VIEWBOX>
            <input type="text" CLASS=EDIT ID="country" disabled="true" name="country" value="" maxlength=10 placeholder='Country:*' required>
            <input type="hidden" name="_HIDDENlead_companycountry" id="_HIDDENlead_companycountry" value="" entryType="10">
          </SPAN>
      </TD>
    </TR>

  </table>
</body>

</html>
0
geocodezip 15 Янв 2021 в 02:32