我正在尝试使用 React google 自动完成功能,我遇到的问题是,由于某种原因,两个库
react-google-places-autocomplete
和 react-places-autocomplete
总是从我所做的搜索中返回单个值,这是错误的,因为在 google 上搜索时或者使用 use-places-autocomplete
它会返回更多值。
81237
react-google-places-autocomplete
和 react-places-autocomplete
1: 数组得到的结果
[
{
"address_components": [
{
"long_name": "81237",
"short_name": "81237",
"types": [
"postal_code"
]
},
{
"long_name": "Ohio City",
"short_name": "Ohio City",
"types": [
"locality",
"political"
]
},
...
],
"formatted_address": "Ohio City, CO 81237, USA",
"geometry": {
...
},
"place_id": "ChIJJXK28KjiP4cRZNwTV9HTmB0",
"types": [
"postal_code"
]
}
]
但是来自
use-places-autocomplete
5 的数组:
[
{
"description": "Ohio City, CO 81237, USA",
"matched_substrings": [
{
"length": 5,
"offset": 14
}
],
"place_id": "ChIJJXK28KjiP4cRZNwTV9HTmB0",
"reference": "ChIJJXK28KjiP4cRZNwTV9HTmB0",
"structured_formatting": {
....
},
"terms": [
{
"offset": 0,
"value": "Ohio City"
},
...
],
"types": [
"postal_code",
"geocode"
]
},
{
"description": "81237 Geranium Avenue, Indio, CA, USA",
"matched_substrings": [
{
"length": 5,
"offset": 0
}
],
"place_id": "ChIJWQb2oxH42oAR_9paiGTudYc",
"reference": "ChIJWQb2oxH42oAR_9paiGTudYc",
"structured_formatting": {
...
},
"terms": [
{
"offset": 0,
"value": "81237"
},
...
],
"types": [
"premise",
"geocode"
]
},
{
"description": "81237 Victoria Lane, La Quinta, CA, USA",
"matched_substrings": [
{
"length": 5,
"offset": 0
}
],
"place_id": "ChIJv5gvO0RX2oARay4BYKgPMGA",
"reference": "ChIJv5gvO0RX2oARay4BYKgPMGA",
"structured_formatting": {
...
},
"terms": [
{
"offset": 0,
"value": "81237"
},
...
],
"types": [
"premise",
"geocode"
]
}
]
代码逻辑:
import { geocodeByAddress } from 'react-google-places-autocomplete'
const handleAddressOptionsFilter = async () => {
try {
if (!fieldAdrress) {
setAddressOptions([])
return
}
const formattedResults = data.map((result) => ({
label: result.description,
value: result,
}))
const rs = await geocodeByAddress(fieldAdrress)
console.log('NewEvent: ', data, rs)
setAddressOptions(formattedResults)
} catch (error) {
console.error('Error fetching geocode data:', error)
}
}
const handleAddressOnChange = (
event: React.ChangeEvent<HTMLInputElement>,
) => {
form.setValue('address', event.target.value)
setValue(event.target.value)
}
const handleAddressSelect = (option: Option) => {
const street = option.value.terms[0].value
const neighborhood = option.value.terms[1].value
const city = option.value.terms[2].value
const state = option.value.terms[3].value
const country = option.value.terms[4].value
if (street) form.setValue('address', street as string)
if (city) form.setValue('city', city as string)
if (state) form.setValue('state', state as string)
// if (zip) form.setValue('zip', zip?.long_name as string)
}
return (
<Base hideBg={true} bottomBar={false} allowFullHeight={true}>
<div className="flex flex-1 mt-[18px] items-center h-full flex-col mb-[50px]">
<form className="flex flex-col items-center">
<Input
type="autocomplete"
placeholder="Address"
className="mt-[18px]"
register={form.register('address')}
hasError={form.formState.errors.address?.message}
form={form}
onCompleteFunction={handleAddressOptionsFilter}
onCompleteOptions={addressOptions}
onChange={handleAddressOnChange}
onSelect={handleAddressSelect}
/>
在
index.js
上我插入了:
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY=places"></script>
我需要使用
react-google-places-autocomplete
和 react-places-autocomplete
中的库,因为 use-places-autocomplete
不返回 ZIP
您提到您正在尝试使用地点自动完成服务。但是,从您提供的代码片段中,我注意到您没有使用
<PlaceAutocomplete>
组件,而只是使用 geocodeAddress
函数,顺便说一句,该函数位于 react-places-autocomplete
库中,而不是 react-google-places-autocomplete
中。
在阅读 react-places-autocomplete 文档后,
geocodeByAddress
实用函数可能利用了 Google Maps Geocoding API。因此,它将用户输入(例如 “81237”(可能由地理编码器读取为邮政编码)转换为地理坐标,并返回与其关联的主要位置,即 “Ohio City, CO 81237, USA” 。
如果您想使用
react-places-autocomplete
并且您的目标是在用户在输入字段中键入甚至不明确的地址(例如 “81237”)时提供自动完成选项,则您需要合并 <PlaceAutocomplete>
组件。
使用官方 npm 文档中的 react-places-autocomplete 和 react-google-places-autocomplete 的基本示例,在使用邮政编码 “81237” 进行测试时,我得到了五个预测。
1.)反应地点自动完成
在我的
index.html
中加载了Maps JS API
App.js
import React from "react";
import PlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from "react-places-autocomplete";
class LocationSearchInput extends React.Component {
constructor(props) {
super(props);
this.state = { address: "" };
}
handleChange = (address) => {
this.setState({ address });
};
handleSelect = (address) => {
geocodeByAddress(address)
.then((results) => getLatLng(results[0]))
.then((latLng) => console.log("Success", latLng))
.catch((error) => console.error("Error", error));
};
render() {
return (
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
onSelect={this.handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div>
<input
{...getInputProps({
placeholder: "Search Places ...",
className: "location-search-input",
})}
/>
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map((suggestion) => {
const className = suggestion.active
? "suggestion-item--active"
: "suggestion-item";
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: "#fafafa", cursor: "pointer" }
: { backgroundColor: "#ffffff", cursor: "pointer" };
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style,
})}
>
<span>{suggestion.description}</span>
</div>
);
})}
</div>
2.)react-google-places-autocomplete
应用程序.js
import React from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";
const Component = () => (
<div>
<GooglePlacesAutocomplete apiKey="YOUR_API_KEY" />
</div>
);
export default Component;