Reputation: 1138
react-native-google-places-autocomplete is not working, I am facing multiple issues 1. the places drop down is not showing up 2. onPress handler is not triggered at all
Note: all google location apis are enabled , google maps api, places api and geocode api are enabled and a valid api key is given.
I tried all possible solutions available in internet 1. setting zIndex: 1000 a high value to avoid it being hidden behind some other view 2. Tried creating new RN App and added only this component to keep the project clean 3. Referred other SO post and tried to fix it
here the code snippet
<GooglePlacesAutocomplete
placeholder="Search"
minLength={2} // minimum length of text to search
autoFocus={false}
fetchDetails={true}
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
console.log(data);
console.log(details);
}}
getDefaultValue={() => {
return ''; // text input default value
}}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'VALID_API_KEY',
language: 'en', // language of the results
}}
styles={{
description: {
fontWeight: 'bold',
},
predefinedPlacesDescription: {
color: '#1faadb',
},
listView: {
color: 'black', //To see where exactly the list is
zIndex: 1000, //To popover the component outwards
position: 'absolute',
top: 45
},
}}
currentLocation={true} // 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
}
}
GooglePlacesDetailsQuery={{
// available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
fields: 'formatted_address',
}}
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
predefinedPlaces={[homePlace, workPlace]}
predefinedPlacesAlwaysVisible={true}
/>
Upvotes: 13
Views: 31653
Reputation: 78
you must add this keyboardShouldPersistTaps="handled"
on all ancestors or
as mentioned on Documentation
Upvotes: 0
Reputation: 1
use this code and enjoy it
import React, {useState} from 'react';
import {
TouchableOpacity,
ScrollView,
StyleSheet,
FlatList,
View,
Dimensions,
} from 'react-native';
import CustomInput from './CustomInput';
import CustomText from './CustomText';
import {Images} from '../assets/images';
import {Colors} from '../utils/colors';
import {fonts} from '../assets/fonts';
const {width} = Dimensions.get('window');
const GooglePlaces = ({value, setValue}) => {
const [searchQuery, setSearchQuery] = useState('');
const [predictions, setPredictions] = useState([]);
const handleSearch = async text => {
setSearchQuery(text);
try {
const apiKey = 'GOOGLE_API_KEY';
const response = await fetch(
`https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${apiKey}&input=${text}`,
);
const data = await response.json();
if (data.predictions) {
setPredictions(data.predictions);
}
} catch (error) {
console.error('Error fetching predictions', error);
}
};
const handlePredictionPress = item => {
setValue(item.description);
setSearchQuery(item.description);
setPredictions([]);
};
return (
<View>
<CustomInput
icon={Images.location}
placeholder="Address"
value={searchQuery}
marginBottom={predictions?.length ? 0.1 : 20}
onChangeText={text => handleSearch(text)}
/>
<ScrollView showsHorizontalScrollIndicator={false} horizontal>
<FlatList
data={predictions}
keyExtractor={(_, i) => i.toString()}
renderItem={({item, index}) => (
<TouchableOpacity
style={[
styles.itemContainer,
{
borderBottomColor:
predictions?.length - 1 == index
? 'transparent'
: Colors.grayBorder,
borderBottomWidth: predictions?.length - 1 == index ? 0 : 1,
},
]}
onPress={() => handlePredictionPress(item)}>
<CustomText
fontFamily={fonts.semiBold}
fontSize={12}
label={item.description}
/>
</TouchableOpacity>
)}
/>
</ScrollView>
</View>
);
};
export default GooglePlaces;
const styles = StyleSheet.create({
itemContainer: {
paddingVertical: 10,
paddingHorizontal: 5,
width: width,
},
});
Upvotes: -1
Reputation: 101
After hours of checking auto complete not showing results, just tested the key like described here and find out this response error
"error_message" : "The provided API key is invalid."
replacing the key solve my issue.
Make sure to replace your key when testing it.
key=YOUR_API_KEY
Upvotes: 0
Reputation: 1
i added the line below to my code and it worked.
listViewDisplayed={true}
THIS THE CODE I USED
<View style={tw`p-5 `}>
<GooglePlacesAutocomplete
placeholder='Where From?'
styles={{
container: {
flex: 0,
},
textInput: {
fontSize: 18,
},
}}
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
console.log(data, details);
}}
listViewDisplayed={true}
fetchDetails
query={{
key: GOOGLE_MAPS_APIKEY,
language: "en",
}} />
</View>
Upvotes: 0
Reputation: 65
I had same issue as well.
This discussion helped me a lot.
Firstly, I needed the this problem cause. Thus, I used take advantage of https://stackoverflow.com/a/62251115/13818089 this.
I saw the error from console and it says "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started". It's about billing, due to it, I enabled billing on Google Cloud.
After that, I have done step by step what it said from https://stackoverflow.com/a/75195681/13818089
And finally it works! I'm kind of excited about it. Because I'm trying to learn more react-native from free youtube videos, and sometimes I faced some different errors which is not unusual. I mean that I want to thank all of people who contributed this discussion. Thanks to you I fixed my problem, and I hope this informations help others!
Upvotes: 0
Reputation: 21
I had the same problem. My code format was this:
After all the solutions i tried nothing was working. Even though I had everything completed even the billing configuration on the google APIs, the the places drop down just wasn't showing.
So at start I reinstalled GooglePlacesAutocomplete with "yarn add react-native-google-places-autocomplete", if you have npm do the "npm i react-native-google-places-autocomplete".
Then I added these two imports again from the start:
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete"; import { GOOGLE_MAPS_APIKEY } from "@env";
Then I rewrote GooglePlacesAutocomplete & GOOGLE_MAPS_APIKEY in my code:
<GooglePlacesAutocomplete
placeholder="Where From?"
styles={{
container: {
flex: 0,
},
textInput: {
fontSize: 18,
},
}}
query={{
key: GOOGLE_MAPS_APIKEY,
language: "en",
}}
nearbyPlacesAPI="GooglePlacesSearch"
debounce={200}
/>
so they define the "new imports" and do the command "yarn install" on my project file even though it was already up to date.
Lastly, I restart my project with clean cache using the command "expo r -c". Magically, it worked!
Hope, that helps someone in the future!
Upvotes: 1
Reputation: 11
So I finally got it working. Here is a detailed solution to get it working. There are many causes and one of these might be the solution to your problem.
Make sure the project on google console has billing enabled. Note, If you just enabled the billing on the account don't forget to delete your api key and create a new one.
I don't want to post code snippet, you can find a working one under the package github repo. If your setup is done right, check to see if the input container for the input has enough space to display the list. you can achieve that by passing the code below to the style prop
{ container: { paddingTop: 20, flex: 1, backgroundColor: "white", } },
Also, check to see if the emulator has an internet connection. It sounds obvious but it can easily skip you. after going through all these steps, I FINALLY got it working
Upvotes: 0
Reputation: 45
I had the same problem, I didn't even get a list of results. Someone lied to me that this package is not working so I found other package that can be uses as an alternative
https://www.npmjs.com/package/react-native-places-input
Upvotes: 0
Reputation: 23
Like Larry DaBig Meech said, you need a 100% container to wrap your component. You can style one of your wrappers to this:
style={StyleSheet.absoluteFillObject}
Upvotes: 0
Reputation: 692
make sure to add fetchDetails
in the tag as show below.
<GooglePlacesAutocomplete
placeholder='Search'
onPress={(data, details = null) => {
console.log(data, details);
}}
fetchDetails
query={{
key: ' GOOGLE_MAPS_API_KEY',
language: 'en',
}}
/>
Upvotes: 0
Reputation: 1
This is what worked for me :
Upvotes: 0
Reputation: 1
Correctly API and Billing configuration on Google Cloud, but I still had problems. I wrote on input but I didn't get results, also the input lose their height. I solved this by wrapping into .
<ScrollView>
<GooglePlacesAutocomplete
placeholder='Where from?'
query={{
key: GOOGLE_MAPS_API_KEY,
language: 'en',
}}
/>
</ScrollView>
Upvotes: -2
Reputation: 161
Make sure to wrap the component in a ScrollView like below :
<ScrollView>
<GooglePlacesAutocomplete
placeholder='Search destination'
minLength={2}
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
console.log(data, details);
}}
query={{
key: mapApiKey,
language: 'en',
}}
/>
</ScrollView>
Upvotes: 15
Reputation: 11
Not sure if this can help someone but I was using this autocomplete and it was working well until I put him in a View without sizing this view
Upvotes: 1
Reputation: 164
So it turns out billing needs to be enabled for each and every API you enable, I thought enabling billing inside of Google console will work throughout all APIs.
So, MAKE SURE BILLING IS ENABLED FOR THE SPECIFIC API in this case GOOGLE PLACES API.
Upvotes: 1
Reputation: 164
You have to make sure you have the Google places API component in a container with 100% height. Mine works but then stops after a few queries don’t know why but I’ll share my solution once done ✅
Upvotes: 6
Reputation: 6668
in my case, react-native-google-places-autocomplete
uses FlatList and since I had wrapped it ScrollView
. The results were not showing up. Removing the parent ScrollView
resolved it
Upvotes: 1
Reputation: 1154
The package works and is well maintained. Your problem is that your api key is not configured properly. You don't need billing enabled either (works for me without any billing details).
In google developer console create a new api key without any restriction and see if that works (might take up to 5 mins for the key to be live). Also add
onFail={error => console.error(error)}
to the component to see the api error.
If the key works then you can try to restrict access.
Upvotes: 5
Reputation: 419
You need to activate and enable your billing on google console.
Upvotes: 1
Reputation: 161
I had the same issue with this lib, and after trying for hours, I found a solution. The problem was in the billing configuration on the google APIs. Try to configure the project where you are using key and activate billing configurations, it solved my problem. Please let me know if it works for you.
P.S. I hope this can help you.
Upvotes: 16