Giter VIP home page Giter VIP logo

react-native-google-places-autocomplete's Introduction

npm version

Google Maps Search Component for React Native

Customizable Google Places autocomplete component for iOS and Android React-Native apps

Sponsor



The financial management super app for expenses, corporate cards, and more.

Click to learn more

Preview

Installation

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 Example

Basic Address Search

import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
      }}
    />
  );
};

export default GooglePlacesInput;

You can also try the basic example in a snack here

More Examples

Get Current Location

Click to expand

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 />.

import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

// navigator.geolocation = require('@react-native-community/geolocation');
// navigator.geolocation = require('react-native-geolocation-service');

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
      }}
      currentLocation={true}
      currentLocationLabel='Current location'
    />
  );
};

export default GooglePlacesInput;

Search with predefined option

Click to expand
import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const homePlace = {
  description: 'Home',
  geometry: { location: { lat: 48.8152937, lng: 2.4597668 } },
};
const workPlace = {
  description: 'Work',
  geometry: { location: { lat: 48.8496818, lng: 2.2940881 } },
};

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
      }}
      predefinedPlaces={[homePlace, workPlace]}
    />
  );
};

export default GooglePlacesInput;

Limit results to one country

Click to expand
import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
        components: 'country:us',
      }}
    />
  );
};

export default GooglePlacesInput;

Use a custom Text Input Component

Click to expand

This is an example using the Text Input from react-native-elements.

import React from 'react';
import { Text, View, Image } from 'react-native';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import { Input } from 'react-native-elements';

const GOOGLE_PLACES_API_KEY = 'YOUR_GOOGLE_API_KEY';

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      query={{
        key: GOOGLE_PLACES_API_KEY,
        language: 'en', // language of the results
      }}
      onPress={(data, details) => console.log(data, details)}
      textInputProps={{
        InputComp: Input,
        leftIcon: { type: 'font-awesome', name: 'chevron-left' },
        errorStyle: { color: 'red' },
      }}
    />
  );
};

export default GooglePlacesInput;

Props

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

Methods

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.

Example

import React, { useEffect, useRef } from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const GooglePlacesInput = () => {
  const ref = useRef();

  useEffect(() => {
    ref.current?.setAddressText('Some Text');
  }, []);

  return (
    <GooglePlacesAutocomplete
      ref={ref}
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
      }}
    />
  );
};

export default GooglePlacesInput;

Styling

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)

Example

<GooglePlacesAutocomplete
  placeholder='Enter Location'
  minLength={2}
  autoFocus={false}
  returnKeyType={'default'}
  fetchDetails={true}
  styles={{
    textInputContainer: {
      backgroundColor: 'grey',
    },
    textInput: {
      height: 38,
      color: '#5d5d5d',
      fontSize: 16,
    },
    predefinedPlacesDescription: {
      color: '#1faadb',
    },
  }}
/>

Default Styles

{
  container: {
    flex: 1,
  },
  textInputContainer: {
    flexDirection: 'row',
  },
  textInput: {
    backgroundColor: '#FFFFFF',
    height: 44,
    borderRadius: 5,
    paddingVertical: 5,
    paddingHorizontal: 10,
    fontSize: 15,
    flex: 1,
  },
  poweredContainer: {
    justifyContent: 'flex-end',
    alignItems: 'center',
    borderBottomRightRadius: 5,
    borderBottomLeftRadius: 5,
    borderColor: '#c8c7cc',
    borderTopWidth: 0.5,
  },
  powered: {},
  listView: {},
  row: {
    backgroundColor: '#FFFFFF',
    padding: 13,
    height: 44,
    flexDirection: 'row',
  },
  separator: {
    height: 0.5,
    backgroundColor: '#c8c7cc',
  },
  description: {},
  loader: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    height: 20,
  },
}

Web Support

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.

Example:

import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const GooglePlacesInput = () => {
  return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
        // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}
      query={{
        key: 'YOUR API KEY',
        language: 'en',
      }}
      requestUrl={{
        useOnPlatform: 'web', // or "all"
        url:
          'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api', // or any proxy server that hits https://maps.googleapis.com/maps/api
        headers: {
          Authorization: `an auth token`, // if required for your proxy
        },
      }}
    />
  );
};

