Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIO-8575: Added ability to reload google maps library with correct API key #5683

Merged
merged 2 commits into from
Jul 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/providers/address/GoogleAddressProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
import { Formio } from '../../Formio';
import _ from 'lodash';
import { AddressProvider } from './AddressProvider';

const GOOGLE_MAPS_BASE_URL = 'https://maps.googleapis.com';
const GOOGLE_MAPS_JS_URL = `${GOOGLE_MAPS_BASE_URL}/maps/api/js`;
const GOOGLE_MAPS_JS_WITH_PARAMS_URL = `${GOOGLE_MAPS_JS_URL}?v=quarterly&libraries=places&loading=async&callback=googleMapsCallback`;

/**
* @typedef {object} AutocompleteOptions
* @property {string[]} fields - The fields to include in the autocomplete response.
Expand Down Expand Up @@ -58,10 +63,11 @@ export class GoogleAddressProvider extends AddressProvider {
constructor(options = {}) {
super(options);
this.setAutocompleteOptions();
let src = 'https://maps.googleapis.com/maps/api/js?v=quarterly&libraries=places&loading=async&callback=googleMapsCallback';
let src = GOOGLE_MAPS_JS_WITH_PARAMS_URL;
if (options.params?.key) {
src += `&key=${options.params.key}`;
}
this.tryRemoveLibrary(options);
Formio.requireLibrary(this.getLibraryName(), 'google.maps.places', src);
}

Expand Down Expand Up @@ -221,4 +227,23 @@ export class GoogleAddressProvider extends AddressProvider {

return _.get(address, displayedProperty, '');
}

/**
* Tries to remove the library if api key for loaded script is different.
* @param {ProviderOptions} options - The options for the provider.
*/
tryRemoveLibrary(options = {}) {
if (!Formio.libraries[this.getLibraryName()]) {
return;
}

const existingScript = document.querySelector(`script[src^="${GOOGLE_MAPS_JS_URL}"]`);
if (existingScript && options.params?.key && !existingScript.attributes.src.value.endsWith(options.params.key)) {
const googleMapsScripts = document.querySelectorAll(`script[src^="${GOOGLE_MAPS_BASE_URL}"]`) ?? [];
googleMapsScripts.forEach(script => script.parentNode.removeChild(script));
delete Formio.libraries[this.getLibraryName()];
delete global?.google?.maps;
delete global[`${this.getLibraryName()}Callback`];
}
}
}
Loading