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