发布于 2026-01-06 2 阅读
0

✨ 隆重推出 use-places-autocomplete:用于 Google 地图地点自动完成的 React Hook

✨ 隆重推出 use-places-autocomplete:用于 Google 地图地点自动完成的 React Hook

嘿,各位!有了use-places-autocomplete,你可以在 10 分钟内构建出像下面示例一样的自定义地点自动完成 UI,真的,一点也不夸张 😉

演示

⚡️亲自体验:https://use-places-autocomplete.netlify.app

特征

它是如何运作的?

首先,使用 script 标签将库加载到您的项目中。



<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>


Enter fullscreen mode Exit fullscreen mode

开始构建我们的组件。查看 API 文档 了解更多信息。



import usePlacesAutocomplete, {
  getGeocode,
  getLatLng,
} from "use-places-autocomplete";
import useOnclickOutside from "react-cool-onclickoutside";

const PlacesAutocomplete = () => {
  const {
    ready,
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions,
  } = usePlacesAutocomplete({
    requestOptions: {
      /* Define search scope here */
    },
    debounce: 300,
  });
  const ref = useOnclickOutside(() => {
    // When user clicks outside of the component, we can dismiss
    // the searched suggestions by calling this method
    clearSuggestions();
  });

  const handleInput = (e) => {
    // Update the keyword of the input element
    setValue(e.target.value);
  };

  const handleSelect =
    ({ description }) =>
    () => {
      // When user selects a place, we can replace the keyword without request data from API
      // by setting the second parameter to "false"
      setValue(description, false);
      clearSuggestions();

      // Get latitude and longitude via utility functions
      getGeocode({ address: description }).then((results) => {
        const { lat, lng } = getLatLng(results[0]);
        console.log("📍 Coordinates: ", { lat, lng });
      });
    };

  const renderSuggestions = () =>
    data.map((suggestion) => {
      const {
        place_id,
        structured_formatting: { main_text, secondary_text },
      } = suggestion;

      return (
        <li key={place_id} onClick={handleSelect(suggestion)}>
          <strong>{main_text}</strong> <small>{secondary_text}</small>
        </li>
      );
    });

  return (
    <div ref={ref}>
      <input
        value={value}
        onChange={handleInput}
        disabled={!ready}
        placeholder="Where are you going?"
      />
      {/* We can use the "status" to decide whether we should display the dropdown or not */}
      {status === "OK" && <ul>{renderSuggestions()}</ul>}
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

很简单吧?这就是✨的魔力usePlacesAutocomplete。我只是通过一个简单的例子来演示它的工作原理。不过,对于用户体验丰富的自动完成组件,你还可以做更多的事情,例如像我的演示那样支持WAI-ARIA和关键词(查看代码),以及关键词清除按钮、搜索历史记录等等。

💡 react-cool-onclickoutside是我的另一个 hook 库,它可以帮助您处理用户在组件外部的点击交互。


感谢阅读,更多使用详情请查看项目的 GitHub 页面:  https://github.com/wellyshen/use-places-autocomplete

您也可以安装此软件包,它通过 npm分发。



$ yarn add use-places-autocomplete
# or
$ npm install --save use-places-autocomplete


Enter fullscreen mode Exit fullscreen mode

使用 TypeScript 时,需要安装@types/googlemaps作为devDependencies.



$ yarn add --dev @types/googlemaps
# or
$ npm install --save-dev @types/googlemaps


Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/wellyshen/introducing-use-places-autocomplete-react-hook-for-google-maps-places-autocomplete-41h5