Code Monkey home page Code Monkey logo

react-native-google-places's Introduction

react-native-google-places

iOS/Android Google Places Widgets (Autocomplete Modal) and API Services for React Native Apps

Notice: The Google Play Services version of the Places SDK for Android (in Google Play Services 16.0.0) is deprecated as of January 29, 2019, and will be turned off on July 29, 2019. A new version of the Places SDK for Android is now available. I suggest you read the documentations again and update your app to use v3.0.1 (or above) of this package

Shots

Versioning:

Sample App

  • A new Sample App is available to help with sample usage and debugging issues.

Install

npm i react-native-google-places --save

OR

yarn add react-native-google-places

Google Places API Set-Up

  1. Sign up for Google Places & Google Maps APIs for Android in Google API Console to grab your Android API key (not browser key).
  2. Read further API setup guides at https://developers.google.com/places/android-sdk/signup.
  3. Similarly, sign up for Google Places API for iOS in Google API Console to grab your iOS API key (not browser key).
  4. Ensure you check out further guides at https://developers.google.com/places/ios-sdk/get-api-key.
  5. Enable billing for your projects - please do not file any issues on this repo without first checking you have, indeed, enabled billing on your account.
  6. With both keys in place, you can proceed.

Post-Install Steps (iOS)

1) Auto Linking & Cocoapods Integration
  • If you do not have CocoaPods already installed on your machine, run gem install cocoapods to set it up the first time. (Hint: Go grab a cup of coffee!)
  • If you are not using Cocoapods in your project already, run cd ios && pod init at the root directory of your project. This would create a Podfile in your ios directory.
  • Run react-native link react-native-google-places at the root directory of your project and ensure you edit your Podfile to look like the sample below (remove all the targets you are not building for, such as Tests and tvOS):
# platform :ios, '9.0'

target '_YOUR_PROJECT_TARGET_' do

  # Pods for _YOUR_PROJECT_TARGET_
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'CxxBridge',
    'DevSupport',
    'RCTText',
    'RCTImage',
    'RCTNetwork',
    'RCTWebSocket',
    'RCTSettings',
    'RCTAnimation',
    'RCTLinkingIOS',
    # Add any other subspecs you want to use in your project
    # Remove any subspecs you don't want to use in your project
  ]

  pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
  # This should already be auto-added for you, if not add the line below
  pod 'react-native-google-places', :path => '../node_modules/react-native-google-places'

end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-places'
      target.build_configurations.each do |config|
        config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
      end
    end
    if target.name == "React"
      target.remove_from_project
    end
  end
end
  • Replace all references to YOUR_PROJECT_TARGET with your project target (it's the same as project name by default).
  • By now, you should be all set to install the packages from your Podfile. Run pod install from your ios directory.
  • Close Xcode, and then open (double-click) your project's .xcworkspace file to launch Xcode. From this time onwards, you must use the .xcworkspace file to open the project. Or just use the react-native run-ios command as usual to run your app in the simulator.
2) Configuration on iOS
  • In your AppDelegate.m file, import the Google Places library by adding
    @import GooglePlaces; 
    @import GoogleMaps;

on top of the file.

  • Within the didFinishLaunchingWithOptions method, instantiate the library as follows - read about a better way to secure this below:
[GMSPlacesClient provideAPIKey:@"YOUR_IOS_API_KEY_HERE"];
[GMSServices provideAPIKey:@"YOUR_IOS_API_KEY_HERE"];
  • Ensure you have the required location permissions for the application by declaring keys for NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription in your info.plist file, either using Xcode or manually editing the file e.g.
<key>NSLocationWhenInUseUsageDescription</key>
	<string>RNGPDemos needs your location to show you places</string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>RNGPDemos needs your location to show you places</string>

Post-Install Steps (Android)

Auto Linking With Your Project
  • This was done automatically for you when you ran react-native link react-native-google-places. Or you can run the command now if you have not already.
  • In your AndroidManifest.xml file, request the following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  • In your /android/gradle.properties file, add your API key, read about a better way to secure this below
RNGP_ANDROID_API_KEY=Insert_API_KEY_here
Manual Linking With Your Project (Android)
  • The following additional setup steps are optional as they should have been taken care of, for you when you ran react-native link react-native-google-places. Otherwise, do the following or just ensure they are in place;
  • Add the following in your android/settings.gradle file:
include ':react-native-google-places'
project(':react-native-google-places').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-google-places/android')
  • Add the following in your android/app/build.grade file:
dependencies {
    ...
    compile project(':react-native-google-places')
}
  • Add the Google Maven Repo in your android/build.gradle file:
allprojects {
    repositories {
        ...
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url "https://maven.google.com" 
        }
    }
}
  • Add the following in your ...MainApplication.java file:
import com.arttitude360.reactnative.rngoogleplaces.RNGooglePlacesPackage;

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      ...
      new RNGooglePlacesPackage() //<-- Add line
  );
}
Additional Requirement (Android)
  • Enable multiDex for your application.
  • Ensure you are compiling with Java 1.8 or above. Add the following in your /android/app/build.gradle file:
