如何用react-places-autocomplete限制谷歌自动补全仅显示城市、州、国家、邮编?
Hey there! I get exactly what you're trying to achieve—narrowing down the autocomplete results to just the specific region types you need, without those unwanted towns or missing ZIP codes. Let's break down the problem and fix it step by step.
Why Your Current Settings Aren't Working
- When using
types: ['(regions)'], Google Places API returns a broad range of regional results including sub-localities (like towns/neighborhoods), which is why you're seeing unwanted entries. types: ['(cities)']restricts results to city-level entries, but it doesn't include postal codes, hence the missing ZIP code suggestions.
The Solution: Combine Specific Types + Frontend Filtering
Google Places API doesn't have a single type that covers exactly cities, states, countries, and ZIP codes, but we can combine specific individual types and filter results to exclude unwanted entries. Here's how to adjust your code:
Update the
searchOptionsto target the exact types we care about:const searchOptions = { types: ['locality', 'administrative_area_level_1', 'country', 'postal_code'], componentRestrictions: { country: "us" } }Let's define these types for clarity:
locality: Citiesadministrative_area_level_1: US Statescountry: The United Statespostal_code: ZIP Codes
Filter Suggestions Before Rendering
Even with the updated types, we might get some stray results. We'll add a filter to only keep suggestions that match our allowed types:Modify the
suggestions.mapsection in yourrenderFuncto include a filter first:{suggestions .filter(suggestion => { const allowedTypes = new Set(['locality', 'administrative_area_level_1', 'country', 'postal_code']); // Check if the suggestion has at least one of our allowed types return suggestion.types.some(type => allowedTypes.has(type)); }) .map(suggestion => { const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item'; const style = suggestion.active ? { backgroundColor: '#fafafa', cursor: 'pointer', margin: '0px 0px 0px 10px', width: '70%' } : { backgroundColor: '#ffffff', cursor: 'pointer', margin: '0px 0px 0px 10px', width: '70%'}; return ( <div {...getSuggestionItemProps(suggestion, { className, style, })} > <span>{suggestion.description}</span> </div> ); })}
Full Modified Code
Here's your complete code with the changes applied:
import PlacesAutocomplete, { geocodeByAddress, getLatLng, } from 'react-places-autocomplete'; class YourComponent extends React.Component { state = { address: '' }; // Ensure state is initialized searchOptions = { types: ['locality', 'administrative_area_level_1', 'country', 'postal_code'], componentRestrictions: { country: "us" } } 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() { const renderFunc = ({ getInputProps, suggestions, getSuggestionItemProps, loading }) => ( <div> <input className="location-field" {...getInputProps({ placeholder: 'Search Places ...', className: 'input-box location-search-input form-control field-list', })} /> <div className="autocomplete-dropdown-container"> {loading && <div>Loading...</div>} {suggestions .filter(suggestion => { const allowedTypes = new Set(['locality', 'administrative_area_level_1', 'country', 'postal_code']); return suggestion.types.some(type => allowedTypes.has(type)); }) .map(suggestion => { const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item'; const style = suggestion.active ? { backgroundColor: '#fafafa', cursor: 'pointer', margin: '0px 0px 0px 10px', width: '70%' } : { backgroundColor: '#ffffff', cursor: 'pointer', margin: '0px 0px 0px 10px', width: '70%'}; return ( <div {...getSuggestionItemProps(suggestion, { className, style, })} > <span>{suggestion.description}</span> </div> ); })} </div> </div> ); return ( <div> <PlacesAutocomplete value={this.state.address} onChange={this.handleChange} onSelect={(e)=>this.handleSelect(e, fieldConstants.region)} searchOptions={this.searchOptions} > {renderFunc} </PlacesAutocomplete> </div> ); } }
How This Works
- By specifying the exact types we want, we tell Google Places API to prioritize those result types.
- The filter step ensures that any accidental non-matching results (like sub-localities) are excluded from the autocomplete dropdown.
- Now users will see cities, states, the US itself, and ZIP codes—exactly what you're looking for!
内容的提问来源于stack exchange,提问作者Sangram Badi

