I have a form where users can input their address using the Google Places Autocomplete API. I’ve run into a problem where the autocomplete isn’t distinguishing between similar addresses in the UK, meaning the house number + address + city exist twice, and the only way to distinguish between the two is postal code. In fact for one of the addresses, I have to manually input the postal code for the address to even show up.
Is there a way to fix this, this is my current setup:
import React, { useRef } from "react";
import { useLoadScript } from "@react-google-maps/api";
const libraries: "places"[] = ["places"];
interface GoogleAddressInputProps {
onPlaceSelected: (place: google.maps.places.PlaceResult) => void;
}
const GoogleAddressInput: React.FC<GoogleAddressInputProps> = ({
onPlaceSelected,
}) => {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: import.meta.env.VITE_GOOGLE_MAPS_API_KEY,
libraries,
});
const inputRef = useRef<HTMLInputElement>(null);
const handlePlaceChanged = () => {
if (inputRef.current) {
const autocomplete = new google.maps.places.Autocomplete(
inputRef.current,
{
componentRestrictions: { country: "GB" },
fields: [
"address_components",
"formatted_address",
"geometry",
"place_id",
], // Include postal code
}
);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
onPlaceSelected(place);
});
}
};
if (loadError) return <div>Error loading Google Maps</div>;
if (!isLoaded) return <div>Loading...</div>;
return (
<input
ref={inputRef}
type="text"
placeholder="Enter your address"
onFocus={handlePlaceChanged}
className="w-full px-4 py-3 text-sm rounded-md border border-gray-200 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-all outline-none text-gray-600"
/>
);
};
export default GoogleAddressInput;