-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
/
GoogleMaps.tsx
177 lines (158 loc) · 4.88 KB
/
GoogleMaps.tsx
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import parse from 'autosuggest-highlight/parse';
import throttle from 'lodash/throttle';
// This key was created specifically for the demo in mui.com.
// You need to create a new one for your application.
const GOOGLE_MAPS_API_KEY = 'AIzaSyC3aviU6KHXAjoSnxcw6qbOhjnFctbxPkE';
function loadScript(src: string, position: HTMLElement | null, id: string) {
if (!position) {
return;
}
const script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('id', id);
script.src = src;
position.appendChild(script);
}
const autocompleteService = { current: null };
interface MainTextMatchedSubstrings {
offset: number;
length: number;
}
interface StructuredFormatting {
main_text: string;
secondary_text: string;
main_text_matched_substrings: readonly MainTextMatchedSubstrings[];
}
interface PlaceType {
description: string;
structured_formatting: StructuredFormatting;
}
export default function GoogleMaps() {
const [value, setValue] = React.useState<PlaceType | null>(null);
const [inputValue, setInputValue] = React.useState('');
const [options, setOptions] = React.useState<readonly PlaceType[]>([]);
const loaded = React.useRef(false);
if (typeof window !== 'undefined' && !loaded.current) {
if (!document.querySelector('#google-maps')) {
loadScript(
`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=places`,
document.querySelector('head'),
'google-maps',
);
}
loaded.current = true;
}
const fetch = React.useMemo(
() =>
throttle(
(
request: { input: string },
callback: (results?: readonly PlaceType[]) => void,
) => {
(autocompleteService.current as any).getPlacePredictions(
request,
callback,
);
},
200,
),
[],
);
React.useEffect(() => {
let active = true;
if (!autocompleteService.current && (window as any).google) {
autocompleteService.current = new (
window as any
).google.maps.places.AutocompleteService();
}
if (!autocompleteService.current) {
return undefined;
}
if (inputValue === '') {
setOptions(value ? [value] : []);
return undefined;
}
fetch({ input: inputValue }, (results?: readonly PlaceType[]) => {
if (active) {
let newOptions: readonly PlaceType[] = [];
if (value) {
newOptions = [value];
}
if (results) {
newOptions = [...newOptions, ...results];
}
setOptions(newOptions);
}
});
return () => {
active = false;
};
}, [value, inputValue, fetch]);
return (
<Autocomplete
id="google-map-demo"
sx={{ width: 300 }}
getOptionLabel={(option) =>
typeof option === 'string' ? option : option.description
}
filterOptions={(x) => x}
options={options}
autoComplete
includeInputInList
filterSelectedOptions
value={value}
onChange={(event: any, newValue: PlaceType | null) => {
setOptions(newValue ? [newValue, ...options] : options);
setValue(newValue);
}}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
renderInput={(params) => (
<TextField {...params} label="Add a location" fullWidth />
)}
renderOption={(props, option) => {
const matches = option.structured_formatting.main_text_matched_substrings;
console.log(option, option.structured_formatting);
const parts = parse(
option.structured_formatting.main_text,
matches.map((match: any) => [match.offset, match.offset + match.length]),
);
return (
<li {...props}>
<Grid container alignItems="center">
<Grid item>
<Box
component={LocationOnIcon}
sx={{ color: 'text.secondary', mr: 2 }}
/>
</Grid>
<Grid item xs>
{parts.map((part, index) => (
<span
key={index}
style={{
fontWeight: part.highlight ? 700 : 400,
}}
>
{part.text}
</span>
))}
<Typography variant="body2" color="text.secondary">
{option.structured_formatting.secondary_text}
</Typography>
</Grid>
</Grid>
</li>
);
}}
/>
);
}