You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用react-places-autocomplete限制谷歌自动补全仅显示城市、州、国家、邮编?

Fixing React-Places-Autocomplete to Show Only Cities, States, Countries, and ZIP Codes (US)

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:

  1. Update the searchOptions to 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: Cities
    • administrative_area_level_1: US States
    • country: The United States
    • postal_code: ZIP Codes
  2. 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.map section in your renderFunc to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:57:31