gf_address_autocomplete.php

Gravity Forms Address Autocomplete

The provided file is a WordPress PHP snippet that integrates Google Places Autocomplete into a WordPress form. It enqueues the necessary Google Maps API script and sets up a JavaScript function to automatically fill in address fields as the user types, improving data accuracy and user experience.

<?php add_action( 'wp_enqueue_scripts', 'enqueue_autocomplete_script' ); function enqueue_autocomplete_script() { $api_key = 'YOUR_API_KEY_HERE'; wp_enqueue_script( 'google-maps-api', 'https://maps.googleapis.com/maps/api/js?key='.$api_key.'&libraries=places', array(), null, true ); } add_action( 'wp_footer', 'autocomplete_script', 20 ); function autocomplete_script() { $form_id = '24'; ?> <script> (function($) { $(document).bind('gform_post_render', function() { // Define the autocomplete variable var autocomplete; // Define the mapping for address components - you will need to manually modify this to match your form markup var componentForm = { street_number: 'input_<?php echo $form_id; ?>_1_1', route: 'input_<?php echo $form_id; ?>_1_2', locality: 'input_<?php echo $form_id; ?>_1_3', administrative_area_level_1: 'input_<?php echo $form_id; ?>_1_4', country: 'input_<?php echo $form_id; ?>_1_6', postal_code: 'input_<?php echo $form_id; ?>_1_5' }; // Initialize the autocomplete object autocomplete = new google.maps.places.Autocomplete( (document.getElementById('input_<?php echo $form_id; ?>_1_1')), {types: ['geocode']} ); // Add listener for place_changed event autocomplete.addListener('place_changed', fillInAddress); function fillInAddress() { // Get the place details from the autocomplete object var place = autocomplete.getPlace(); // Loop through each component in the address for (var component in componentForm) { document.getElementById(componentForm[component]).value = ''; document.getElementById(componentForm[component]).disabled = false; } // Get each component of the address and set the corresponding field value 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]['long_name']; document.getElementById(componentForm[addressType]).value = val; } } } }); })(jQuery); </script> <?php } ?>

Frequently Asked Questions

Google Places Autocomplete is a feature that auto-completes address fields in forms by suggesting possible addresses as users type.