最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I include postal codes in Google Places Autocomplete to differentiate similar addresses? - Stack Overflow

programmeradmin2浏览0评论

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;

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论