react-native-google-autocomplete

repository·main·Indexed 41 days ago

https://github.com/appandflow/react-native-google-autocomplete

A React Native hook for integrating Google Places Autocomplete into applications. Version 2.2.0 provides the useGoogleAutocomplete hook to handle search terms, debouncing, location biasing, and fetching place details via searchDetails. It supports custom headers for platform security, country restrictions via components, and requires a proxyUrl for web platforms to avoid CORS issues.

Tokens
4.7K
Snippets
16
Records
20
Agent score
50%

What's inside react-native-google-autocomplete

  1. Restrict search results by country

    main

    To restrict search results to a specific country, use the components property with the format country:XX (where XX is the two-letter country code). For example, to restrict to Canada, use components="country:ca".

    // Example: Restrict to Canada
    const { locationResults, setTerm } = useGoogleAutocomplete(API_KEY, {
      components: 'country:ca',
    });
  2. Apply Custom Headers for Platform Restrictions

    main

    Use the headers property in the config object to pass platform-specific API restrictions like Android package names or iOS bundle identifiers.

    // Android
    const { locationResults, setTerm } = useGoogleAutocomplete(API_KEY, {
      headers: {
        'X-Android-Package': 'com.example.app',
        'X-Android-Cert': 'your-signing-certificate-fingerprint',
      },
    });
    
    // iOS
    const { locationResults, setTerm } = useGoogleAutocomplete(API_KEY, {
      headers: {
        'X-Ios-Bundle-Identifier': 'com.example.app',
      },
    });
  3. Configure the useGoogleAutocomplete hook

    main

    The config object allows you to customize the autocomplete behavior.

    PropertyTypeDefaultDescription
    debouncenumber300Delay in ms before starting the search.
    debounceOptionsobject-Configuration options for debounce behavior.
    languagestring'en'Language code.
    queryTypesstring'address'Google Place Types.
    minLengthnumber2Minimum term length before search starts.
    componentsstring-Grouping of places to restrict results (e.g., components="country:ca").
    radiusnumber-Distance in meters to return place results.
    latnumber-Latitude. Requires lng.
    lngnumber-Longitude. Requires lat.
    strictBoundsboolean-Returns only places strictly within the defined location and radius.
    originobject-Origin point { lat, lng } to calculate distance_meters.
    proxyUrlstring-Required for Web platforms to avoid CORS issues.
    headersobject-Custom headers for API requests (e.g., for platform restrictions).
  4. Implement a basic Google Autocomplete search

    main

    This example demonstrates how to bind a TextInput to the term and setTerm properties, and how to display and interact with the locationResults.

      const { locationResults, setTerm, clearSearch, searchDetails, term } =
        useGoogleAutocomplete(API_KEY, {
          language: 'en',
          debounce: 300,
        });
    
      return (
        <View>
          <TextInput
            value={term}
            onChangeText={setTerm}
          />
          {locationResults.slice(0, 3).map((el, i) => (
            <TouchableOpacity
              key={String(i)}
              onPress={async () => {
                const details = await searchDetails(el.place_id);
                console.log(JSON.stringify(details, null, 2));
              }}
            >
              <Text>{el.structured_formatting.main_text}</Text>
            </TouchableOpacity>
          ))}
        </View>
      );
  5. Access properties from useGoogleAutocomplete

    main

    The hook returns an object containing the following properties:

    • clearSearch: Function to clear the current search.
    • isSearching: Boolean indicating if a search is currently in progress.
    • locationResults: Array of GoogleLocationResult objects returned by the search.
    • searchDetails: Function to fetch full details for a specific result using its place_id.
    • searchError: Contains errors encountered during search.
    • term: The current search term string.
    • setTerm: Function to update the current search term.
  6. Use the useGoogleAutocomplete hook

    main

    The useGoogleAutocomplete hook provides functionality to search for Google Places. It requires a Google Places API key and accepts an optional configuration object.

    Arguments:

    • apiKey: Your Google Places API key.
    • config: (Optional) Configuration object to customize search behavior.
    const { 
      locationResults, 
      setTerm, 
      clearSearch, 
      searchDetails, 
      term 
    } = useGoogleAutocomplete(API_KEY, {
      language: 'en',
      debounce: 300,
    });
  7. Configure the Query object for Google API requests

    main

    When using the GoogleService to search or fetch details, you must provide a Query object. This object configures the parameters sent to the Google Maps Places API.

    Key parameters include:

    • key: Your Google API Key.
    • language: The language code for the response.
    • types: Restricts results to specific types. Supported values are 'address', 'geocode', '(cities)', 'establishment', or 'geocode|establishment'.
    • components: (Optional) A string used to restrict results to certain regions (e.g., 'country:us').
    • radius: (Optional) A string representing the radius in meters.
    • lat and lng: (Optional) Latitude and longitude to define the location around which to retrieve place information. Note: Both must be provided together.
    • origin: (Optional) An object containing { lat, lng } to define the origin point for distance calculations. Note: Both must be provided together.
    • strictBounds: (Optional) A boolean to enable strict bounds checking.
    const query: Query = {
      key: 'YOUR_GOOGLE_API_KEY',
      language: 'en',
      types: 'address',
      lat: 40.7128,
      lng: -74.0060
    };
  8. Reference the GoogleLocationDetailResult type

    main

    When calling searchDetails(place_id), the returned object follows the GoogleLocationDetailResult interface.

    export interface GoogleLocationDetailResult {
      adr_address: string;
      formatted_address: string;
      icon: string;
      id: string;
      name: string;
      place_id: string;
      scope: string;
      reference: string;
      url: string;
      utc_offset: number;
      vicinity: string;
      types: string[];
      geometry: {
        location: {
          lat: number;
          lng: number;
        };
        viewport: {
          [type: string]: {
            lat: number;
            lng: number;
          };
        };
      };
      address_components: Array<{ 
        long_name: string; 
        short_name: string; 
        types: string[]; 
      }>;
    }
  9. Reference the GoogleLocationResult type

    main

    The locationResults array contains objects following the GoogleLocationResult interface. Note that distance_meters is only present if the origin parameter was provided in the config.

    export interface GoogleLocationResult {
      description: string;
      id: string;
      matched_substrings: Array<{ 
        length: number; 
        offset: number; 
      }>;
      place_id: string;
      reference: string;
      structured_formatting: {
        main_text: string;
        secondary_text: string;
        main_text_matched_substrings: Array<{ 
          length: number; 
        }>;
      };
      terms: Array<{ 
        offset: number; 
        value: string; 
      }>;
      types: string[];
      distance_meters?: number; // Present when origin parameter is provided
    }
  10. Use searchDetails to retrieve specific place information

    main

    Once a user selects a result from locationResults, you can use the searchDetails function to fetch comprehensive information about that specific place using its placeId.

    // Example: Fetching details when a result is selected
    const handleSelect = async (placeId: string) => {
      try {
        const details = await searchDetails(placeId);
        console.log('Place Details:', details);
      } catch (error) {
        console.error('Failed to fetch details', error);
      }
    };