javascriptgoogle-places-apidata-mapping

How can I name the HTML input ID differently than than the address_component for Google Places API?


This code works correctly by extracting the address components into separate form fields but my problem is that it is forcing me to name the HTML input ID the same as the address component. For example, with the .js code below I need:

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

How can I change the .js syntax so that it still retrieves "postal_code" and "locality" components but plops them into form fields I name:

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

Here is the (complete) javascript; my original post only had a snippet of this:

  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;
      }
    }
  } 

Solution

  • By the way, I think the "short name" "long name" entries are just to tell the Google Places API whether or not to abbreviate country names, etc.

    More like the API response includes a lot of fields, and you are using that data structure to choose which field to pick for each place component.

    Using a mapping from google's name to yours is the right answer. One alternative would be to change your selector from:

    document.getElementById(addressType).value = val;
    

    To:

    document.getElementById(
        new Map([
            ["postal_code", "zip_code"],
            ["locality", "city"],
        ]).get(addressType)
    ).value = val;