react-native-google-places-autocomplete icon indicating copy to clipboard operation
react-native-google-places-autocomplete copied to clipboard

Does not work with new Places API, legacy Places API not available for new GCP projects

Open jjfattz opened this issue 9 months ago • 18 comments

New GCP projects cannot enable the legacy Places API anymore and therefore cannot use this package until it is updated to work with the new Places API.

jjfattz avatar Mar 12 '25 08:03 jjfattz

been stuck on this for 2 days now, thinking of implementing something of my own

arpu-nagar avatar Mar 13 '25 04:03 arpu-nagar

been stuck on this for 2 days now, thinking of implementing something of my own

Same here.

I saw another issue that was closed, which explains that this library calls the wrong API endpoint.

@FaridSafi / anyone planning on looking into this?

Thank you.

CandyNorth avatar Mar 15 '25 02:03 CandyNorth

yes, +1

Daniel-W1 avatar Mar 15 '25 15:03 Daniel-W1

same issue +1

Andrei21XD avatar Mar 18 '25 09:03 Andrei21XD

facing the same problem

equilizer avatar Mar 18 '25 12:03 equilizer

Same issue +1

akozy1 avatar Mar 18 '25 14:03 akozy1

Yep, not working anymore.

adamalexander avatar Mar 18 '25 18:03 adamalexander

ok, so I successfully got the link to the old places API and enabled it but it still doesn't work. google support told me to activate both the new and the old API but without any result, except for the fact that I got rid of the "(NOBRIDGE) ERROR This API project is not authorized to use this API" error. maybe you can do something with it and share the fix with us. https://console.cloud.google.com/apis/library/places-backend.googleapis.com

dvvidd7 avatar Mar 18 '25 20:03 dvvidd7

+1

MohitNarkhede avatar Mar 19 '25 10:03 MohitNarkhede

@arpu-nagar did you find any solution?

MohitNarkhede avatar Mar 19 '25 10:03 MohitNarkhede

I managed to make it work with the new Places API :

  1. I took the 2.5.7 version or the last commit from master to include this PR https://github.com/FaridSafi/react-native-google-places-autocomplete/pull/943/files#diff-c0d73f319f1167879412f6c75dcd9cc124356ef467bb09cc3874a36ce3cdecdc: packages.json: "react-native-google-places-autocomplete": "https://github.com/FaridSafi/react-native-google-places-autocomplete#master"
  2. I had to patch node_modules/react-native-google-places-autocomplete/GooglePlacesAutocomplete.js import Qs from 'qs'; +import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; (see last paragraph of https://www.npmjs.com/package/uuid)
  3. Then I used the new prop isNewPlacesAPI={true} of <GooglePlacesAutocomplete> (see the PR above)

nlarif avatar Mar 19 '25 10:03 nlarif

@nlarif and what restrictions have you put on your API key in the google cloud console?

Ramer357 avatar Mar 19 '25 18:03 Ramer357

I just allowed the existing API key of Legacy Places to be used with the new Places API: GCP Console > APIs & Services > Credentials > Your existing key > Edit API Key > API restriction > Add New Places API

nlarif avatar Mar 19 '25 20:03 nlarif

and shouldn't the request url be changed? i think there is something wrong with the request in the GooglePlacesAutocomplete.js file as the request.status is 0 (i console.logged it because it still doesn't work)

Ramer357 avatar Mar 19 '25 20:03 Ramer357

ok, so I successfully got the link to the old places API and enabled it but it still doesn't work. google support told me to activate both the new and the old API but without any result, except for the fact that I got rid of the "(NOBRIDGE) ERROR This API project is not authorized to use this API" error. maybe you can do something with it and share the fix with us.

I had the same problem. After enabling the old Places API from the link you shared and removing all restrictions from my API keys, the issue was resolved.

veyselemrearik avatar Mar 20 '25 08:03 veyselemrearik

ok, so I successfully got the link to the old places API and enabled it but it still doesn't work. google support told me to activate both the new and the old API but without any result, except for the fact that I got rid of the "(NOBRIDGE) ERROR This API project is not authorized to use this API" error. maybe you can do something with it and share the fix with us. https://console.cloud.google.com/apis/library/places-backend.googleapis.com

  • You also need to enable the following libraries to use the Old Places api:

-> Maps JavaScript API -> Geocoding API -> Geolocation API

  • Also use Separate keys for Places Api (new) and old

-> You can test the old API with this in the chrome:

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=USA&types=geocode&key=YOUR_API_KEY

-> You can test the new API in the Terminal with this:

