Test

Google Places Autocomplete Fix

Google Places Autocomplete Fix

For WooCommerce Checkout Page

Implementation Instructions

  1. Replace the existing dbdc_enqueue_autocomplete() function in your plugin with the code below
  2. Make sure your Google Maps API key is properly set in the plugin settings
  3. Test the functionality on your checkout page

Updated PHP Code:

/**
 * Enqueue Google Places Autocomplete on checkout page
 * Enhanced version with better error handling and UI
 */
function dbdc_enqueue_autocomplete() {
    if (is_checkout() && dbdc_is_woocommerce_active() && function_exists('WC')) {
        $api_key = '';
        
        // Try to get API key from shipping zones
        if (class_exists('WC_Shipping_Zones')) {
            $shipping_zones = WC_Shipping_Zones::get_zones();
            foreach ($shipping_zones as $zone) {
                foreach ($zone['shipping_methods'] as $method) {
                    if ($method->id === 'dbdc' && !empty($method->get_option('api_key'))) {
                        $api_key = $method->get_option('api_key');
                        break 2;
                    }
                }
            }
        }
        
        // If not found in zones, try global settings
        if (empty($api_key)) {
            $shipping_methods = WC()->shipping()->get_shipping_methods();
            if (isset($shipping_methods['dbdc']) && !empty($shipping_methods['dbdc']->get_option('api_key'))) {
                $api_key = $shipping_methods['dbdc']->get_option('api_key');
            }
        }
        
        if (!empty($api_key)) {
            // Enqueue Google Places API
            wp_enqueue_script(
                'dbdc-google-places',
                'https://maps.googleapis.com/maps/api/js?key=' . $api_key . '&libraries=places&callback=Function.prototype',
                array('jquery'),
                null,
                true
            );

            // Enqueue custom styles
            wp_enqueue_style(
                'dbdc-checkout-styles',
                plugin_dir_url(__FILE__) . 'assets/checkout-styles.css',
                array(),
                '1.3.0'
            );

            // Add inline script with proper error handling
            wp_add_inline_script('dbdc-google-places', '
                (function($) {
                    var dbdcInitialized = false;
                    
                    function initDBDCAutocomplete() {
                        if (dbdcInitialized) return;
                        
                        var shippingInput = document.getElementById("shipping_address_1");
                        
                        if (!shippingInput) {
                            console.log("DBDC: Shipping address input not found");
                            return;
                        }
                        
                        // Check if Google Maps API is loaded
                        if (typeof google === "undefined" || typeof google.maps === "undefined" || typeof google.maps.places === "undefined") {
                            console.error("DBDC: Google Maps API not loaded properly");
                            return;
                        }
                        
                        // Create a container for the address field with icon
                        var container = document.createElement("div");
                        container.className = "dbdc-address-container";
                        shippingInput.parentNode.insertBefore(container, shippingInput);
                        container.appendChild(shippingInput);
                        
                        // Add search icon
                        var icon = document.createElement("i");
                        icon.className = "dbdc-search-icon fas fa-search";
                        container.appendChild(icon);
                        
                        // Add validation notice
                        var notice = document.createElement("div");
                        notice.className = "dbdc-validation-notice";
                        notice.innerHTML = "' . __('Please select an address from the dropdown suggestions', 'dbdc') . '";
                        container.parentNode.insertBefore(notice, container.nextSibling);
                        
                        // Store original value for comparison
                        var originalValue = shippingInput.value;
                        
                        var autocomplete = new google.maps.places.Autocomplete(shippingInput, { 
                            types: ["geocode"],
                            componentRestrictions: {country: "' . (WC()->countries->get_base_country() ?: '') . '"},
                            fields: ["address_components", "formatted_address"]
                        });
                        
                        // Prevent entering custom text
                        shippingInput.addEventListener("keydown", function(e) {
                            // Allow only navigation and deletion keys
                            var allowedKeys = [8, 9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 92, 93];
                            if (allowedKeys.indexOf(e.keyCode) === -1 && !e.ctrlKey && !e.metaKey) {
                                e.preventDefault();
                            }
                        });
                        
                        // Handle place selection
                        autocomplete.addListener("place_changed", function() {
                            var place = autocomplete.getPlace();
                            
                            if (!place.address_components) {
                                // Invalid selection, revert to original value
                                shippingInput.value = originalValue;
                                notice.style.display = "block";
                                return;
                            }
                            
                            // Hide validation notice
                            notice.style.display = "none";
                            
                            // Fill other address fields
                            dbdcFillAddressFields(place, "shipping");
                            
                            // Update original value
                            originalValue = shippingInput.value;
                            
                            // Trigger update of checkout
                            $(document.body).trigger("update_checkout");
                        });
                        
                        // Validate on blur
                        shippingInput.addEventListener("blur", function() {
                            if (shippingInput.value !== originalValue) {
                                // Value was changed manually, revert
                                shippingInput.value = originalValue;
                                notice.style.display = "block";
                            }
                        });
                        
                        dbdcInitialized = true;
                        console.log("DBDC: Autocomplete initialized successfully");
                    }
                    
                    function dbdcFillAddressFields(place, prefix) {
                        var components = place.address_components;
                        var data = {
                            address_1: "",
                            address_2: "",
                            city: "",
                            state: "",
                            postcode: "",
                            country: ""
                        };
                        
                        // Parse address components
                        for (var i = 0; i < components.length; i++) {
                            var component = components[i];
                            var type = component.types[0];
                            
                            if (type === "street_number") {
                                data.address_1 = component.long_name + " ";
                            } else if (type === "route") {
                                data.address_1 += component.long_name;
                            } else if (type === "subpremise") {
                                data.address_2 = component.long_name;
                            } else if (type === "locality") {
                                data.city = component.long_name;
                            } else if (type === "administrative_area_level_1") {
                                data.state = component.short_name;
                            } else if (type === "postal_code") {
                                data.postcode = component.long_name;
                            } else if (type === "country") {
                                data.country = component.short_name;
                            }
                        }
                        
                        // Update form fields
                        for (var field in data) {
                            if (data[field]) {
                                var el = document.getElementById(prefix + "_" + field);
                                if (el) {
                                    el.value = data[field];
                                    $(el).trigger("change");
                                }
                            }
                        }
                    }
                    
                    $(document).ready(function() {
                        // Initialize after a short delay to ensure everything is loaded
                        setTimeout(function() {
                            initDBDCAutocomplete();
                        }, 500);
                        
                        // Also try initializing when checkout updates
                        $(document.body).on("updated_checkout", function() {
                            setTimeout(function() {
                                initDBDCAutocomplete();
                            }, 1000);
                        });
                    });
                })(jQuery);
            ');
        }
    }
}
add_action('wp_enqueue_scripts', 'dbdc_enqueue_autocomplete');

Test the Address Input

This simulates how the address field will work on your checkout page:

Please select an address from the dropdown suggestions.
Address successfully selected! Other fields will be auto-filled.
Add to cart

Notice: ob_end_flush(): Failed to send buffer of zlib output compression (1) in /home/streampi/public_html/pharmacy/wp-includes/functions.php on line 5471

Notice: ob_end_flush(): Failed to send buffer of zlib output compression (1) in /home/streampi/public_html/pharmacy/wp-includes/functions.php on line 5471