android {
    defaultConfig {
        ...
        multiDexEnabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
  • Finally, we can run react-native run-android to get started.

Usage

Allows your users to enter place names and addresses - and autocompletes your users' queries as they type.

Import library

import RNGooglePlaces from 'react-native-google-places';

Open Autocomplete Modal (e.g as Callback to an onPress event)

class GPlacesDemo extends Component {
  openSearchModal() {
    RNGooglePlaces.openAutocompleteModal()
    .then((place) => {
		console.log(place);
		// place represents user's selection from the
		// suggestions and it is a simplified Google Place object.
    })
    .catch(error => console.log(error.message));  // error is a Javascript Error object
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.button}
          onPress={() => this.openSearchModal()}
        >
          <Text>Pick a Place</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
Optional Parameters

To customize autocomplete results as listed for Android and iOS in the official docs, you can pass an options object as a parameter to the openAutocompleteModal() method as follows:

    RNGooglePlaces.openAutocompleteModal({
            initialQuery: 'vestar', 
            locationRestriction: {
                latitudeSW: 6.3670553, 
                longitudeSW: 2.7062895, 
                latitudeNE: 6.6967964, 
                longitudeNE: 4.351055
            },
            country: 'NG',
            type: 'establishment'
        }, ['placeID', 'location', 'name', 'address', 'types', 'openingHours', 'plusCode', 'rating', 'userRatingsTotal', 'viewport']
    )
    .then((place) => {
        console.log(place);
    })
    .catch(error => console.log(error.message));

OPTIONS

  • type (String) - The type of results to return. Can only be one of (geocode, address, establishment, regions, and cities). (optional)
  • country (String) - Limit results to a specific country using a ISO 3166-1 Alpha-2 country code (case insensitive). If this is not set, no country filtering will take place. (optional)
  • locationBias (Object) - To bias autocomplete results to a specific geographic region, pass an object (with the keys: latitudeNE (Number), longitudeNE (Number), latitudeSW (Number), longitudeSW (Number)) representing the bounding box for the region. (optional)
  • locationRestriction (Object) - To restrict autocomplete results to a specific geographic region, pass an object (with the keys: latitudeNE (Number), longitudeNE (Number), latitudeSW (Number), longitudeSW (Number)) representing the bounding box for the region. (optional)
  • useOverlay (Boolean) [Android Only] - If true, the autocomplete modal will open as an overlay rather than fullscreen. Defaults to false.
  • initialQuery (String) [Android Only] - If present, the autocomplete modal would launch with results pre-populated for the query passed (optional).

NOTE - On iOS, only one of locationBias or locationRestriction is respected, when passing both, only the first passed option would be used.

PLACE FIELDS

  • To prevent yourself from incurring huge usage bill, you can select the result fields you need in your application. Pass an (optional) placeFields as the second param to openAutocompleteModal.
  • placeFields is an Array of String such as placeID, location, name, address, types, openingHours, plusCode, rating, userRatingsTotal, viewport, website, phoneNumber, plusCode and addressComponents (available in v3.0.1+).
  • Defaults to an empty array which returns every field possible for the particular place.

Example Response from the Autocomplete Modal

{   priceLevel: 0,
    viewport: {   
        longitudeSW: 3.320172219708498,
        latitudeSW: 6.572546249999999,
        longitudeNE: 3.322870180291502,
        latitudeNE: 6.584909250000001 
    },
    address: 'Lagos, Nigeria',
    location: {   
        longitude: 3.3211348, 
        latitude: 6.5818185 
    },
    addressComponents: [ 
      { shortName: 'Lagos',
        name: 'Lagos',
        types: [ 'locality', 'political' ] 
      },
      { shortName: 'LA',
        name: 'Lagos',
        types: [ 'administrative_area_level_1', 'political' ] 
      },
      { shortName: 'NG',
        name: 'Nigeria',
        types: [ 'country', 'political' ] 
      } 
    ],
    userRatingsTotal: 939,
    plusCode: { 
        globalCode: '6FR5H8JC+PF',
        compoundCode: 'H8JC+PF Lagos, Nigeria' 
    },
    rating: 3.2,
    types: [ 'airport', 'point_of_interest', 'establishment' ],
    attributions: [],
    placeID: 'ChIJhRTXUeeROxARmk_Rp3PtIvI',
    name: 'Murtala Muhammed International Airport' 
}
  • Note: The keys available from the response from the resolved Promise from calling RNGooglePlaces.openAutocompleteModal() are dependent on the selected place - as phoneNumber, website, north, south, east, west, priceLevel, rating are not set on all Google Place objects.

Get Current Place

This method returns to you the place where the device is currently located. That is, the place at the device's currently-reported location. For each place, the result includes an indication of the likelihood that the place is the right one. A higher value for likelihood means a greater probability that the place is the best match. Ensure you have required the appropriate permissions, as stated post-install steps above, before making this request.

  RNGooglePlaces.getCurrentPlace()
    .then((results) => console.log(results))
    .catch((error) => console.log(error.message));

OR

  RNGooglePlaces.getCurrentPlace(['placeID', 'location', 'name', 'address'])
    .then((results) => console.log(results))
    .catch((error) => console.log(error.message));

PLACE FIELDS

  • To prevent yourself from incurring huge usage bill, you can select the result fields you need in your application. Pass an (optional) placeFields as the only param to getCurrentPlace.
  • placeFields is an Array of String such as placeID, location, name, address, types, openingHours, plusCode, rating, userRatingsTotal, viewport.
  • Defaults to an empty array which returns every field possible for the particular place.
  • Place note that requesting for website, phoneNumber, phoneNumber and addressComponents are not supported when calling getCurrentPlace.

Example Response from Calling getCurrentPlace()

[{ name: 'Facebook HQ',
  website: 'https://www.facebook.com/',
  longitude: -122.14835169999999,
  address: '1 Hacker Way, Menlo Park, CA 94025, USA',
  latitude: 37.48485,
  placeID: 'ChIJZa6ezJa8j4AR1p1nTSaRtuQ',
  types: [ 'street_address', 'geocode' ],
  phoneNumber: '+1 650-543-4800',
  likelihood: 0.9663974,
  ...
},{
  ...
}]

The sum of the likelihoods in a given result set is always less than or equal to 1.0. Note that the sum isn't necessarily 1.0.

Using Your Own Custom UI/Views

If you have specific branding needs or you would rather build out your own custom search input and suggestions list (think Uber), you may profit from calling the API methods below which would get you autocomplete predictions programmatically using the underlying iOS and Android SDKs.

Get Autocomplete Predictions

  RNGooglePlaces.getAutocompletePredictions('facebook')
    .then((results) => this.setState({ predictions: results }))
    .catch((error) => console.log(error.message));
Optional Parameters

To filter autocomplete results as listed for Android and iOS in the official docs, you can pass an options object as a second parameter to the getAutocompletePredictions() method as follows:

  RNGooglePlaces.getAutocompletePredictions('Lagos', {
	  type: 'cities',
	  country: 'NG'
  })
    .then((place) => {
    console.log(place);
    })
    .catch(error => console.log(error.message));

OR

RNGooglePlaces.getAutocompletePredictions('pizza', {
	    type: 'establishments',
	    locationBias: {
            latitudeSW: 6.3670553, 
            longitudeSW: 2.7062895, 
            latitudeNE: 6.6967964, 
            longitudeNE: 4.351055
        }
    })
    .then((place) => {
    console.log(place);
    })
    .catch(error => console.log(error.message));
  • type (String) - The type of results to return. Can only be one of (geocode, address, establishment, regions, and cities). (optional)
  • country (String) - Limit results to a specific country using a ISO 3166-1 Alpha-2 country code (case insensitive). If this is not set, no country filtering will take place. (optional)
  • locationBias (Object) - To bias autocomplete results to a specific geographic region, pass an object (with the keys: latitudeNE (Number), longitudeNE (Number), latitudeSW (Number), longitudeSW (Number)) representing the bounding box for the region. (optional)
  • locationRestriction (Object) - To restrict autocomplete results to a specific geographic region, pass an object (with the keys: latitudeNE (Number), longitudeNE (Number), latitudeSW (Number), longitudeSW (Number)) representing the bounding box for the region. (optional)

NOTE - On iOS, only one of locationBias or locationRestriction is respected, when passing both, only the first passed option would be used.

Example Response from Calling getAutocompletePredictions()

[ { primaryText: 'Facebook HQ',
    placeID: 'ChIJZa6ezJa8j4AR1p1nTSaRtuQ',
    secondaryText: 'Hacker Way, Menlo Park, CA, United States',
    fullText: 'Facebook HQ, Hacker Way, Menlo Park, CA, United States' },
    types: [ 'street_address', 'geocode' ],
  { primaryText: 'Facebook Way',
    placeID: 'EitGYWNlYm9vayBXYXksIE1lbmxvIFBhcmssIENBLCBVbml0ZWQgU3RhdGVz',
    secondaryText: 'Menlo Park, CA, United States',
    fullText: 'Facebook Way, Menlo Park, CA, United States' },
    types: [ 'street_address', 'geocode' ],

    ...
]

Look-Up Place By ID

  RNGooglePlaces.lookUpPlaceByID('ChIJZa6ezJa8j4AR1p1nTSaRtuQ')
    .then((results) => console.log(results))
    .catch((error) => console.log(error.message));

OR

  RNGooglePlaces.lookUpPlaceByID('ChIJZa6ezJa8j4AR1p1nTSaRtuQ', ['placeID', 'location', 'name', 'address'])
    .then((results) => console.log(results))
    .catch((error) => console.log(error.message));

PLACE FIELDS

  • To prevent yourself from incurring huge usage bill, you can select the result fields you need in your application. Pass an (optional) placeFields as the second param to lookUpPlaceByID.
  • placeFields is an Array of String such as placeID, location, name, address, types, openingHours, plusCode, rating, userRatingsTotal, viewport, addressComponents, website, phoneNumber, and phoneNumber.
  • Defaults to an empty array which returns every field possible for the particular place.

Example Response from Calling lookUpPlaceByID()

{ name: 'Facebook HQ',
  website: 'https://www.facebook.com/',
  longitude: -122.14835169999999,
  address: '1 Hacker Way, Menlo Park, CA 94025, USA',
  latitude: 37.48485,
  placeID: 'ChIJZa6ezJa8j4AR1p1nTSaRtuQ',
  types: [ 'street_address', 'geocode' ],
  phoneNumber: '+1 650-543-4800',
}
  • Note: Check Autocomplete response for notes and other available keys.

Design Hint

The typical use flow would be to call getAutocompletePredictions() when the value of your search input changes to populate your suggestion listview and call lookUpPlaceByID() to retrieve the place details when a place on your listview is selected.

PS (from Google)

  • Use of the getAutocompletePredictions() method is subject to tiered query limits. See the documentation on Android & iOS Usage Limits.
  • Also, your UI must either display a 'Powered by Google' attribution, or appear within a Google-branded map.

Securing Your API Keys & Making Them Work With Your CI/CD Tools (Optional Steps)

Android API Key

  • From version 3 of this package, on Android, the package would, by default, first look for your API key in System Variables before checking for it in your gradle.properties file - this ensures you can totally keep your keys out of Version Control.
  • Remove your API key from gradle.properties, if already defined. Define a system variable representing your Android API key e.g. on a Unix/Mac terminal run:
export RNGP_ANDROID_API_KEY=Insert_API_KEY_here
  • You may need to export this system/environment variable before every build or add them to your ~/.bash_profile file or similar files.
  • Ensure you have the system/environment variable replicated in your CI/CD build and you should be fine.
  • You may skip these steps and continue to have your API key in gradle.properties, things would work just as fine.

iOS API Key

You would have to do a bit more work to properly secure and move your API key out of Version Control than we did for Android.

  • Add a Gemfile to the root of your /ios folder with the following or similar content:
source 'https://rubygems.org'

gem 'cocoapods'
gem 'cocoapods-keys'
  • Install the cocoapods-keys CocoaPod plugin by running the following on your terminal from your /ios directory:
gem install cocoapods-keys
  • Add the plugin to your Podfile like below:
plugin 'cocoapods-keys'

target 'YourApp' do

  # Pods for YourApp

  pod 'GoogleMaps'
  pod 'GooglePlaces'

end
  • Consult the usage and alternative usage sections of the cocoapods-keys repo to learn how to add your API key to keychain on the Mac.
  • Set up your key with cocoapods-keys with either of the instructions from the line above.
  • Run pod install again from your /ios directory.
  • Replace the string versions of your key in your AppDelegate.m file. You can review a sample usage in the Sample App
  • You may skip these steps and continue to have your API key directly in AppDelegate.m, things would work just as fine.

Troubleshooting

Ensure you have automatically/manually linked dependencies and/or re-run the build after doing so.

  1. Run react-native link
  2. Try Manual Linking With Your Project steps above.
  3. Run react-native run-ios

On iOS, ensure you have installed the native dependencies with Cocoapods.

License

The MIT License.

react-native-google-places's People

Contributors

aforty avatar bahaa96 avatar congnguyen91 avatar jpapillon avatar kappac avatar kostiag avatar luugiathuy avatar matanelgabsi avatar meta-dreamer avatar nopik avatar qrokqt avatar richou avatar rohantalip avatar ruqqq avatar simonbuerger avatar tolu360 avatar xsduan 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

react-native-google-places's Issues

Android permissions Issues

Hey @tolu360, is there any plan to add permissions request into the Android part of the library. App crashes when I request for places due to Locations permissions not being requested for in Android 6.0 and above.

Android Does not return selected location object

@tolu360 Great library this is. But just a nagging issue i've been struggling with for days. I am able to get the result of user selected location when user clicks on any of the auto-suggested place in iOS, but doesn't work in Android.

const place = await RNGooglePlaces.openAutocompleteModal();
// promise always gets lost in here for Android but gets resolved in iOS

Could not Invoke RNGooglePlaces.openplacePickerModal

Hi @tolu360 ! and thanks for this component, is quite useful.
The only problem I've using it is that while on IOS everything works fine on android when i try to invoke openPlacePickerModal on RNGooglePlaces react-native returns an error.

Here is the error:
screenshot

I tried to inspect your java module but didn't find anything yet.

What i did so far:

  • created api keys
  • placed keys in meta inside xml
  • added permission for fine location
  • did react-native link your-package-name
  • double checked that everythings was imported (in build.gradle, MainApplication.java etc. etc.)
  • i even tried to ask permission before invoke openPlacePickerModalbecuase i tought was a permission problem.

so this is my code so far:

async openSearchModal() {
    if(Platform.OS === 'android') {
      try {
        let granted = await PermissionsAndroid.requestPermission(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
        if (!granted) {
          return false
        }
      } catch (err) {
        console.warn(err)
        return false
      }
    }

    RNGooglePlaces.openPlacePickerModal()
    .then((place) => {
        console.log(place)
        // place represents user's selection from the
        // suggestions and it is a simplified Google Place object.
    })
    .catch(error => console.log(error.message))  // error is a Javascript Error object
  }

removing the permission related code doesn't resolve the error.
Everything is being tested on real device.

One Plus One,
Android 6.0

Module 'GoogleMaps' not found

Fresh install
I get this error.

`While building module 'GooglePlacePicker' imported from /Users/coding/Documents/react/test/node_modules/react-native-google-places/ios/RNGooglePlacesViewController.m:4:
In file included from :1:
In file included from /Users/coding/Documents/react/test/node_modules/react-native-google-places/ios/../../../ios/Pods/GooglePlacePicker/Frameworks/GooglePlacePicker.framework/Headers/GooglePlacePicker.h:1:
/Users/coding/Documents/react/test/node_modules/react-native-google-places/ios/../../../ios/Pods/GooglePlacePicker/Frameworks/GooglePlacePicker.framework/Headers/GMSPlacePicker.h:12:9: fatal error: module 'GoogleMaps' not found
@import GoogleMaps;

1 error generated.`

Only known places can be selected

My problem is the following:
When I select a place in map, a point in a street, the "SELECT" buttons goes disabled, and none information about that point (street, latitude, longitude) is returned:

image

How can I make any place in the map "selectable", instead of "only know places"?

I wish something like this:

image

Is possible?

undefined - RNGooglePlacesNative.openPlacePickerModal

import {
  Image,
  Linking,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { LoadingScreen } from './home/commons';
import * as Expo from 'expo';
import Colors from '../constants/Colors'
import { connect } from 'react-redux';
import ChatList from './home/components/ChatList';
import { fetchGroupChats } from './home/actions';
import RNGooglePlaces from 'react-native-google-places';
import { MonoText } from '../components/StyledText';

export default class HomeScreen extends React.Component {
  openSearchModal() {
    RNGooglePlaces.openPlacePickerModal()
    .then((place) => {
        console.log(place);
    })
    .catch(error => console.log(error.message));
  }
  static route = {
    navigationBar: {
      visible: false,
    },
  };

  async getLocationAsync() {
    const { Location, Permissions } = Expo;
    const { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status === 'granted') {
      var locObj = await Location.getCurrentPositionAsync({enableHighAccuracy: true});
      let lat = locObj['coords'].latitude;
      let lon = locObj['coords'].longitude;

      this.location = locObj;

      return this.location;

    } else {
      throw new Error('Location permission not granted');
    }
  }


  componentDidMount() {
    this.getLocationAsync();
    this.props.fetchGroupChats();
  }



  render() {
    let receivedLocation = this.location;

    if (!receivedLocation) {
      return (
        <View style={styles.container}>
          <LoadingScreen />
        </View>
      )
    } else {
      return (
        <View style={styles.root}>
          <Expo.MapView
          style={{flex: 1}}
          initialRegion={{
            latitude: receivedLocation['coords'].latitude,
            longitude:  receivedLocation['coords'].longitude,
            latitudeDelta: 0.005,
            longitudeDelta: 0.005,
          }}/>
          <View style={styles.container}>
            <TouchableOpacity
            style={styles.button}
            onPress={() => this.openSearchModal()}
          >
              <Text>Pick a Place</Text>
            </TouchableOpacity>
          </View>
        </View>
      )

    }
  }

Language setting?

Hi there! Thanks for the package :)

Is there a language setting? If not, can you give me guidelines so I can contribute with this feature?

'GooglePlaces/GooglePlaces.h' file not found

After installing the package and manually adding Google Places sdk (without pod), running the app throws an error. Below is a screenshot of the error. The GooglePlaces header file can be accessed from my appDelegate.m file.

RN version: 0.36.1
react-native-google-places version: 0.8.8
Google Places sdk version: 2.2

screen shot 2017-03-22 at 6 30 27 pm

Apple Store rejected because of IPv6 compatibility issue

Hello,

I have submitted my app to apple store but they rejected it because of IPv6 compatibility issue.

Have you ever encountered this problem ?
Do you know if Google Places iOS sdk are compatible with IPv6 addresses ?

Thanks for your help
Best regards.

IOS build error: cannot build module 'GooglePlaces' , module 'GoogleMapsBase' not found

Hi @tolu360. Thanks for building this module. After following the setup on the readme, and running react-native run-ios, I got the build errors copied below.

/node_modules/react-native-google-places/ios/../../../ios/Pods/GooglePlaces/Frameworks/GooglePlaces.framework/Headers/GMSAddressComponent.h:12:9: fatal error:
module 'GoogleMapsBase' not found
@import GoogleMapsBase;

node_modules/react-native-google-places/ios/RNGooglePlacesViewController.h:2:9: fatal error:
could not build module 'GooglePlaces'
#import <GooglePlaces/GooglePlaces.h>

/node_modules/react-native-google-places/ios/../../../ios/Pods/GooglePlacePicker/Frameworks/GooglePlacePicker.framework/Headers/GMSPlacePickerConfig.h:12:9: fatal error:
module 'GoogleMapsBase' not found
@import GoogleMapsBase;

Below is the Podfile.lock file.

PODS:

  • GoogleMaps (2.1.1):
    • GoogleMaps/Maps (= 2.1.1)
  • GoogleMaps/Base (2.1.1)
  • GoogleMaps/Maps (2.1.1):
    • GoogleMaps/Base
  • GooglePlacePicker (2.1.1):
    • GoogleMaps (= 2.1.1)
    • GooglePlaces (= 2.1.1)
  • GooglePlaces (2.1.1):
    • GoogleMaps/Base (= 2.1.1)

DEPENDENCIES:

  • GoogleMaps
  • GooglePlacePicker
  • GooglePlaces

SPEC CHECKSUMS:
GoogleMaps: a5b5bbe47734e2443bde781a6aa64e69fdb6d785
GooglePlacePicker: 665f39f931f2df32f9dd3fcc45f7e8abf71e535c
GooglePlaces: 35636d86e5020cba3856eb988c09a5491de0a65a

PODFILE CHECKSUM: 9e1e9b87ca813feb8ea6f289cc25daf3e325cac6

COCOAPODS: 1.1.1

The pods appeared to be installed successfully, and I double checked the AppleDelegate.m file. I have v 0.35.0 of react-native installed. I copied my AppDelegate.m file below as well. Any ideas on how to fix this?

@import GooglePlaces;
@import GoogleMaps;

#import "AppDelegate.h"

#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

@implementation AppDelegate

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    NSURL *jsCodeLocation;

    jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

    [GMSPlacesClient provideAPIKey:@"AIzaSyxxxxxxxx"];
    [GMSServices provideAPIKey:@"AIzaSyxxxxxxxxxx"];

    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
    moduleName:@"thriftRide"
    initialProperties:nil
    launchOptions:launchOptions];
    rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIViewController *rootViewController = [UIViewController new];
    rootViewController.view = rootView;
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];
    return YES;
    }

@EnD

Could not load search Results And Illegal Callback Invocation

Hi thanks for the google places package.

I am having problems with RNGooglePlaces.openAutocompleteModal from the example you gave. When I click pick a place, the modal shows up and disappears almost immediately with an error message "Could not load search results". When I try to input some values in the search field I get an error "Illegal callback invocation from native module. This callback type only permits a single invocation from native code."

screen shot 2017-02-27 at 10 35 28 pm

An error occurred while executing doInBackground

hi i got error after install react-native-google-places. without react-native-google-places map is working fine. any idea? thx

"react": "16.0.0-alpha.6",
"react-native": "0.44.2",
"react-native-maps": "^0.15.0",
"react-native-google-places": "^2.1.0",

screen shot 2017-07-17 at 4 49 01 pm

working on hardware but not simulator

Hi tolu!

I went through all the build errors and setup (took a while but finally) and was able to get the module to actually work on my hardware device when i run it from Xcode directly onto my phone. However when trying to run on the simulator I am regularly getting this error (i have tried reboots and reinstalls of the server for simulator and the node_module folder and cache clearing, to no avail). Is it expected behavior to not work on a simulator because of non-device limitations?


screenshot 2017-02-09 00 29 55

Problem with NSDictionary+GMSPlace.m

no such file or directory: '.../app/node_modules/react-native-google-places/ios/NSDictionary+GMSPlace.m

I install by CocoaPods and I present the problem above.

Could not invoke RNGooglePlaces.getAutocompletePredictions

Hie bro I am getting this error trying to run the app on android. Everything works fine on ios.

Inside my node-modules folder i checked and saw that react-native-maps is using

compile "com.google.android.gms:play-services-base:10.2.4"
compile "com.google.android.gms:play-services-maps:10.2.4"

While react native google places
is using

    compile 'com.google.android.gms:play-services-base:10.2.0'
    compile 'com.google.android.gms:play-services-places:10.2.0'
    compile 'com.google.android.gms:play-services-location:10.2.0'

React native maps -
screen shot 2017-06-08 at 9 16 32 am

How can i get photos for places?

@tolu360 Mb You know, How can i get photos for places using RNGooglePlaces.getAutocompletePredictions method?

And Mb You know, How can i get latitude and longitude in RNGooglePlaces.getAutocompletePredictions for places?

not seeing map and list not initialized?

Running it in an iOS simulator. Location is set and coordinates are specified. However and picker is opened map is not displayed and list is not initialized to places near by. What am I doing wrong if anything?

Input and result list style

Hi and thank you very much for this repo. Is there an option to modify styles of rendered list, like with renderRow or similar? Thanks!

Change the results language

For now all results is in English,
Is there any way to change it to specific language?
Already pass the 'country' option, but all result still in English.

Thank you in advance.

Filter Multiple Countries

Can you allow us to enter an array to filter my multiple countries such as:

RNGooglePlaces.getAutocompletePredictions(text, { type: 'cities', country: ['ca', 'us'] })...

How get more information of the the result?

The place result only information about: name, adress, lat, lng, place_id
If i want more information like result of google place api (includes photos.....):
{ "formatted_address" : "New York, NY, USA", "geometry" : { "location" : { "lat" : 40.7127837, "lng" : -74.0059413 }, "viewport" : { "northeast" : { "lat" : 40.9152555, "lng" : -73.70027209999999 }, "southwest" : { "lat" : 40.4960439, "lng" : -74.25573489999999 } } }, "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png", "id" : "7eae6a016a9c6f58e2044573fb8f14227b6e1f96", "name" : "New York", "photos" : [ { "height" : 2592, "html_attributions" : [ "\u003ca href=\"https://maps.google.com/maps/contrib/109675169087914453108/photos\"\u003eJernique Webb\u003c/a\u003e" ], "photo_reference" : "CoQBdwAAABvCjwlFI11PMTsyaKb3hl81StlK5z_nsziAovImoNzX-dxaEeQCiRasa6xb3ccYfZ6Lq5YP-m4A--6l8uyk8siTzhKHOBYdYwLwSt1eM3maNm_LulnbigPPyM1tuAdK9RIpAGKV1dimyereRGAcPZv4KMcD2lKHf-5m_LlegKIfEhCZkVL3One_8kaTYHU4zCVaGhRMs0ZzZWln8ZeT9qcERSSJ4rL_AA", "width" : 4608 } ], "place_id" : "ChIJOwg_06VPwokRYv534QaPC8g", "reference" : "CmRbAAAA7X5dgQSwuttJRVnhq1rNDr-gvRCvx5a_R6UN2pTnKzAXPW1GdxJWCAZG1VvTD4hOmybnb8Xqn_yRwdjajZ7UDoZYIIFS6LkWIJmsxNUL7wN5T5Fj_XQ-1R0agJaa1gkWEhA9kCh6uanW_76pujFpJ5b8GhR-Nv3jt7RFXNVJmm408PWL6WxmtQ", "types" : [ "locality", "political" ] }

Android error: statusCode=PLACES_API_KEY_EXPIRED

After installing and creating keys as per instructions in the readme I get this error when I call openAutocompleteModal:

Error: Status{statusCode=PLACES_API_KEY_EXPIRED, resolution=null}
at createErrorFromErrorData (NativeModules.js:115)
at NativeModules.js:78
at MessageQueue.__invokeCallback (MessageQueue.js:296)
at MessageQueue.js:120
at MessageQueue.__guard (MessageQueue.js:218)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:119)
at debuggerWorker.js:71

I have not restricted my key's usage. I did try doing so based on SHA-1, but that didn't help. I also generated a new key with no better luck.

Any suggestions are welcome

react-native-google-places clinching with react-native-fcm

SOLVED: The problem was the version of Google Play Services pulled in by react-native-fcm. The solution was forcing the versions of Google Play Services to adhere to that of the react-native-google-places library.

Hello @tolu360

We are currently building an application, which uses your react-native-google-places library. We have only been using the getAutocompletePredictions function to produce our own in-app dropdown with suggestions. So far everything has been running smoothly.

We then decided to use push notifications with Firebase using the react-native-fcm library, which has also gained huge traction of late. This has resulted in an error, which breaks the functionality we use from react-native-google-places.

The error is vaguely described as "Could not invoke RNGooglePlaces.getAutocompletePredictions" on the infamous red background.

screenshot_20170518-193619

What we have tried so far:

  • Uninstalled react-native-fcm library, which solved the getAutocompletePredictions problem, but leaves us back at square one regarding push notifications, so that's not really a viable fix.
  • Tried calling other functions in your library; openPlacePickerModal, openAutocompleteModal - which all behave as expected, but their usage is not what we are looking for, so those functions are not preferred solutions either.
  • Messed around with build configurations; reordering import, compile, and dependency lines, and tried different makeshift solutions we could track down with google. All to no avail.
  • Read through issue #4, which looks fairly similar to our problem, but the suggested fixes in that thread either doesn't work or are not applicable to our project.

The project has only been run on Android, on both Nexus 5x and Samsung Galaxy 7 Edge. Neither of the phones produce the result we want. We have yet to run anything on iOS, but we need it to run on Android regardless.

Do you have any knowledge about this bug, or are you able to take a look and give us a hint?
Thank you very much in advance.

Let me know, if you need any further information regarding the bug.

Custom modal

Has anyone developed a simple getAutocompletePredictions modal? I was considering implementing a basic component that included a list view for recent searches, Home and Current Location.

using together with react-native-navigation issue: view is not in the window hierarchy

The code should change in order to work to (need to find topmost controller):

GMSAutocompleteViewController *viewController = [[GMSAutocompleteViewController alloc] init]; viewController.delegate = self; UIViewController *topController = [UIApplication sharedApplication].delegate.window.rootViewController; while (topController.presentedViewController) { topController = topController.presentedViewController; } [topController presentViewController:viewController animated:YES completion:nil];

Receive the full api response

Is there a way to get the full response instead of a squashed version of it? For example, I need to parse out the street, city, zip, and country all separately. Thanks so much!

I can't generate ipa file.

Thanks for making this component.
I like this component to use in my app, very useful.

But I can't generate ipa file.
/////////////////////////////////////////////////////////////////////
In xcode, I can build successfully, but I can't build in terminal,
this error occurs.


** BUILD FAILED **

The following build commands failed:
CompileC /Users/my_project/ios/build/Build/Intermediates/RCTSettings.build/Debug-iphonesimulator/RCTSettings.build/Objects-normal/x86_64/RCTSettingsManager.o RCTSettingsManager.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
CompileC /Users/my_project/ios/build/Build/Intermediates/RCTAnimation.build/Debug-iphonesimulator/RCTAnimation.build/Objects-normal/x86_64/RCTFrameAnimation.o Drivers/RCTFrameAnimation.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

Package is empty

@tolu360 I have just installed the package and on accessing the openAutocompleteModal method I get an error of RNGooglePlaces being undefined. On logging, I found that the object is empty.
Any advice on the issue?

import RNGooglePlaces from 'react-native-google-places';

Execution failed for task ':app:transformClassesWithDexForDebug'.

When i'm building my app for debug, i got this type of error, please give some solution

Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
Dex: Error converting bytecode to dex:WithDexForDebug
Cause: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/location/places/zzl;
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/location/places/zzl;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)

