Google API Autocomplete
unknown
plain_text
3 years ago
1.1 kB
8
Indexable
const AutocompleteInput = () => {
const [address, setAddress] = useState<string>('');
const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);
const libraries = ['places'];
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: Api-Key,
libraries,
});
const handlePlaceChanged = useCallback(() => {
if (autocompleteRef.current) {
const place = autocompleteRef.current.getPlace();
setAddress(place.formatted_address || '');
}
}, []);
if (loadError) return <Alert severity="error">Error loading Google Maps libraries</Alert>;
if (!isLoaded) return <Alert severity="info">Loading Google Maps libraries</Alert>;
return (
<div>
<Autocomplete
ref={(autocomplete) => (autocompleteRef.current = autocomplete || null)}
onLoad={(autocomplete: google.maps.places.Autocomplete) => (autocompleteRef.current = autocomplete)}
onPlaceChanged={handlePlaceChanged}
>
<input type="text" placeholder="Enter address" />
</Autocomplete>
</div>
);
};
export default AutocompleteInput;Editor is loading...