curl -X POST -d '{
  "input": "USA"
}' \
-H 'Content-Type: application/json' -H 'X-Goog-Api-Key: YOUR_API_KEY' \
https://places.googleapis.com/v1/places:autocomplete


  • If you have the old API enabled and working fine in the chrome after testing it with the link i provided it should be fine using this library but if you insist on using the New Places API use this custom code and tweak it to your preference:
import React, {useState} from 'react';
import {
  View,
  TextInput,
  FlatList,
  Text,
  ActivityIndicator,
  TouchableOpacity,
  StyleSheet,
  SafeAreaView,
} from 'react-native';

const GOOGLE_API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key

const GooglePlacesAutocomplete = () => {
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  const [loading, setLoading] = useState(false);

  // Fetch autocomplete results
  const fetchPlaces = async (input: string) => {
    if (!input) {
      setSuggestions([]);
      return;
    }

    setLoading(true);

    try {
      const response = await fetch(
        'https://places.googleapis.com/v1/places:autocomplete',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Goog-Api-Key': GOOGLE_API_KEY,
          },
          body: JSON.stringify({input}),
        },
      );

      const data = await response.json();
      const results =
        data.suggestions?.map((s: any) => s.placePrediction.text.text) || [];

      setSuggestions(results);
    } catch (error) {
      console.error('Error fetching places:', error);
    }

    setLoading(false);
  };

  const handleInputChange = (text: string) => {
    setQuery(text);
    if (text.length >= 2) {
      fetchPlaces(text);
    } else {
      setSuggestions([]); // Clear suggestions if input is too short
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Search for a place..."
        value={query}
        onChangeText={handleInputChange}
      />

      {loading && (
        <ActivityIndicator size="small" color="gray" style={styles.loader} />
      )}

      <FlatList
        data={suggestions}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({item}) => (
          <TouchableOpacity style={styles.item} onPress={() => setQuery(item)}>
            <Text style={styles.itemText}>{item}</Text>
          </TouchableOpacity>
        )}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 10,
    backgroundColor: '#fff',
  },
  input: {
    height: 50,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 10,
    fontSize: 16,
    backgroundColor: '#f9f9f9',
  },
  loader: {
    marginVertical: 10,
  },
  item: {
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#ddd',
  },
  itemText: {
    fontSize: 16,
  },
});

export default GooglePlacesAutocomplete;

hashhirr avatar Mar 21 '25 00:03 hashhirr

I managed to make it work with the new Places API :

  1. I took the 2.5.7 version or the last commit from master to include this PR https://github.com/FaridSafi/react-native-google-places-autocomplete/pull/943/files#diff-c0d73f319f1167879412f6c75dcd9cc124356ef467bb09cc3874a36ce3cdecdc: packages.json: "react-native-google-places-autocomplete": "https://github.com/FaridSafi/react-native-google-places-autocomplete#master"
  2. I had to patch node_modules/react-native-google-places-autocomplete/GooglePlacesAutocomplete.js import Qs from 'qs'; +import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; (see last paragraph of https://www.npmjs.com/package/uuid)
  3. Then I used the new prop isNewPlacesAPI={true} of (see the PR above)

Works in production? The same author opened an draft issue related to this PR https://github.com/FaridSafi/react-native-google-places-autocomplete/pull/951 without conclusion

Works for me send props

isNewPlacesAPI
 requestUrl={{
            url: 'https://places.googleapis.com',
            useOnPlatform: 'all',
            headers: {
              'content-type': 'application/json; charset=utf-8',
            },
          }}
fields="id,..."

Id is required in fields because is verified to invoke onPress Only send isNewPlacesAPI={true} doesnt work, I had to add url for new places

mannoeu avatar Mar 24 '25 17:03 mannoeu

Hi, I've created a fresh library for Places autocomplete using the New API, give it a try

🎨 Fully customizable UI 🌍 RTL support ⌨️ Debounced search 🔄 Loading indicators 📱 Keyboard-aware 🎯 TypeScript support 🔍 Custom place types filtering 🌐 Multi-language support

https://github.com/amitpdev/react-native-google-places-textinput https://www.npmjs.com/package/react-native-google-places-textinput

amitpdev avatar Mar 25 '25 12:03 amitpdev

fixed mine by installing react-native-get-random-values and importing it on top of my file like import "react-native-get-random-values";

you can check this on stackoverflow

WHITELOTUS0 avatar Apr 03 '25 16:04 WHITELOTUS0

@amitpdev @jjfattz @adamalexander @equilizer @jakozbek. Hi all, check this hook on npm I think It can help you :) https://www.npmjs.com/package/rn-use-google-places-autocomplete

dpakakpo4 avatar Apr 21 '25 18:04 dpakakpo4