Jump to content

Google Places Autocomplete address form


Recommended Posts

Hi,

I'm not very familiar with JS. I need a way  to add places fast and with validated data into our database. So I came up with the idea to use Google Places Autocomplete for this.

Found this - https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform#maps_places_autocomplete_addressform-javascript

and with some modifications created a nice hmtl form that does the job fine. Next step was to make it work with the embedded Caspio form. As expected, just putting the code in HTML block / footer and referencing the right Caspio fields did not work. So I'm stuck, any ideas ? Here's code I use : 

<script>

let autocomplete;
let address1Field;
let address2Field;
let postalField;

function initAutocomplete() {
  address1Field = document.getElementById("InsertRecordCompanyName");
  address2Field = document.getElementById("InsertRecordAddress");
  postalField = document.getElementById("InsertRecordPostcode");
  // Create the autocomplete object, restricting the search predictions to
  // addresses in the US and Canada.
  autocomplete = new google.maps.places.Autocomplete(address1Field, {
    componentRestrictions: { country: ["de", "fr"] },
    fields: ["address_components", "name", "geometry"],
    types: ["establishment"],
  });
  address1Field.focus();
  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener("place_changed", fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  const place = autocomplete.getPlace();
  var latitude = place.geometry.location.lat();
  var longitude = place.geometry.location.lng();
  var faddress = place.name ;
  let address1 = "";
  let postcode = "";

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  // place.address_components are google.maps.GeocoderAddressComponent objects
  // which are documented at http://goo.gle/3l5i5Mr
  for (const component of place.address_components) {
    // @ts-ignore remove once typings fixed
    const componentType = component.types[0];

    switch (componentType) {
  case "street_number": {
        address1 = `${component.long_name} ${address1}`;
        break;
      }

      case "route": {
        address1 = `${component.short_name} ${address1}`;
        break;
      } 
        case "postal_code": {
        postcode = `${component.long_name}${postcode}`;
        break;
      }

      case "postal_code_suffix": {
        postcode = `${postcode}-${component.long_name}`;
        break;
      }
      case "locality":
        document.getElementById("InsertRecordCity").value = component.long_name;
        break;
      case "administrative_area_level_1": {
        document.getElementById("InsertRecordGPSLatitude").value = component.long_name;
        break;
      }
      case "country":
        document.getElementById("InsertRecordCountry").value = component.short_name;
        break;
    }
  }

  address1Field.value = address1;
  address2Field.value = faddress;
  postalField.value = postcode;
  // After filling the form with address components from the Autocomplete
  // prediction, set cursor focus on the second address line to encourage
  // entry of subpremise information such as apartment, unit, or floor number.
  address2Field.focus();
}

window.initAutocomplete = initAutocomplete;

</script>

 

Thanks in advance for any help.

 

Link to comment
Share on other sites

Hi again. So I'm not giving up that easy. After some further testing I found out this behaviour :

- if I load the Google Maps API in the HTML file, it does not work at all

- if I load the API in the header of the datapage, it actually works, BUT only AFTER I click on the submit button once and the datapage is reloaded ( destination is Same Form )

Here's a link to the datapage, it's for testing purposes - https://c0ach287.caspio.com/dp/dfe06000e3abc0f66e72412d8197

Maybe I have to add a listener of some kind ? AJAX loading is enabled, responsive also.

Link to comment
Share on other sites

  • 9 months later...
On 2/22/2023 at 12:37 PM, ta33ik said:

Hi again. So I'm not giving up that easy. After some further testing I found out this behaviour :

- if I load the Google Maps API in the HTML file, it does not work at all

- if I load the API in the header of the datapage, it actually works, BUT only AFTER I click on the submit button once and the datapage is reloaded ( destination is Same Form )

Here's a link to the datapage, it's for testing purposes - https://c0ach287.caspio.com/dp/dfe06000e3abc0f66e72412d8197

Maybe I have to add a listener of some kind ? AJAX loading is enabled, responsive also.

@ta33ik and @BCannon

 

I was able to get Google Places API to autocomplete my address and parse the address details into the necessary fields in a Submit Datapage. By adding this code into an HTML Block. The field Address_String is where the user begins to type the address and selects the autopopulated address. Be sure to insert your own API and actually deploy the datapage onto your website (and that your url is listed with the API). It won't work properly if you are just previewing the form on a caspio URL. Good luck!

 

<!-- Load Google Places API -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=InsertYourAPI&libraries=places"></script>


<!-- Set autocomplete input for 'InsertRecordAddress_String' -->
<script>
  document.addEventListener("DataPageReady", function() {
    var gpaInput = document.getElementById('InsertRecordAddress_String');
    var autocomplete = new google.maps.places.Autocomplete(gpaInput);

    // Listener for when a place is selected
    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();

      // Check if a place was actually selected
      if (place && place.geometry) {
        var addressComponents = place.address_components;

        var address = '';
        var city = '';
        var state = '';
        var zipCode = '';
        var country = '';
        var county = '';
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();

        // Extracting specific address components
        for (var i = 0; i < addressComponents.length; i++) {
          var component = addressComponents[i];
          if (component.types.includes('route') || component.types.includes('street_number')) {
            address += component.long_name + ' ';
          } else if (component.types.includes('locality')) {
            city = component.long_name;
          } else if (component.types.includes('administrative_area_level_1')) {
            state = component.short_name;
          } else if (component.types.includes('postal_code')) {
            zipCode = component.long_name;
          } else if (component.types.includes('country')) {
            country = component.long_name;
          } else if (component.types.includes('administrative_area_level_2')) {
            county = component.long_name;
          }
        }

        // Setting values in Caspio fields
        document.getElementById('InsertRecordAddress').value = address.trim();
        document.getElementById('InsertRecordCity').value = city;
        document.getElementById('InsertRecordState').value = state;
        document.getElementById('InsertRecordZip').value = zipCode;
        document.getElementById('InsertRecordCountry').value = country;
        document.getElementById('InsertRecordPhysical_County').value = county;
        document.getElementById('InsertRecordLat').value = latitude;
        document.getElementById('InsertRecordLong').value = longitude;

        // You might need to adapt this to fit your specific data structure and field IDs
      }
    });
  });
</script>

 

Link to comment
Share on other sites

  • 2 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...