:app:transformClassesWithDexForDebug FAILED

Carthage support?

Hey! Looks like an awesome package!! Any chance you're going to set it up so we can use it with carthage?

Execution failed for task ':react-native-google-places:compileReleaseJavaWithJavac'.

while running react-native run-android

:react-native-google-places:incrementalReleaseJavaCompilationSafeguard UP-TO-DATE
:react-native-google-places:compileReleaseJavaWithJavac
:react-native-google-places:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
C:\Users\alex\Desktop\chat-mobile\node_modules\react-native-google-places\android\src\main\java\com\arttitude360\reactnative\rngoogleplaces\RNGooglePlacesModule.java:42: error: RNGooglePlacesModule is not abstract and does not override abstract method onActivityResult(int,int,Intent) in ActivityEventListener
public class RNGooglePlacesModule extends ReactContextBaseJavaModule implements ActivityEventListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
       ^
C:\Users\alex\Desktop\chat-mobile\node_modules\react-native-google-places\android\src\main\java\com\arttitude360\reactnative\rngoogleplaces\RNGooglePlacesModule.java:82: error: method does not override or implement a method from a supertype
    @Override
    ^
C:\Users\alex\Desktop\chat-mobile\node_modules\react-native-google-places\android\src\main\java\com\arttitude360\reactnative\rngoogleplaces\RNGooglePlacesModule.java:448: error: method does not override or implement a method from a supertype
    @Override
    ^
