Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type P = {
- label: string
- setPlace: (place: Place) => void
- }
- const GooglePlacesAutocomplete = ({ label, setPlace }: P) => {
- const [query, setQuery] = useState('')
- let textInput = React.createRef<HTMLInputElement>()
- const handleChange = ({
- currentTarget: { value },
- }: React.ChangeEvent<HTMLInputElement>) => {
- setQuery(value)
- }
- const handlePlaceSelect = (autocomplete: google.maps.places.Autocomplete) => {
- let addressObject = autocomplete.getPlace()
- if (addressObject.geometry && addressObject.address_components) {
- let place: Place = {}
- place.name = addressObject.address_components[0].short_name
- place.lat = addressObject.geometry.location.lat()
- place.lng = addressObject.geometry.location.lng()
- if (place) {
- setQuery(place.name)
- setPlace(place)
- }
- }
- }
- const handleLoad = () => {
- // Options for Autocomplete
- const options = { types: [`(cities)`] }
- // Initialise Google Autocomplete
- if (textInput.current) {
- /*global google*/
- const autocomplete = new google.maps.places.Autocomplete(
- textInput.current,
- options,
- )
- // Set initial restrict to the greater list of countries.
- // Currently restricted to the UK
- autocomplete.setComponentRestrictions({
- country: ['gb', 'fr', 'pt', 'es'],
- })
- // Avoid paying for data that you don't need by restricting the
- // set of place fields that are returned to just the address
- // components and formatted address
- autocomplete.setFields([
- 'address_components',
- 'formatted_address',
- 'geometry',
- ])
- // Fire Event when a suggested name is selected
- autocomplete.addListener('place_changed', () => {
- handlePlaceSelect(autocomplete)
- })
- } else {
- throw new Error(
- `Google maps failed to initialise. Is the ref target correct?`,
- )
- }
- }
- return (
- <>
- <Script
- url={`...google api url`}
- onLoad={handleLoad}
- />
- <TextInputLabel
- htmlFor="gpac"
- css={{
- marginTop: '20px',
- }}
- >
- {label}
- </TextInputLabel>
- <Input
- id="gpac"
- type="text"
- value={query}
- className={query ? 'suggestions-active' : ''}
- onChange={handleChange}
- placeholder="eg London"
- ref={textInput}
- spellCheck={false}
- autoComplete="none"
- />
- </>
- )
- }
- export default GooglePlacesAutocomplete
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement