✨ 隆重推出 use-places-autocomplete:用于 Google 地图地点自动完成的 React Hook
嘿,各位!有了use-places-autocomplete,你可以在 10 分钟内构建出像下面示例一样的自定义地点自动完成 UI,真的,一点也不夸张 😉
⚡️亲自体验:https://use-places-autocomplete.netlify.app
特征
- 🧠 提供由Google Maps Places API支持的智能地点建议。
- 🎣 使用 React hook构建您自己的自定义自动完成 UI 。
- 🔧使用Google Maps Geocoding API进行地理编码和获取地理坐标的实用函数。
- 🤑 内置缓存机制,帮您节省 Google API 的费用。
- 💰 内置防抖机制,可降低 Google API 的成本。
- 🚀 支持异步加载 Google 脚本。
- 📜 支持TypeScript类型定义。
- ⌨️ 通过全面的演示代码构建 UX 丰富的组件(例如符合 WAI-ARIA 标准并支持关键字)。
- 🦔 体积小巧(压缩后约 1.7KB)。除了 . 之外,没有其他外部依赖项
react。
它是如何运作的?
首先,使用 script 标签将库加载到您的项目中。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
开始构建我们的组件。查看 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>
);
};
很简单吧?这就是✨的魔力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
使用 TypeScript 时,需要安装@types/googlemaps作为devDependencies.
$ yarn add --dev @types/googlemaps
# or
$ npm install --save-dev @types/googlemaps
