|
| 1 | +import React, {useEffect, useRef, useState} from 'react'; |
| 2 | +import {useAutocomplete, useGoogleMap} from '@ubilabs/google-maps-react-hooks'; |
| 3 | + |
| 4 | +import styles from './places-search.module.css'; |
| 5 | + |
| 6 | +const PlacesSearch = () => { |
| 7 | + const {map} = useGoogleMap(); |
| 8 | + |
| 9 | + // Use the input ref to pass an input field to the useAutocomplete hook below |
| 10 | + const inputRef = useRef<HTMLInputElement | null>(null); |
| 11 | + |
| 12 | + const [inputValue, setInputValue] = useState(''); |
| 13 | + const [selectedPlace, setSelectedPlace] = |
| 14 | + useState<google.maps.places.PlaceResult | null>(null); |
| 15 | + |
| 16 | + const [marker, setMarker] = useState<google.maps.Marker | null>(null); |
| 17 | + |
| 18 | + const onPlaceChanged = (place: google.maps.places.PlaceResult) => { |
| 19 | + if (place) { |
| 20 | + setSelectedPlace(place); |
| 21 | + setInputValue(place.formatted_address || place.name); |
| 22 | + |
| 23 | + // Keep focus on input element |
| 24 | + inputRef.current?.focus(); |
| 25 | + } |
| 26 | + }; |
| 27 | + |
| 28 | + // Use the useAutocomplete hook and pass the input field ref and the onPlaceChanged function to it |
| 29 | + useAutocomplete({ |
| 30 | + inputField: inputRef && inputRef.current, |
| 31 | + onPlaceChanged |
| 32 | + }); |
| 33 | + |
| 34 | + const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { |
| 35 | + setInputValue(event.target.value); |
| 36 | + }; |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + if (map && selectedPlace) { |
| 40 | + if (marker) { |
| 41 | + marker.setMap(null); |
| 42 | + } |
| 43 | + |
| 44 | + const markerOptions: google.maps.MarkerOptions = { |
| 45 | + map, |
| 46 | + position: selectedPlace?.geometry?.location, |
| 47 | + title: selectedPlace.name, |
| 48 | + clickable: false |
| 49 | + }; |
| 50 | + |
| 51 | + // Add a marker whenever a place was selected |
| 52 | + const newMarker = new google.maps.Marker(markerOptions); |
| 53 | + |
| 54 | + setMarker(newMarker); |
| 55 | + } |
| 56 | + }, [map, selectedPlace]); |
| 57 | + |
| 58 | + return ( |
| 59 | + <input |
| 60 | + className={styles.searchInput} |
| 61 | + ref={inputRef} |
| 62 | + value={inputValue} |
| 63 | + onChange={handleInputChange} |
| 64 | + /> |
| 65 | + ); |
| 66 | +}; |
| 67 | + |
| 68 | +export default PlacesSearch; |
0 commit comments