How to get the address from google maps autocomplete in React Native

Rafael V. Vega picture Rafael V. Vega · Jul 18, 2018 · Viewed 13.3k times · Source

I am using react-native-google-places-autocomplete to select a location. I want to extract the location selected and use it in other component.

How can I save the address

This is my code

I've been also using another library with some differences

app.js

import React,{Component} from 'react';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome';
import { View, Image, Text, StyleSheet, AsyncStorage, Button,ScrollView, TextInput, ActivityIndicator } from 'react-native';
import {
  NavigationActions
} from 'react-navigation';
import { GoogleAutoComplete } from 'react-native-google-autocomplete';
import {Card, Input} from "react-native-elements";

import LocationItem from './locationItem';


export default class App extends React.Component {

  state={
    datos:[],
  }
  componentDidMount(){
    this._loadedinitialstate().done();
  }
  _loadedinitialstate =async() => {
    AsyncStorage.getItem('datos');
  }

  render() {
    return (
      <View style={styles.container}>
        <GoogleAutoComplete apiKey={'AIzaSyB2HyNTBm1sQJYJkwOOUA1LXRHAKh4gmjU'} debounce={20} minLength={2} getDefaultValue={() => ''}  onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);}}   returnKeyType={'default'} fetchDetails={true}
>
          {({
            locationResults,
            isSearching,
            clearSearchs,
            datos,
            handleTextChange
          }) => (
            <React.Fragment>
              <View style={styles.inputWrapper}>
                <Input
                  style={styles.textInput}
                  placeholder="Ingresa tu direccion"
                  onChangeText={(datos) => this.setState({datos})}
                  value={datos}
                />

              </View>
              {isSearching && <ActivityIndicator size="large" color="red" />}
             <ScrollView>
               {locationResults.map(el => (
                 <LocationItem
                   {...el}
                   key={el.id}
                 />
               ))}
             </ScrollView>
            </React.Fragment>
          )}
        </GoogleAutoComplete>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  textInput: {
    height: 40,
    width: 300,
    borderWidth: 1,
    paddingHorizontal: 16,
  },
  inputWrapper: {
    marginTop: 80,
    flexDirection: 'row'
  },
});

locationitem.js

import React, { PureComponent } from 'react';
import { View, Alert, Text, StyleSheet, TouchableOpacity, AsyncStorage} from 'react-native';

class LocationItem extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {datos:''};
  }

  _handlePress = () => {
    AsyncStorage.setItem('datos',datos)
  }



  render() {
    return (
      <TouchableOpacity style={styles.root} onPress={this._handlePress}  >
        <Text value={this.state.datos}> {this.props.description} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  root: {
    height: 40,
    borderBottomWidth: StyleSheet.hairlineWidth,
    justifyContent: 'center'
  }
})

export default LocationItem;

The source of both codes is here react-native-google-places-autocomplete enter link description here

Which code will be easy to use, and How can I solve my Issue (get the address) ??

Any Answer will be Helpful

Answer

Ragulan picture Ragulan · Oct 24, 2018

first install

npm i react-native-google-places-autocomplete

then

import React from 'react';
import { View, Image } from 'react-native';
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'
      minLength={2} // minimum length of text to search
      autoFocus={false}
      returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
      listViewDisplayed='auto'    // true/false/undefined
      fetchDetails={true}
      renderDescription={row => row.description} // custom description render
      onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}

      getDefaultValue={() => ''}

      query={{
        // available options: https://developers.google.com/places/web-service/autocomplete
        key: 'YOUR API KEY',
        language: 'en', // language of the results
        types: '(cities)' // default: 'geocode'
      }}

      styles={{
        textInputContainer: {
          width: '100%'
        },
        description: {
          fontWeight: 'bold'
        },
        predefinedPlacesDescription: {
          color: '#1faadb'
        }
      }}

      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
      }}
      GooglePlacesSearchQuery={{
        // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
        rankby: 'distance',
        types: 'food'
      }}

      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]}

      debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
      renderLeftButton={()  => <Image source={require('path/custom/left-icon')} />}
      renderRightButton={() => <Text>Custom text after the input</Text>}
    />
  );
}