3 errors
:react-native-google-places:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-google-places:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 19.835 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html```

undefined is not an object ('RNGooglePlacesNative.openAutoCompleteModal')

Hello !
I followed all the instructions, but it has the following errors:

printi
I even tried to put in the first js and manual link, but no sucess.

my pod:

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, ’8’

target 'MyMap' do
  react_native_path = "../node_modules/react-native"
  pod "Yoga", :path => "#{react_native_path}/ReactCommon/yoga"
  pod "React", :path => react_native_path

  pod 'GoogleMaps'  
  pod 'GooglePlaces'
  pod 'GooglePlacePicker'

end

no map view

only places selections, but no map view

 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Colors from '../constants/Colors'
import MapView from 'react-native-maps';
import ChatList from './home/components/ChatList';
import { fetchGroupChats } from './home/actions';
import { LoadingScreen } from './home/commons';
import { connect } from 'react-redux';
import RNGooglePlaces from 'react-native-google-places';

@connect(
  state => ({
    chats: state.home.chats
  }),
  { fetchGroupChats }
)


export default class HomeScreen extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  openSearchModal() {
    RNGooglePlaces.openAutocompleteModal({
	  type: 'establishment'
  })
    .then((place) => {
    console.log(place);
    })
    .catch(error => console.log(error.message));  // error is a Javascript Error object
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        error: null,
      });
        console.log(position);
      },
      (error) => console.log(new Date(), error),
      {enableHighAccuracy: false, timeout: 10000}
    )
    this.props.fetchGroupChats();
  }

  render() {

    if (this.state.longitude) {
      const {
        chats: {
          isFetched,
          data,
          error
        }
      } = this.props;
      if (!isFetched) {
      return (
        <View style={styles.container}>
          <LoadingScreen />
        </View>
      )
      } else if (error.on) {
        return (
          <View>
            <Text>{error.message}</Text>
          </View>
        );
      } else if (isFetched) {
        return (

            <View style={styles.root}>
              <TouchableOpacity
                style={styles.button}
                onPress={() => this.openSearchModal()}
              >
                <Text>Pick a Place</Text>
              </TouchableOpacity>
            </View>
        
        )
      }
    } else {
        return (
        <View style={styles.container}>
          <LoadingScreen />
        </View>
      )
    }
  }

}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    justifyContent: 'center',
    //backgroundColor: '$medBlueColor'
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
  topContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.blackBlueColor
  },
  bottomContainer: {
    flex: 0.9,
    backgroundColor: Colors.medBlueColor
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center'
  },
  tabBarInfoContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    alignItems: 'center',
    backgroundColor: '#fbfbfb',
    paddingVertical: 20,
  },
});

Android simulator error: undefined is not an object (evaluating '_reactNativeGooglePlaces.RNGooglePlaces.openPlacePickerModal')

Hello! I've done the setup and I'm getting this error:

undefined is not an object (evaluating '_reactNativeGooglePlaces.RNGooglePlaces.openPlacePickerModal')
openSearchModal
    PlacePicker.js:7
onPress
    PlacePicker.js:20

I created a component based on the example code:

PlacePicker.js

import React, { Component } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { RNGooglePlaces } from 'react-native-google-places';

class PlacePicker extends Component {
  openSearchModal() {
    RNGooglePlaces.openPlacePickerModal()
    .then((place) => { 
        console.log(place);         
    })
    .catch(error => console.log(error.message));
  }

  render() {
    return (
      <View style={{ width: 100, height: 20 }}>
        <TouchableOpacity
          onPress={() => this.openSearchModal()}
        >
          <Text>Open Place Picker</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

export default PlacePicker;

Then I'm using it wrapped in a View-like component

        <CardSection>
          <PlacePicker />
        </CardSection>

Any ideas on how to solve this?
Thanks in advance, I really like this project.

GooglePlacePicker.h file not found when not using GooglePlacePicker

Hi, I was trying to install this library and I plan on using only the API, not the picker. So as per the docs, I didn't include the GooglePlacePicker pod in my podfile. But when I build the project, I get a not found error. When I list GooglePlacePicker in my pods, the issue goes away. Is there a way to use this library without the picker?

P.S: I do not mind having GooglePlacePicker among my pods. It's just that the README states that it's optional. That's all. 😄

/Volumes/Data/QPlay/PharmaTruck/app/node_modules/react-native-google-places/ios/RNGooglePlacesViewController.m:4:9: 'GooglePlacePicker/GooglePlacePicker.h' file not found

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.