Autocomplete example with Places API (new) #707
-
Greetings, I have currently implemented the Autocomplete example (seen in https://visgl.github.io/react-google-maps/examples/autocomplete) precisely the classic version with some minimal edits. const AddressInput = () => {
const [placeAutocomplete, setPlaceAutocomplete] =
useState<google.maps.places.Autocomplete | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const places = useMapsLibrary("places");
useEffect(() => {
if (!places || !inputRef.current) return;
const options = {
fields: ["geometry", "name", "formatted_address"],
};
setPlaceAutocomplete(new places.Autocomplete(inputRef.current, options));
}, [places]);
useEffect(() => {
if (!placeAutocomplete) return;
placeAutocomplete.addListener("place_changed", () => {
console.log(placeAutocomplete.getPlace());
});
}, [placeAutocomplete]);
return <Input ref={inputRef} placeholder="Search address" />;
}; As I understood, this implementation uses the Legacy version of Places API, now I know to switch it to Places API (new) it's all a matter of migration (following https://developers.google.com/maps/documentation/javascript/places-migration-autocomplete#autocomplete-widget). placeAutocomplete.addEventListener("gmp-placeselect", async ({place}) => {
await place.fetchFields({
fields: ["displayName", "formattedAddress", "location"],
});
}); But |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
The first thing to know is that the There seems to be a couple of things wrong with that at the moment. For example, the placeAutocomplete.addEventListener(
"gmp-placeselect",
async (event: google.maps.places.PlaceAutocompletePlaceSelectEvent) =>
handlePlaceSelected(event.place)
); Another issue is that the So, to summarize – I would recommend you go a different route and use the I would also love to migrate our examples to use the new Places API, so if you get something working, please consider dropping us a PR for that. |
Beta Was this translation helpful? Give feedback.
-
Hi. I just recently noticed that without
|
Beta Was this translation helpful? Give feedback.
The first thing to know is that the
PlaceAutocompleteElement
is currently only available in the alpha and beta release-channels, and it isn't quite clear yet when it will be ready for the stable releases. When the constructor can't be found, that would typically be because you're loading a stable (weekly/monthly/quarterly) release instead of alpha or beta.There seems to be a couple of things wrong with that at the moment. For example, the
@types/google.maps
package has a couple of issues related to thePlaceAutocompleteElement
class (see my comment here: googlemaps/js-api-loader#894 (comment)). Another thing is that theEventTarget
interface isn't properly typed at the moment either, so …