import _ from 'lodash'; import React, { useEffect, useRef, RefObject, FC, FocusEvent, useId } from 'react'; import ErrorMessage from './ErrorMessage'; import { classNames } from '@/utils'; import FormLabel from './FormLabel'; export type OnPlaceSelectedParamType = { city: string; state: string; zip: string; country: { long_name: string; short_name: string }; address: string; place: google.maps.places.PlaceResult; inputValue: string; }; export type GooglePlaceAutocompleteProps = { label?: React.ReactNode; input?: React.DetailedHTMLProps, HTMLInputElement>; className?: string; errors?: string[]; onPlaceSelected: (data: OnPlaceSelectedParamType) => void; countryRestriction?: string; value?: string; onClear?: () => void; onFocus?: (event?: FocusEvent) => void; onBlur?: () => void; apiKey: string; showClear: boolean; disabled?: boolean; }; let autoComplete: google.maps.places.Autocomplete; const loadScript = (url: string, callback: () => void) => { // Don't load Google API script in every component mounts if (window.google?.maps?.places) { callback(); return; } const scriptEl = document.createElement('script'); const initMapEl = document.createElement('script'); initMapEl.type = 'text/javascript'; initMapEl.textContent = 'function initMapPlaceholderFunc() {}'; scriptEl.type = 'text/javascript'; scriptEl.src = url; document.body.appendChild(initMapEl); document.body.appendChild(scriptEl); scriptEl.onload = () => callback(); // document.getElementsByTagName('head')[0].appendChild(initMapEl); // document.getElementsByTagName('head')[0].appendChild(scriptEl); }; const GooglePlaceAutocomplete: FC = ({ label, apiKey, input, className, errors, onPlaceSelected, countryRestriction, value, onClear, onFocus, onBlur, showClear = true, disabled, }) => { const generatedId = useId(); const autoCompleteRef = useRef(null); const handlePlaceSelect = () => { const place = autoComplete.getPlace(); const inputValue = autoCompleteRef.current!.value; if (place && place.name) { autoCompleteRef.current!.value = place.name; } else { autoCompleteRef.current!.value = inputValue; } // updateQuery(place.formatted_address); const address = _.get(place, 'address_components'); let city = ''; let state = ''; let zip = ''; let country = { long_name: '', short_name: '' }; _.forEach(address, function (component) { const types = _.get(component, 'types'); if (_.includes(types, 'country')) { country = component; } if (_.includes(types, 'locality')) { city = _.get(component, 'long_name'); } if (_.includes(types, 'administrative_area_level_1')) { state = _.get(component, 'long_name'); } if (_.includes(types, 'postal_code')) { zip = _.get(component, 'long_name'); } }); onPlaceSelected({ city: city ?? '', state: state ?? '', zip: zip ?? '', country: country ?? { long_name: '', short_name: '' }, address: autoCompleteRef.current?.value ?? '', place, inputValue, }); }; const handleScriptLoad = (autoCompleteRef: RefObject, countryRestriction?: string) => { const { maps } = window.google; autoComplete = new maps.places.Autocomplete(autoCompleteRef.current as HTMLInputElement); if (countryRestriction) { autoComplete.setComponentRestrictions({ country: countryRestriction, }); } autoComplete.addListener('place_changed', () => handlePlaceSelect()); }; useEffect(() => { if (autoCompleteRef.current && value) { autoCompleteRef.current.value = value; } }, [value]); useEffect(() => { const googleURL = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&language=en&callback=initMapPlaceholderFunc`; loadScript(googleURL, () => handleScriptLoad(autoCompleteRef, countryRestriction)); }, [countryRestriction]); const hasErrors = Boolean(errors && errors.length > 0); return ( <> {typeof label === 'string' ? ( {label} ) : ( label )}
{value && value.toString().length && showClear && (
)}
); }; export default GooglePlaceAutocomplete;