All files / app/address/googleAutocomplete GoogleAutocompleteScriptLoader.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5726x       26x         4x     26x 5x 3x     2x 2x 2x             2x 2x 2x     2x     2x             2x   26x     2x   2x                
import { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';
 
import { GoogleAutocompleteWindow, GoogleMapsSdk } from './googleAutocompleteTypes';
 
export default class GoogleAutocompleteScriptLoader {
    private _scriptLoader: ScriptLoader;
    private _googleAutoComplete?: Promise<GoogleMapsSdk>;
 
    constructor() {
        this._scriptLoader = getScriptLoader();
    }
 
    loadMapsSdk(apiKey: string): Promise<GoogleMapsSdk> {
        if (this._googleAutoComplete) {
            return this._googleAutoComplete;
        }
 
        this._googleAutoComplete = new Promise((resolve, reject) => {
            const callbackName = 'initAutoComplete';
            const params = [
                'language=en',
                `key=${apiKey}`,
                'libraries=places',
                `callback=${callbackName}`,
            ].join('&');
 
            (window as GoogleCallbackWindow)[callbackName] = () => {
                Eif (isAutocompleteWindow(window)) {
                    resolve(window.google.maps);
                }
 
                reject();
            };
 
            this._scriptLoader.loadScript(`//maps.googleapis.com/maps/api/js?${params}`)
                .catch(e => {
                    this._googleAutoComplete = undefined;
                    throw e;
                });
        });
 
        return this._googleAutoComplete;
    }
}
 
function isAutocompleteWindow(window: Window): window is GoogleAutocompleteWindow {
    const autocompleteWindow = window as GoogleAutocompleteWindow;
 
    return Boolean(autocompleteWindow.google &&
        autocompleteWindow.google.maps &&
        autocompleteWindow.google.maps.places);
}
 
export interface GoogleCallbackWindow extends Window {
    initAutoComplete?(): void;
}