function bpFieldInitAddressGoogleElement(element) {

    //this script is async loaded so it does not prevent other scripts in page to load while this is fetched from outside url.
    //at somepoint our initialization script might run before the script is on page throwing undesired errors.
    //this makes sure that when this script is run, it has google available either on our field initialization or when the callback function is called.
    if(typeof google === "undefined") { return; }

    var $addressConfig = element.data('google-address');

    var $storeAsJson = element.data('store-as-json');
    var $field = $(element).parent().children('input[type=hidden]');

    if ($field.val() && $field.val().length) {
        try {
            var existingData = JSON.parse($field.val());
            element.val(existingData.value);
        } catch(error) {
            element.val($field.val());
        }
    }

    var $autocomplete = new google.maps.places.Autocomplete(
        (element[0]),
        {types: ['geocode']});

    $autocomplete.addListener('place_changed', function fillInAddress() {
        var place = $autocomplete.getPlace();
        var value = element.val();
        var latlng = place.geometry.location;
        var data = {"value": value, "latlng": latlng};

        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            data[addressType] = place.address_components[i]['long_name'];
        }

        if($storeAsJson) {
            $field.val(JSON.stringify(data));
        } else {
            $field.val(value);
        }
        $field.trigger('change');
    });

    $field.on('CrudField:disable', function() {
        element.attr('disabled', 'disabled');
    });

    $field.on('CrudField:enable', function() {
        element.removeAttr('disabled');
    });

    element.change(function(){
        if(!$storeAsJson) {
            $field.val(element.val());
        } else {
            if (!element.val().length) {
                $field.val("");
            }
        }
    });
    
    element.keydown(function(e) {
        if ($('.pac-container').is(':visible') && e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

    // Make sure pac container is closed on modals (inline create)
    let modal = document.querySelector('.modal-dialog');
    if(modal) modal.addEventListener('click', e => document.querySelector('.pac-container').style.display = "none");
}

//Function that will be called by Google Places Library
if (typeof initGoogleAddressAutocomplete === "undefined") {
    function initGoogleAddressAutocomplete() {
        $('[data-google-address]').each(function () {
            var element = $(this);
            var functionName = element.data('init-function');

            if (typeof window[functionName] === "function") {
            window[functionName](element);
            }
        });
    }
}

        