export default GooglePlacesInput;

Note: The library expects the same response that the Google Maps API would return.

Features

  • Places autocompletion
  • iOS and Android compatibility
  • Places details fetching + ActivityIndicatorIOS/ProgressBarAndroid loaders
  • Customizable using the styles parameter
  • XHR cancellations when typing fast
  • Google Places terms compliant
  • Predefined places
  • typescript types
  • Current location

Compatibility

This library does not use the iOS, Android or JS SDKs from Google. This comes with some Pros and Cons.

Pros:

  • smaller app size
  • better privacy for your users (although Google still tracks server calls)
  • no need to keep up with sdk updates

Cons:

  • the library is not compatible with a Application key restrictions
  • doesn't work directly on the web without a proxy server
  • any Google API change can be a breaking change for the library.

Use Inside a <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).

A word about the Google Maps APIs

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:

  • Place Autocomplete - automatically fills in the name and/or address of a place as users type.
  • Place Details - returns more detailed information about a specific place (using a place_id that you get from Place Search, Place Autocomplete, or Query Autocomplete).
  • Place Photos - provides access to the millions of place-related photos stored in Google's Place database (using a reference_id that you get from Place Search, Place Autocomplete, or Query Autocomplete).
  • Place Search - returns a list of places based on a user's location or search string.
  • Query Autocomplete - provides a query prediction service for text-based geographic searches, returning suggested queries as users type.

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.

Which APIs does this library use?

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.

  1. Autocomplete -> query (options)
  2. Place Details -> GooglePlacesDetailsQuery (options)
  3. Nearby Search -> GooglePlacesSearchQuery (options)
  4. Geocode -> 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.

Changelog

Please see the releases tab for the changelog information.

License

MIT

Authors

react-native-google-places-autocomplete's People

Contributors

alonp99 avatar aryk avatar ashuvssut avatar bell-steven avatar davidstoker avatar esganzerla avatar faridsafi avatar grabcode avatar grifotv avatar gstcarv avatar guilhermepontes avatar halilb avatar hashamali avatar jamesa3 avatar jamesone avatar jmpridgen avatar kanerogers avatar moiseshilario avatar oliveroneill avatar parasharrajat avatar rgordon95 avatar robert-nash avatar shubham1206agra avatar situchan avatar strdr4605 avatar vitorebatista avatar vond avatar waqas19921 avatar willham12 avatar zaidqureshi2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-google-places-autocomplete's Issues

How to close the autocomplete dropdown?

I have a scenario, where the user can input something in the textbox and he can:

  • choose something from the dropdown (works ok)
  • not choose anything and type his own custom text (not sure how to close the dropdown with suggestions without clicking on any of the suggestions)

I can easily write a PR to solve this, by adding a onEditingEnd prop on TextInput and setting the state.listViewDisplayed to false. Does this sound okay, should I make a PR? I can also do that all this is enabled when setting a prop to the GooglePlacesAutocomplete, to keep backwards compatibility.

How to return current location?

Given the lack of explicit documentation, I would expect that when a user clicks on the Current Location item, the module would return, calling this.props.onPress, just like it does with predefined and autocomplete'd rows. Instead what happens is that it refreshes the list with new data.

I don't get this. Isn't the user clicking on Current Location to use that as the "place"? More to the point, how can I get the module to do what I want โ€” should I just fork the project and use my own version or perhaps, if you like this functionality, I could write it in a way suitable to be incorporated.

Xcode Build

Hello,

i have the following error in Xcode when i build to the device or when a try to create an archive:

ld: library not found for -lRNGooglePlaces
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Is there not a rnpm link to do?

Thx.

Controlled text input

Hi.

Fox example, I would like to control the value of textInput manually. But as I understand It is not possible.

Add clear text method

It'll be nice to have clear text method that also closes the listView.

Thanks!

BTW
I tried to create a pull request but I'm not authorized

Remove separator from the last item in the list.

Hi,

Thanks for this very useful component. I'm trying to figure out 2 things:

  1. How to remove the seperator after the last item in the list.
  2. I'm assuming clearButtonMode will need to be implemented manually for android. Is this correct? Any suggestions?

Thank you.

Autocomplete not working after upgrade to React Native 0.38

Hi guys,
This component stopped working on our app after we upgraded to React Native 0.38. Nothing else is changed. Is there any new setting we need to cater for after upgrade? Here's our code if it helps, pretty standard:

import React, {Component} from 'react';
import {View, MapView, WebView, Text} from 'react-native'
//import WebViewBridge from 'react-native-webview-bridge';
var {GooglePlacesAutocomplete} = require('react-native-google-places-autocomplete');




const injectScript = `
  (function () {
    if (WebViewBridge) {
        WebViewBridge.onMessage = function (message) {                       
        };
    }
    }());
`;

var self;

class LocationSearch extends Component {
    constructor(props) {
        super(props);
        
    }
    componentDidMount() {
        self = this;
    }
    
    render() {
        var route = this.props.navigator.getCurrentRoutes(0);
        searchlocation = route[route.length - 1].positionToSearch;  
        var stringSearchLocation= searchlocation.coords.latitude +', ' + searchlocation.coords.longitude;        
        return (
            <View style={{marginTop:60}}>
                <GooglePlacesAutocomplete
                    placeholder='Search'
                    minLength={2}
                    autoFocus={false}
                    fetchDetails={true}
                    onPress={(data, details = null) => {                     
                        self.props.callBack(details);
                        self.props.navigator.pop();                     
                    } }                  
                    query={{
                        // available options: https://developers.google.com/places/web-service/autocomplete
                        key: 'AIzaSyCJzwLTQ4ADlEr2vftLexbX2xY81hO9yq0',
                        language: 'en', // language of the results   
                        location: stringSearchLocation,
                        radius:5000                     
                    }}
                    styles={{
                        description: {
                            fontWeight: 'bold',
                        },
                        predefinedPlacesDescription: {
                            color: '#1faadb',
                        },
                    }}

                    currentLocation={false} // Will add a 'Current location' button at the top of the predefined places list
                    currentLocationLabel="Current location"
                    nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
                    GoogleReverseGeocodingQuery={{
                        // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
                    }}
                    GooglePlacesSearchQuery={{
                        // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                        rankby: 'distance',
                        types: 'food',
                    }}
                    filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}
                    
                    />
            </View>
        );
    }
}

module.exports = LocationSearch;

Filter by country

Hi,

I'm interested in restricting search to a country. Is this possible using this plugin?

Thanks
Tim

Setting a predefined place in the search text box

Hi,

Is't possible to set a predefined place in the search text box,

Why i need this?

If the user want to edit his choice of picking place, I want to load the old place in the search text box, I can load the old option to the list like current location, but i prefer to add it to the search text box.

Thanks

app crashes

app crashes...

view <RCTShadowView: 0x100637400; viewName: RCTTextField; reactTag: 1799; frame: {{8, 8}, {398, 28}}> (tag #1799) is not a descendant of <RCTShadowView: 0x1062935b0; viewName: RCTView; reactTag: 1695; frame: {{0, 0}, {394, 784.66666666666663}}> (tag #1695)

RCTMeasureLayout + 400
RCTUIManager.m:1269
-[RCTUIManager measureLayout:relativeTo:errorCallback:callback:] + 292
+ 144
+ 284
+ 60
-[RCTModuleMethod invokeWithBridge:module:arguments:] + 1684
-[RCTBatchedBridge _handleRequestNumber:moduleID:methodID:params:] + 712
__33-[RCTBatchedBridge handleBuffer:]_block_invoke.452 + 1144
_dispatch_call_block_and_release + 24
_dispatch_client_callout + 16
_dispatch_queue_drain + 1036
_dispatch_queue_invoke + 464
_dispatch_root_queue_drain + 760
_dispatch_worker_thread3 + 132
_pthread_wqthread + 1092
start_wqthread + 4

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I am getting this error:-
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is my code:--

// @flow
'use strict';

import React, { Component } from 'react';
import {
View
} from 'react-native';
import GooglePlacesAutocomplete from 'react-native-google-places-autocomplete';
import { Actions } from 'react-native-router-flux';

// Styles
import * as googlePlacesStyle from '../googleplaces/style';

export default class GooglePlacesScene extends Component {

  state: {
    homePlace?: {
        description: string,
        geometry: {
            location: {
                lat: number,
                lng: number
            }
        }
    },
    workPlace?: {
        description: string,
        geometry: {
            location: {
                lat: number,
                lng: number
            }
        }
    }
};

constructor(props: {}) {
    super(props);

    this.state = {  homePlace: { description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 }}},
                    workPlace: {description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }}};
}

render() {
    return(
     <View style={googlePlacesStyle.bodyStyle}>
         <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2}
            autoFocus={false}
            fetchDetails={true}
            onPress={(data, details = null) => {
                console.log(data);
                console.log(details);
            }}
            getDefaultValue={() => {
                return ''; // text input default value
            }}
            query={{
                key: 'ALaiPuRiT3eyqE9CDhjjklAD2179Pw1uRoeVfBq',
                language: 'en',
                types: '(cities)',
            }}
            styles={{description: {
                fontWeight: 'bold',
            },
            predefinedPlacesDescription: {
                color: '#1faadb',
            },
        }}
        currentLocation={true}
        currentLocationLabel="Current location"
        nearbyPlacesAPI='GooglePlacesSearch'
        GoogleReverseGeocodingQuery={{
        }}
        GooglePlacesSearchQuery={{
            rankby: 'distance',
            types: 'food',
        }}
        filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}
        predefinedPlaces={[this.state.homePlace, this.state.workPlace]}
       />

    </View>
    );
}

}

Get geolocation

I'm trying to get the geolocation for the selected place, but it seems I'm not receiving it.

Can anyone give me a help with that?

Thanks!

Use iOS/Android key instead of web

Is there any way of changing this library to use the iOS/Android keys? Right as is we have to set our web key to allow incoming requests from anywhere. Someone can easily obtain our key by sniffing traffic and use our key however they like which is quite insecure. Not sure what would all be involved, but I imagine there's some native code which would be needed in order to make this happen.

Making establishment type work?

I can't get to make the establishment type to work. Cities work while establishment doesn't how come see code and screenshot below:

Screenshot here http://screencast.com/t/Xx9xXgqaZYzb


  <GooglePlacesAutocomplete
        placeholder='Establishments Name'
        minLength={0} // minimum length of text to search
        autoFocus={false}
        fetchDetails={false}
        enablePoweredByContainer={false}
        onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
          console.log(data);
          console.log(details);
        }}
        getDefaultValue={(value) => {
          return ''
          // this.props.onDefaultValue(value) // text input default value
        }}
        query={{
          // available options: https://developers.google.com/places/web-service/autocomplete
          key: 'AIza--------------------key',
          language: 'en', // language of the results
          types: '(establishment)', // default: 'geocode'
        }}
        styles={{
          description: {
            fontWeight: 'bold',
          },
          predefinedPlacesDescription: {
            color: '#1faadb',
          },
        }}
        listViewDisplayed={true}
        nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
        GoogleReverseGeocodingQuery={{
          // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
        }}
        GooglePlacesSearchQuery={{
          // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
          rankby: 'distance',

        }}

        currentLocation={false}
        filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities


      />

Special characters break the request.

Hi,

It appears that if you use a hash # in your query then it breaks the input.

Why would I want a hash in the lookup? In Colombia the addresses are in the following format: Calle 11 #220-25. The hash is needed to look up the address.

Quick look at the code and you appear to be using encodeURI() to encode special chars before submitting. This function encodes special characters, except: , / ? : @ & = + $ #. There is an alternative encodeURIComponent() which also encodes those ones.

Happy to to submit a PR if you like otherwise a quick swap out should sort it.

Thanks for your hard work,

Sam

Not working in react-native 0.34

After upgrading to RN 0.34 the package won't work for me. The search page appears, but as soon as I type in the search box warnings are logged: "google places autocomplete: This API project was not found. This API project may have been deleted".

I've only tested in the iOS simulator (iOS 10, iPhone 6).

Any suggestions?

"dependencies": {
"moment": "^2.14.1",
"react": "^15.3.2",
"react-native": "^0.34.1",
"react-native-button": "^1.6.0",
"react-native-drawer": "^2.2.6",
"react-native-google-places-autocomplete": "^1.2.4",
"realm": "^0.14.3",
"underscore": "^1.8.3"
}

How to override methods

Hi!
Can you explain please, how to override your methods (for example, _onPress), when I use your component in my project, and want to change some features?

Address

Is it possible to return address instead cities? I need to use autocomplete for retrieve a complete address. Can anyone help me?

Problem with click on item, on the first click

Firstable, Great plugin!
Buth, when i click on item after typing some city, i click on the item but the cb is not go to call back.
Instead is just go and blur the window typing.
Just if i click again on the item, the cb work.

I am using this plugin inside ScrollView

[Help] GoogleAutoComplete avoid keyboard

Hi @FaridSafi great component. I have the component inside a form in a ListView. I am wanting to push the component above the keyboard on iOS. I've tried using the KeyboardAvoidingView with no luck. Any advice on accomplishing this? Thanks

react-native 0.35.0
react-native-google-places-autocomplete 1.2.6

Extracting Place_id

With the api, is there a method in which I can extract the Place_id (id of the address) or the longitude and latitude once creating the GooglePlacesAutocomplete component? Looking at the src code, it is called several times, but I was wondering if I can explicitly retrieve the values of it after creating the component.

Reverse Geocoding with any location?

Hello @myaskevich ,

With the current implementation, it seems like you can only do reverse geocoding with the current location, but is there a way to do reverse geocoding with a given place_id or longitude and latitude?

Thank you!

Losing focus when typing

Do we get a workaround so we don't lose focus on the search bar when showing new update to listview of results?

rankBy distance not working

 GooglePlacesSearchQuery={{ 
                                rankby: 'distance', 
                                types: 'street_address',
                                location: 34.8083336+','+32.1579631,
                            }} 

Not working, Also I have traced your code, _requestNearby never called on change text which support to get ranked result

Element type is invalid: expected a string (for built-in components)...Check the render method of 'StaticRenderer'.

Hi, Here is my code:

'use strict';

import React, { Component } from 'react';

import { connect } from 'react-redux';
import polyline from 'polyline';

import {BlurView} from 'react-native-blur';
import LoadingOverlay from '../LoadingOverlay';
import AwesomeButton from 'react-native-awesome-button';

import { Image, View, Dimensions, Platform, StatusBar, Switch, Slider, DatePickerIOS, Picker, PickerIOS, ProgressViewIOS } from 'react-native';
import {GooglePlacesAutocomplete} from 'react-native-google-places-autocomplete';

....

                       <GooglePlacesAutocomplete
                            placeholder='From Location'
                            minLength={2} // minimum length of text to search
                            autoFocus={false}
                            fetchDetails={true}
                           
                            onPress={(data, details = null) => { 
                              console.log("googleplaces");
                              console.log(details);
                              this.setState({fromLocation:details.name});
                              this.setState({fromLatitude:details.geometry.location.lat});
                              this.setState({fromLongtitude:details.geometry.location.lng});
                              console.log("checking from long");
                              console.log(this.state.fromLatitude,this.state.fromLongtitude);
                              this.setState({ fromCoordinates: [parseFloat(details.geometry.location.lat),parseFloat(details.geometry.location.lng) ]});
                              
                              console.log("checking parseFloat:");
                              console.log(parseFloat(details.geometry.location.lat), parseFloat(details.geometry.location.lng));
                              
                              this._map && this._map.setCenterCoordinateZoomLevel(parseFloat(details.geometry.location.lat), parseFloat(details.geometry.location.lng),13);
                              this.setState({ annotations: [{
                                                      coordinates: this.state.fromCoordinates,
                                                      type: 'point',
                                                      title: this.state.fromLocation,
                                                      fillAlpha: 1,
                                                      fillColor: '#000000',
                                                      strokeAlpha: 1,
                                                      subtitle: 'It has a rightCalloutAccessory too',
                                                      // rightCalloutAccessory: {
                                                      //   source: { uri: 'https://cldup.com/9Lp0EaBw5s.png' },
                                                      //   height: 50,
                                                      //   width: 50
                                                      // }, 
                                                      id: 'marker1'
                                                    }]});
                              
                              

                              



                            }}
                            getDefaultValue={() => {
                              return ''; // text input default value
                            }}
                            query={{
                              // available options: https://developers.google.com/places/web-service/autocomplete
                              key: 'AIzaSyCx4LyiTDnAAgJLnSeVSVKR3uAQPsslXxg',
                              language: 'en', // language of the results
                              
                            }}
                             styles={{
                              textInputContainer: {
                                backgroundColor: '#fff',
                                borderTopWidth: 1,
                                borderBottomWidth:1,
                                 borderRadius: 20,
                                 borderColor: '#000',
                                 borderLeftColor: '#000',
                                 borderRightColor: '#000',
                                 borderTopColor: '#000',
                                 borderBottomColor: '#000',
                                 borderLeftWidth: 1,
                                 borderRightWidth: 1,
                                 color: 'black',

                              },

                              textInput: {
                              backgroundColor: '#fff',
                              color: 'black',
                              
                              },
                              
                              
                              description: {
                                 backgroundColor: '#fff',
                                fontWeight: 'bold',
                              },
                              predefinedPlacesDescription: {
                                color: '#1faadb',
                              }, 
                              listView:{
                                backgroundColor: '#fff',
                              },
                              poweredContainer: {
                           
                                borderRadius: 30,

                              },
                              container:{
                                
                                 borderRadius: 30,
                                 borderRightRadius: 25,
                                 borderLeftRadius: 25,
                                 borderBottomRadius: 25,
                                 flex: 3,
                                 marginLeft: 30, marginRight:30,

                              
                            },
                          }}
                            enablePoweredByContainer = {false}
                              // Will add a 'Current location' button at the top of the predefined places list
                            currentLocationLabel="Current location"
                            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
                            GoogleReverseGeocodingQuery={{
                              // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
                            }}
                            GooglePlacesSearchQuery={{
                              // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                              rankby: 'distance',
                              types: 'food',
                            }}


                            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}  > 
                        </GooglePlacesAutocomplete>
                        
                    </View>
                    <View style={{padding: 10}}>
                   
                        <GooglePlacesAutocomplete
                            placeholder='To Location'
                            minLength={2} // minimum length of text to search
                            autoFocus={false}
                            fetchDetails={true}
                           
                            onPress={(data, details = null) => { 
                              console.log("googleplaces");
                              console.log(details);
                              this.setState({toLocation:details.name});
                              this.setState({toLatitude:details.geometry.location.lat});
                              this.setState({toLongtitude:details.geometry.location.lng});
                               this.setState({ toCoordinates: [parseFloat(details.geometry.location.lat),parseFloat(details.geometry.location.lng) ]});
                              
                              console.log("checking parseFloat:");
                              console.log(parseFloat(details.geometry.location.lat), parseFloat(details.geometry.location.lng));
                              
                              
                              this._map && this._map.setVisibleCoordinateBounds(parseFloat(this.state.fromLatitude), parseFloat(this.state.fromLongtitude), parseFloat(this.state.toLatitude), parseFloat(this.state.toLongtitude), 100, 100, 100, 100);
                               this.drawRoute();
                            
                            this._map && this._map.selectAnnotation("marker1",false);
                            this._map && this._map.selectAnnotation("marker2",false);
                              }}
                            getDefaultValue={() => {
                              return ''; // text input default value
                            }}
                            query={{
                              // available options: https://developers.google.com/places/web-service/autocomplete
                              key: 'AIzaSyCx4LyiTDnAAgJLnSeVSVKR3uAQPsslXxg',
                              language: 'en', // language of the results
                              
                            }}
                            styles={{
                              textInputContainer: {
                                backgroundColor: '#fff',
                                borderTopWidth: 1,
                                borderBottomWidth:1,
                                 borderRadius: 20,
                                 borderColor: '#000',
                                 borderLeftColor: '#000',
                                 borderRightColor: '#000',
                                 borderTopColor: '#000',
                                 borderBottomColor: '#000',
                                 borderLeftWidth: 1,
                                 borderRightWidth: 1,
                                 color: 'black',

                              },

                              textInput: {
                              backgroundColor: '#fff',
                              color: 'black',
                              
                              },
                              
                              
                              description: {
                                 backgroundColor: '#fff',
                                fontWeight: 'bold',
                              },
                              predefinedPlacesDescription: {
                                color: '#1faadb',
                              }, 
                              listView:{
                                backgroundColor: '#fff',
                              },
                              poweredContainer: {
                            
                                borderRadius: 30,

                              },
                              container:{
                                
                                 borderRadius: 30,
                                 borderRightRadius: 25,
                                 borderLeftRadius: 25,
                                 borderBottomRadius: 25,
                                 flex: 3,
                                 marginLeft: 30, marginRight:30,

                              
                            },
                          }}

                            enablePoweredByContainer = {false}
                              // Will add a 'Current location' button at the top of the predefined places list
                            currentLocationLabel="Current location"
                            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
                            GoogleReverseGeocodingQuery={{
                              // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
                            }}
                            GooglePlacesSearchQuery={{
                              // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                              rankby: 'distance',
                              types: 'food',
                            }}


                            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}  > 
                        </GooglePlacesAutocomplete>

How add custom value to textInput when press on cell

It seems that the getDefaultValue only runs once and it does not help me when I put my custom state on that property.

I'm test too with textInputProps sending onChangeText function, but it's no good, because when the _onPress is executed it is forced to take the value of rowData.description and I lose control over that state. code here.

I would like to know if there is a way to achieve this and if it is not possible, then I would appreciate it being implemented for an upcoming version

Custom styling of TextInput and result list

Great job with this plugin.
I don't know whether custom styling is possible in this yet or not? If yes it would be pretty helpful if you can put this in documentation on how to do it.
i simply tried to put autoCorrect to false by putting "autoCorrect:false," into textInput style but got the invalid props.style key autoCorrect supplied to TextInput.

Fallback or Cancel

Is there a way to cancel or make the list hide back , I can't seem to find a way other than to tap one of the list options of the auto complete.

Circular indeterminate `ProgressBarAndroid`is deprecated. Use `ActivityIndicator` instead.

On android, RN 0.31.0 with fetchDetails={true}, I get the following error - Circular indeterminate ProgressBarAndroidis deprecated. Use ActivityIndicator instead.

Proposed solution - Remove the condition that returns the ProgressBarAndroid component in _getRowLoader() in GooglePlacesAutocomplete.js.

I can submit a PR for this, just wanted to get a contributors ok/opinion first.

Fetch details of place too?

Hi, Farid!

Thanks again for making such a wonderful, useful component!

Would you like to add an option to fetch the details of the place via the Google Place Details API? I'm about to implement this myself in my application code, but figured this might be helpful to the library as well.

If necessary, it could be hidden behind a fetchDetails flag, if you don't want this to be the default behaviour.

Let me know if you're interested! ๐Ÿ˜ธ

RN 0.13 support

This was working fine with RN 0.12 in both iOS and Android.

Now, after upgrading to RN 0.13, when selecting an item it is not closing the list and showing the selected item on the textView. When selecting again the list closes but textView is still empty.

Restrict Country

Hello,

I'm searching for how to restrict country scope for search.
i've made this in query prop but it's not working : components: {country :"us"}

Timeout on android

It seems that android has some problems while getting current position. iOS has no problems but android goes in timeout.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.