Gathering detailed insights and metrics for react-native-google-places-autocomplete
Gathering detailed insights and metrics for react-native-google-places-autocomplete
Gathering detailed insights and metrics for react-native-google-places-autocomplete
Gathering detailed insights and metrics for react-native-google-places-autocomplete
react-google-autocomplete
React component for google autocomplete.
react-google-places-autocomplete
Google places autocomplete input for ReactJS.
react-places-autocomplete
A React component for Google Maps Places Autocomplete
use-places-autocomplete
React hook for Google Maps Places Autocomplete.
npm install react-native-google-places-autocomplete
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,011 Stars
493 Commits
854 Forks
23 Watching
2 Branches
112 Contributors
Updated on 27 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
11.5%
13,904
Compared to previous day
Last week
11.3%
67,194
Compared to previous week
Last month
1.6%
266,154
Compared to previous month
Last year
44.1%
2,794,154
Compared to previous year
4
1
Customizable Google Places autocomplete component for iOS and Android React-Native apps
The financial management super app for expenses, corporate cards, and more.
Click to learn more
Step 1.
npm install react-native-google-places-autocomplete --save
or
yarn add react-native-google-places-autocomplete
Step 2.
Get your Google Places API keys and enable "Google Places API Web Service" (NOT Android or iOS) in the console. Billing must be enabled on the account.
Step 3.
Enable "Google Maps Geocoding API" if you want to use GoogleReverseGeocoding for Current Location
Basic Address Search
1import React from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4const GooglePlacesInput = () => { 5 return ( 6 <GooglePlacesAutocomplete 7 placeholder='Search' 8 onPress={(data, details = null) => { 9 // 'details' is provided when fetchDetails = true 10 console.log(data, details); 11 }} 12 query={{ 13 key: 'YOUR API KEY', 14 language: 'en', 15 }} 16 /> 17 ); 18}; 19 20export default GooglePlacesInput;
You can also try the basic example in a snack here
Get Current Location
Extra step required!
If you are targeting React Native 0.60.0+ you must install either @react-native-community/geolocation
(link) or react-native-geolocation-service
(link).
Please make sure you follow the installation instructions there and add navigator.geolocation = require(GEOLOCATION_PACKAGE)
somewhere in you application before <GooglePlacesAutocomplete />
.
1import React from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4// navigator.geolocation = require('@react-native-community/geolocation'); 5// navigator.geolocation = require('react-native-geolocation-service'); 6 7const GooglePlacesInput = () => { 8 return ( 9 <GooglePlacesAutocomplete 10 placeholder='Search' 11 onPress={(data, details = null) => { 12 // 'details' is provided when fetchDetails = true 13 console.log(data, details); 14 }} 15 query={{ 16 key: 'YOUR API KEY', 17 language: 'en', 18 }} 19 currentLocation={true} 20 currentLocationLabel='Current location' 21 /> 22 ); 23}; 24 25export default GooglePlacesInput;
Search with predefined option
1import React from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4const homePlace = { 5 description: 'Home', 6 geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }, 7}; 8const workPlace = { 9 description: 'Work', 10 geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }, 11}; 12 13const GooglePlacesInput = () => { 14 return ( 15 <GooglePlacesAutocomplete 16 placeholder='Search' 17 onPress={(data, details = null) => { 18 // 'details' is provided when fetchDetails = true 19 console.log(data, details); 20 }} 21 query={{ 22 key: 'YOUR API KEY', 23 language: 'en', 24 }} 25 predefinedPlaces={[homePlace, workPlace]} 26 /> 27 ); 28}; 29 30export default GooglePlacesInput;
Limit results to one country
1import React from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4const GooglePlacesInput = () => { 5 return ( 6 <GooglePlacesAutocomplete 7 placeholder='Search' 8 onPress={(data, details = null) => { 9 // 'details' is provided when fetchDetails = true 10 console.log(data, details); 11 }} 12 query={{ 13 key: 'YOUR API KEY', 14 language: 'en', 15 components: 'country:us', 16 }} 17 /> 18 ); 19}; 20 21export default GooglePlacesInput;
Use a custom Text Input Component
This is an example using the Text Input from react-native-elements
.
1import React from 'react'; 2import { Text, View, Image } from 'react-native'; 3import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 4import { Input } from 'react-native-elements'; 5 6const GOOGLE_PLACES_API_KEY = 'YOUR_GOOGLE_API_KEY'; 7 8const GooglePlacesInput = () => { 9 return ( 10 <GooglePlacesAutocomplete 11 query={{ 12 key: GOOGLE_PLACES_API_KEY, 13 language: 'en', // language of the results 14 }} 15 onPress={(data, details) => console.log(data, details)} 16 textInputProps={{ 17 InputComp: Input, 18 leftIcon: { type: 'font-awesome', name: 'chevron-left' }, 19 errorStyle: { color: 'red' }, 20 }} 21 /> 22 ); 23}; 24 25export default GooglePlacesInput;
This list is a work in progress. PRs welcome!
Prop Name | type | description | default value | Options |
---|---|---|---|---|
autoFillOnNotFound | boolean | displays the result from autocomplete if the place details api return not found | false | true | false |
currentLocation | boolean | Will add a 'Current location' button at the top of the predefined places list | false | true | false |
currentLocationLabel | string | change the display label for the current location button | Current Location | Any string |
debounce | number | debounce the requests (in ms) | 0 | |
disableScroll | boolean | disable scroll on the results list | ||
enableHighAccuracyLocation | boolean | use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested. use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested. | true | |
enablePoweredByContainer | boolean | show "powered by Google" at the bottom of the search results list | true | |
fetchDetails | boolean | get more place details about the selected option from the Place Details API | false | |
filterReverseGeocodingByTypes | array | filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities | ||
GooglePlacesDetailsQuery | object | "query" object for the Google Place Details API (when you press on a suggestion) | ||
GooglePlacesSearchQuery | object | "query" object for the Google Places Nearby API (when you use current location to find nearby places) | { rankby: 'distance', type: 'restaurant' } | |
GoogleReverseGeocodingQuery | object | "query" object for the Google Geocode API (when you use current location to get the current address) | ||
isRowScrollable | boolean | enable/disable horizontal scrolling of a list result https://reactnative.dev/docs/scrollview#scrollenabled | true | |
inbetweenCompo | React.ReactNode | Insert a ReactNode in between the search bar and the search results Flatlist | ||
keepResultsAfterBlur | boolean | show list of results after blur | false | true | false |
keyboardShouldPersistTaps | string | Determines when the keyboard should stay visible after a tap https://reactnative.dev/docs/scrollview#keyboardshouldpersisttaps | 'always' | 'never' | 'always' | 'handled' |
listEmptyComponent | function | use FlatList's ListEmptyComponent prop when no autocomplete results are found. | ||
listLoaderComponent | function | show this component while results are loading. | ||
listHoverColor | string | underlay color of the list result when hovered (web only) | '#ececec' | |
listUnderlayColor | string | underlay color of the list result when pressed https://reactnative.dev/docs/touchablehighlight#underlaycolor | '#c8c7cc' | |
listViewDisplayed | string | override the default behavior of showing the list (results) view | 'auto' | 'auto' | true | false |
minLength | number | minimum length of text to trigger a search | 0 | |
nearbyPlacesAPI | string | which API to use for current location | 'GooglePlacesSearch' | 'none' | 'GooglePlacesSearch' | 'GoogleReverseGeocoding' |
numberOfLines | number | number of lines (android - multiline must be set to true) https://reactnative.dev/docs/textinput#numberoflines | 1 | |
onFail | function | returns if an unspecified error comes back from the API | ||
onNotFound | function | returns if the Google Places Details API returns a 'not found' code (when you press a suggestion). | ||
onPress | function | returns when after a suggestion is selected | ||
onTimeout | function | callback when a request timeout | ()=>console.warn('google places autocomplete: request timeout') | |
placeholder | string | placeholder text https://reactnative.dev/docs/textinput#placeholder | 'Search' | |
predefinedPlaces | array | Allows you to show pre-defined places (e.g. home, work) | ||
predefinedPlacesAlwaysVisible | boolean | Shows predefined places at the top of the search results | false | |
preProcess | function | do something to the text of the search input before a search request is sent | ||
query | object | "query" object for the Google Places Autocomplete API (link) | { key: 'missing api key', language: 'en', types: 'geocode' } | |
renderDescription | function | determines the data passed to each renderRow (search result) | ||
renderHeaderComponent | function | use the ListHeaderComponent from FlatList when showing autocomplete results | ||
renderLeftButton | function | add a component to the left side of the Text Input | ||
renderRightButton | function | add a component to the right side of the Text Input | ||
renderRow | function | custom component to render each result row (use this to show an icon beside each result). data and index will be passed as input parameters | ||
requestUrl | object | used to set the request url for the library | ||
returnKeyType | string | the return key text https://reactnative.dev/docs/textinput#returnkeytype | 'search' | |
styles | object | See styles section below | ||
suppressDefaultStyles | boolean | removes all default styling from the library | false | true | false |
textInputHide | boolean | Hide the Search input | false | true | false |
textInputProps | object | define props for the textInput, or provide a custom input component | ||
timeout | number | how many ms until the request will timeout | 20000 |
method name | type | description |
---|---|---|
getAddressText | () => string | return the value of TextInput |
setAddressText | (value: string) => void | set the value of TextInput |
focus | void | makes the TextInput focus |
blur | void | makes the TextInput lose focus |
clear | void | removes all text from the TextInput |
isFocused | () => boolean | returns true if the TextInput is currently focused; false otherwise |
getCurrentLocation | () => void | makes a query to find nearby places based on current location |
You can access these methods using a ref.
1import React, { useEffect, useRef } from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4const GooglePlacesInput = () => { 5 const ref = useRef(); 6 7 useEffect(() => { 8 ref.current?.setAddressText('Some Text'); 9 }, []); 10 11 return ( 12 <GooglePlacesAutocomplete 13 ref={ref} 14 placeholder='Search' 15 onPress={(data, details = null) => { 16 // 'details' is provided when fetchDetails = true 17 console.log(data, details); 18 }} 19 query={{ 20 key: 'YOUR API KEY', 21 language: 'en', 22 }} 23 /> 24 ); 25}; 26 27export default GooglePlacesInput;
GooglePlacesAutocomplete
can be easily customized to meet styles of your app. Pass styles props to GooglePlacesAutocomplete
with style object for different elements (keys for style object are listed below)
key | type |
---|---|
container | object (View) |
textInputContainer | object (View style) |
textInput | object (style) |
listView | object (ListView style) |
row | object (View style) |
loader | object (View style) |
description | object (Text style) |
predefinedPlacesDescription | object (Text style) |
separator | object (View style) |
poweredContainer | object (View style) |
powered | object (Image style) |
1<GooglePlacesAutocomplete 2 placeholder='Enter Location' 3 minLength={2} 4 autoFocus={false} 5 returnKeyType={'default'} 6 fetchDetails={true} 7 styles={{ 8 textInputContainer: { 9 backgroundColor: 'grey', 10 }, 11 textInput: { 12 height: 38, 13 color: '#5d5d5d', 14 fontSize: 16, 15 }, 16 predefinedPlacesDescription: { 17 color: '#1faadb', 18 }, 19 }} 20/>
1{ 2 container: { 3 flex: 1, 4 }, 5 textInputContainer: { 6 flexDirection: 'row', 7 }, 8 textInput: { 9 backgroundColor: '#FFFFFF', 10 height: 44, 11 borderRadius: 5, 12 paddingVertical: 5, 13 paddingHorizontal: 10, 14 fontSize: 15, 15 flex: 1, 16 }, 17 poweredContainer: { 18 justifyContent: 'flex-end', 19 alignItems: 'center', 20 borderBottomRightRadius: 5, 21 borderBottomLeftRadius: 5, 22 borderColor: '#c8c7cc', 23 borderTopWidth: 0.5, 24 }, 25 powered: {}, 26 listView: {}, 27 row: { 28 backgroundColor: '#FFFFFF', 29 padding: 13, 30 height: 44, 31 flexDirection: 'row', 32 }, 33 separator: { 34 height: 0.5, 35 backgroundColor: '#c8c7cc', 36 }, 37 description: {}, 38 loader: { 39 flexDirection: 'row', 40 justifyContent: 'flex-end', 41 height: 20, 42 }, 43}
Web support can be enabled via the requestUrl
prop, by passing in a URL that you can use to proxy your requests. CORS implemented by the Google Places API prevent using this library directly on the web. You will need to use a proxy server. Please be mindful of this limitation when opening an issue.
The requestUrl
prop takes an object with two required properties: useOnPlatform
and url
, and an optional headers
property.
The url
property is used to set the url that requests will be made to. If you are using the regular google maps API, you need to make sure you are ultimately hitting https://maps.googleapis.com/maps/api.
useOnPlatform
configures when the proxy url is used. It can be set to either web
- will be used only when the device platform is detected as web (but not iOS or Android, or all
- will always be used.
You can optionally specify headers to apply to your request in the headers
object.
1import React from 'react'; 2import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; 3 4const GooglePlacesInput = () => { 5 return ( 6 <GooglePlacesAutocomplete 7 placeholder='Search' 8 onPress={(data, details = null) => { 9 // 'details' is provided when fetchDetails = true 10 console.log(data, details); 11 }} 12 query={{ 13 key: 'YOUR API KEY', 14 language: 'en', 15 }} 16 requestUrl={{ 17 useOnPlatform: 'web', // or "all" 18 url: 19 'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api', // or any proxy server that hits https://maps.googleapis.com/maps/api 20 headers: { 21 Authorization: `an auth token`, // if required for your proxy 22 }, 23 }} 24 /> 25 ); 26}; 27 28export default GooglePlacesInput;
Note: The library expects the same response that the Google Maps API would return.
styles
parameterThis library does not use the iOS, Android or JS SDKs from Google. This comes with some Pros and Cons.
Pros:
Cons:
<ScrollView/>
or <FlatList/>
If you need to include this component inside a ScrolView or FlatList, remember to apply the keyboardShouldPersistTaps
attribute to all ancestors ScrollView or FlatList (see this issue comment).
Google Provides a bunch of web APIs for finding an address or place, and getting it’s details. There are the Google Places Web APIs (Place Search, Place Details, Place Photos, Place Autocomplete, Query Autocomplete) and the Google Geocode API .
The 5 Google Places Web APIs are:
The Geocoding API allows you to convert an address into geographic coordinates (lat, long) and to "reverse geocode", which is the process of converting geographic coordinates into a human-readable address.
Place Autocomplete API, Place Details API, Place Search API and the Geocoding API.
We use the Place Autocomplete API to get suggestions as you type. When you click on a suggestion, we use the Place Details API to get more information about the place.
We use the Geocoding API and the Place Search API to use your current location to get results.
Because the query parameters are different for each API, there are 4 different "query" props.
query
(options)GooglePlacesDetailsQuery
(options)GooglePlacesSearchQuery
(options)GoogleReverseGeocodingQuery
(options)Number 1 is used while getting autocomplete results.
Number 2 is used when you click on a result.
Number 3 is used when you select 'Current Location' to load nearby results.
Number 4 is used when nearbyPlacesAPI='GoogleReverseGeocoding'
is set and you select 'Current Location' to load nearby results.
Please see the releases tab for the changelog information.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
8 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 6
Reason
Found 5/13 approved changesets -- score normalized to 3
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
17 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More