| 6597 |
stevensc |
1 |
import React, { useState, useEffect, useRef } from "react";
|
|
|
2 |
|
|
|
3 |
let autoComplete;
|
|
|
4 |
|
|
|
5 |
const loadScript = (url, callback) => {
|
|
|
6 |
let script = document.createElement("script");
|
|
|
7 |
script.type = "text/javascript";
|
|
|
8 |
|
|
|
9 |
if (script.readyState) {
|
|
|
10 |
script.onreadystatechange = function () {
|
|
|
11 |
if (script.readyState === "loaded" || script.readyState === "complete") {
|
|
|
12 |
script.onreadystatechange = null;
|
|
|
13 |
callback();
|
|
|
14 |
}
|
|
|
15 |
};
|
|
|
16 |
} else {
|
|
|
17 |
script.onload = () => callback();
|
|
|
18 |
}
|
|
|
19 |
|
|
|
20 |
script.src = url;
|
|
|
21 |
document.getElementsByTagName("head")[0].appendChild(script);
|
|
|
22 |
};
|
|
|
23 |
|
|
|
24 |
function handleScriptLoad(updateQuery, autoCompleteRef) {
|
|
|
25 |
autoComplete = new window.google.maps.places.Autocomplete(
|
|
|
26 |
autoCompleteRef.current,
|
|
|
27 |
{ types: ["(cities)"], componentRestrictions: { country: "us" } }
|
|
|
28 |
);
|
|
|
29 |
autoComplete.setFields(["address_components", "formatted_address"]);
|
|
|
30 |
autoComplete.addListener("place_changed", () =>
|
|
|
31 |
handlePlaceSelect(updateQuery)
|
|
|
32 |
);
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
async function handlePlaceSelect(updateQuery) {
|
|
|
36 |
const addressObject = autoComplete.getPlace();
|
|
|
37 |
const query = addressObject.formatted_address;
|
|
|
38 |
updateQuery(query);
|
|
|
39 |
console.log(addressObject);
|
|
|
40 |
}
|
|
|
41 |
|
|
|
42 |
function SearchLocationInput({googleApiKey}) {
|
|
|
43 |
const [query, setQuery] = useState("");
|
|
|
44 |
const autoCompleteRef = useRef(null);
|
|
|
45 |
|
|
|
46 |
useEffect(() => {
|
|
|
47 |
loadScript(
|
|
|
48 |
`https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places`,
|
|
|
49 |
() => handleScriptLoad(setQuery, autoCompleteRef)
|
|
|
50 |
);
|
|
|
51 |
}, []);
|
|
|
52 |
|
|
|
53 |
return (
|
|
|
54 |
<div className="search-location-input">
|
|
|
55 |
<input
|
|
|
56 |
ref={autoCompleteRef}
|
|
|
57 |
onChange={event => setQuery(event.target.value)}
|
|
|
58 |
placeholder="Enter a City"
|
|
|
59 |
value={query}
|
|
|
60 |
/>
|
|
|
61 |
</div>
|
|
|
62 |
);
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
export default SearchLocationInput;
|