### Start Example App Packager (Yarn)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Starts the Metro server packager for the example application. This is necessary to run the example app on a device or simulator.
```sh
yarn example start
```
--------------------------------
### Run Example App on iOS (Yarn)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device. Requires iOS development environment setup.
```sh
yarn example ios
```
--------------------------------
### Install @appandflow/react-native-google-autocomplete
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Installation commands for the library using common Node.js package managers.
```bash
# Using yarn
yarn add @appandflow/react-native-google-autocomplete
# Using npm
npm install @appandflow/react-native-google-autocomplete
```
--------------------------------
### Run Example App on Android (Yarn)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator. Requires Android development environment setup.
```sh
yarn example android
```
--------------------------------
### Install Google Autocomplete Package
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
Commands to install the library using common Node.js package managers.
```bash
yarn add @appandflow/react-native-google-autocomplete
```
```bash
npm i @appandflow/react-native-google-autocomplete
```
--------------------------------
### Run Example App on Web (Yarn)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Runs the example application in a web browser. This allows for testing the library's web compatibility.
```sh
yarn example web
```
--------------------------------
### Install Project Dependencies (Yarn)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Installs all necessary project dependencies using Yarn workspaces. This command should be run in the root directory of the project.
```sh
yarn
```
--------------------------------
### Implement Google Autocomplete Hook
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
A functional example demonstrating how to use the useGoogleAutocomplete hook to fetch and display search results with a TextInput and TouchableOpacity components.
```typescript
const { locationResults, setTerm, clearSearch, searchDetails, term } =
useGoogleAutocomplete(API_KEY, {
language: 'en',
debounce: 300,
});
return (
{locationResults.slice(0, 3).map((el, i) => (
{
const details = await searchDetails(el.place_id);
console.log(JSON.stringify(details, null, 2));
}}
>
{el.structured_formatting.main_text}
))}
);
```
--------------------------------
### Restrict Autocomplete Search by Country
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Shows how to limit search results to specific countries using the `components` parameter in the `useGoogleAutocomplete` hook. Examples include restricting to a single country (Canada) and multiple countries (US and Mexico).
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
// Restrict to single country (Canada)
const canadaOnly = useGoogleAutocomplete('YOUR_API_KEY', {
components: 'country:ca',
language: 'en',
});
// Restrict to multiple countries (US and Mexico)
const northAmerica = useGoogleAutocomplete('YOUR_API_KEY', {
components: 'country:us|country:mx',
language: 'en',
});
// Example usage with country restriction
function CanadianAddressSearch() {
const { locationResults, setTerm, term } = useGoogleAutocomplete(
'YOUR_API_KEY',
{
components: 'country:ca',
queryTypes: 'address',
language: 'en',
}
);
return (
{locationResults.map((result) => (
{result.description}
))}
);
}
```
--------------------------------
### Implement useGoogleAutocomplete Hook in React Native
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Demonstrates how to integrate the useGoogleAutocomplete hook to handle search queries, display results, and fetch place details. It covers state management for loading, errors, and user input.
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
import { View, TextInput, TouchableOpacity, Text, FlatList } from 'react-native';
const API_KEY = 'YOUR_GOOGLE_PLACES_API_KEY';
function LocationSearchScreen() {
const {
locationResults,
isSearching,
searchError,
clearSearch,
setTerm,
term,
searchDetails,
} = useGoogleAutocomplete(API_KEY, {
language: 'en',
debounce: 300,
minLength: 2,
queryTypes: 'address',
});
const handleSelectLocation = async (placeId: string) => {
try {
const details = await searchDetails(placeId);
console.log('Selected location:', {
name: details.name,
address: details.formatted_address,
coordinates: details.geometry.location,
});
} catch (error) {
console.error('Failed to get place details:', error);
}
};
return (
{isSearching && Searching...}
{searchError && Error: {searchError.message}}
item.place_id}
renderItem={({ item }) => (
handleSelectLocation(item.place_id)}>
{item.structured_formatting.main_text}
{item.structured_formatting.secondary_text}
)}
/>
);
}
```
--------------------------------
### Run Unit Tests (Jest)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Executes the project's unit tests using Jest. It is recommended to add tests for any new changes or bug fixes.
```sh
yarn test
```
--------------------------------
### Configure Google Autocomplete Hook
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Demonstrates the full range of configuration options for the `useGoogleAutocomplete` hook. This includes settings for search behavior like debouncing and minimum length, query types, geographic restrictions, and platform-specific settings such as proxy URLs and custom headers.
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
// Full configuration example
const { locationResults, setTerm, searchDetails } = useGoogleAutocomplete(
'YOUR_API_KEY',
{
// Search behavior
debounce: 500, // Debounce time in ms (default: 300)
debounceOptions: {
maxWait: 1000, // Maximum wait time
leading: false, // Invoke on leading edge
trailing: true, // Invoke on trailing edge
},
minLength: 3, // Min characters before search (default: 2)
language: 'fr', // Language for results (default: 'en')
// Query type options: 'address' | 'geocode' | '(cities)' | 'establishment' | 'geocode|establishment'
queryTypes: '(cities)', // Search only cities
// Geographic restrictions
components: 'country:ca|country:us', // Restrict to Canada and US
lat: 45.5017, // Center latitude for location bias
lng: -73.5673, // Center longitude for location bias
radius: '50000', // Search radius in meters
strictBounds: true, // Only return results within radius
// Distance calculation from origin point
origin: {
lat: 45.5017,
lng: -73.5673,
},
// Web platform support (required for web due to CORS)
proxyUrl: 'https://your-cors-proxy.com/',
// Custom headers for platform-specific API restrictions
headers: {
'X-Android-Package': 'com.yourapp.package',
'X-Android-Cert': 'your-signing-certificate-fingerprint',
},
}
);
```
--------------------------------
### Publish New Versions (release-it)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Publishes new versions of the package using the release-it tool. This script handles version bumping, tagging, and release creation.
```sh
yarn release
```
--------------------------------
### Enable Web Platform Support with proxyUrl
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Configures the library for use on web platforms by specifying a `proxyUrl`. This is necessary because the Google Places API does not directly support browser requests, requiring a CORS proxy. The `proxyUrl` option should only be provided when running on the web.
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
import { Platform } from 'react-native';
function CrossPlatformSearch() {
const isWeb = Platform.OS === 'web';
const { locationResults, setTerm, isSearching, searchError } = useGoogleAutocomplete(
'YOUR_API_KEY',
{
language: 'en',
// Only set proxyUrl on web platform
proxyUrl: isWeb ? 'https://your-cors-proxy.example.com/' : undefined,
minLength: 3,
}
);
// Note: On web, if proxyUrl is not provided, the hook will throw:
// Error: "A proxy url is needed for web"
return (
{searchError && {searchError.message}}
{isSearching && Loading...}
{locationResults.map((result) => (
{result.description}
))}
);
}
```
--------------------------------
### Lint Project Files (ESLint)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Lints the project files using ESLint to enforce code style and identify potential issues. This command checks for formatting and code quality.
```sh
yarn lint
```
--------------------------------
### Configure Custom Headers for API Restrictions in React Native
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Demonstrates how to pass platform-specific headers to the useGoogleAutocomplete hook. This is essential for applications using Google API keys with Android package or iOS bundle identifier restrictions.
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
import { Platform } from 'react-native';
function SecureApiSearch() {
const getHeaders = () => {
if (Platform.OS === 'android') {
return {
'X-Android-Package': 'com.yourcompany.yourapp',
'X-Android-Cert': 'AB:CD:EF:12:34:56:78:90:AB:CD:EF:12:34:56:78:90:AB:CD:EF:12',
};
}
if (Platform.OS === 'ios') {
return {
'X-Ios-Bundle-Identifier': 'com.yourcompany.yourapp',
};
}
return undefined;
};
const { locationResults, setTerm, searchDetails } = useGoogleAutocomplete(
'YOUR_RESTRICTED_API_KEY',
{
language: 'en',
headers: getHeaders(),
}
);
return (
{locationResults.map((result) => (
{result.description}
))}
);
}
```
--------------------------------
### Setting Custom Headers for API Requests (TypeScript)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
Shows how to pass custom headers to the Google Places API requests using the `useGoogleAutocomplete` hook. This is crucial for implementing application restrictions based on Android package names and signing certificates, or iOS bundle identifiers, enhancing API security.
```typescript
// 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',
},
});
```
--------------------------------
### Importing Result Typings (JavaScript)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
Demonstrates how to import the defined TypeScript/Flow interfaces for GoogleLocationDetailResult and GoogleLocationResult from the 'react-native-google-autocomplete' library. This allows for type checking and better code completion when working with the library's results.
```javascript
import {
GoogleLocationDetailResult,
GoogleLocationResult,
} from 'react-native-google-autocomplete';
```
--------------------------------
### Typecheck Project Files (TypeScript)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Performs type checking on the project files using TypeScript. This helps ensure code quality and catch potential type-related errors.
```sh
yarn typecheck
```
--------------------------------
### Retrieve Place Details with searchDetails
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Fetches detailed information for a specific place using its place_id. This function requires the place_id as input and returns comprehensive data such as formatted address, geometry, and address components. It's useful for displaying rich location details after a user selects a place.
```typescript
import { useGoogleAutocomplete, GoogleLocationDetailResult } from '@appandflow/react-native-google-autocomplete';
import { useState } from 'react';
function PlaceDetailsExample() {
const [selectedPlace, setSelectedPlace] = useState(null);
const { locationResults, setTerm, searchDetails } = useGoogleAutocomplete(
'YOUR_API_KEY',
{ language: 'en' }
);
const handleSelectPlace = async (placeId: string) => {
try {
const details = await searchDetails(placeId);
setSelectedPlace(details);
// Access detailed place information
console.log('Place Details:', {
name: details.name,
formattedAddress: details.formatted_address,
latitude: details.geometry.location.lat,
longitude: details.geometry.location.lng,
placeId: details.place_id,
types: details.types,
utcOffset: details.utc_offset,
url: details.url,
});
// Parse address components
const addressParts = {
streetNumber: details.address_components.find(c => c.types.includes('street_number'))?.long_name,
route: details.address_components.find(c => c.types.includes('route'))?.long_name,
city: details.address_components.find(c => c.types.includes('locality'))?.long_name,
state: details.address_components.find(c => c.types.includes('administrative_area_level_1'))?.short_name,
country: details.address_components.find(c => c.types.includes('country'))?.long_name,
postalCode: details.address_components.find(c => c.types.includes('postal_code'))?.long_name,
};
console.log('Address Components:', addressParts);
} catch (error) {
console.error('Error fetching place details:', error);
}
};
return (
{locationResults.map((result) => (
handleSelectPlace(result.place_id)}
>
{result.description}
))}
{selectedPlace && (
Selected: {selectedPlace.name}
{selectedPlace.formatted_address}
Coordinates: {selectedPlace.geometry.location.lat}, {selectedPlace.geometry.location.lng}
)}
);
}
```
--------------------------------
### Fix Linting Errors (ESLint)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/CONTRIBUTING.md
Automatically fixes formatting errors in the project files using ESLint. This command should be run after `yarn lint` if issues are found.
```sh
yarn lint --fix
```
--------------------------------
### Calculate Distance from Origin Point
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Illustrates how to calculate the straight-line distance from a specified origin point to each search result. When the `origin` parameter is provided to `useGoogleAutocomplete`, the results will include a `distance_meters` field, enabling distance-based filtering or display.
```typescript
import { useGoogleAutocomplete } from '@appandflow/react-native-google-autocomplete';
import { View, TextInput, Text, FlatList } from 'react-native';
function NearbyPlacesSearch() {
// Times Square, NYC as origin point
const originPoint = { lat: 40.758, lng: -73.9855 };
const { locationResults, setTerm, term, isSearching } = useGoogleAutocomplete(
'YOUR_API_KEY',
{
origin: originPoint,
queryTypes: 'establishment',
language: 'en',
}
);
const formatDistance = (meters?: number) => {
if (!meters) return '';
if (meters < 1000) return `${Math.round(meters)}m away`;
return `${(meters / 1000).toFixed(1)}km away`;
};
return (
item.place_id}
renderItem={({ item }) => (
{item.structured_formatting.main_text}
{item.structured_formatting.secondary_text}
{formatDistance(item.distance_meters)}
)}
/>
);
}
```
--------------------------------
### Implement TypeScript Types for Autocomplete Results
Source: https://context7.com/appandflow/react-native-google-autocomplete/llms.txt
Provides the interface definitions for GoogleLocationResult and GoogleLocationDetailResult. These types ensure type safety when handling search results and detailed place information returned by the hook.
```typescript
import {
useGoogleAutocomplete,
GoogleLocationResult,
GoogleLocationDetailResult
} from '@appandflow/react-native-google-autocomplete';
function TypedLocationSearch() {
const { locationResults, searchDetails } = useGoogleAutocomplete('YOUR_API_KEY');
const handleResult = (result: GoogleLocationResult) => {
console.log(result.structured_formatting.main_text);
};
const handleDetails = async (details: GoogleLocationDetailResult) => {
const { lat, lng } = details.geometry.location;
console.log(`Location: ${lat}, ${lng}`);
};
return null;
}
```
--------------------------------
### Google Location Detail Result Interface (JavaScript)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
Defines the structure of a Google Location Detail Result object, typically obtained after selecting a specific location. It includes comprehensive address details, place name, coordinates, and associated components. This is useful for displaying detailed information about a selected place.
```javascript
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[];
}>;
}
```
--------------------------------
### Google Location Result Interface (JavaScript)
Source: https://github.com/appandflow/react-native-google-autocomplete/blob/main/README.md
Defines the structure of a Google Location Result object returned by the autocomplete search. This interface includes properties like description, ID, matched substrings, place ID, and structured formatting. The maximum number of results is limited to 5 per query by Google.
```javascript
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
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.