React-native-google-places-autocomplete: How to get selected value in onPress?

Created on 27 Mar 2017  ·  1Comment  ·  Source: FaridSafi/react-native-google-places-autocomplete

Hello!
Thank you for great work!

Please tell me, how to get selected address?
As data & details from onPress are objects.

I need it for:
1) displaying 'clear' button - as clearButtonMode is iOS specific only.
2) handle address in own server request

here is my code:

import React, { Component } from 'react';

import {
    StackNavigator,  NavigationActions
} from 'react-navigation';

import {
    Animated,
    StyleSheet,
    Text,
    View,
    TextInput,
    TouchableOpacity,
    AsyncStorage,
    Platform,
    ScrollView,
    Image,
} from 'react-native';

import { TabViewAnimated, TabBar } from 'react-native-tab-view';

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

var {GooglePlacesAutocomplete} = require('react-native-google-places-autocomplete');

let textInput = null;

export default class Main extends Component {

    static appbarElevation = 0;
    static propTypes = {
        style: View.propTypes.style,
    };

    static navigationOptions = {
        header: { visible: false },
    };


    constructor(props){
        super(props);
        this.state = {
            index: 0,
            routes: [
                { key: '1', title: 'ТРУД' },
                { key: '2', title: 'Места памяти' }
            ],
            address: '',
            bounceValue: new Animated.Value(1),
            showClearIcon: false,

        }
    }

    _handleChangeTab = (index) => {
        this.setState({ index });
    };

    _renderHeader = (props) => {
        return <TabBar {...props}
            style={styles.tabbar}
            indicatorStyle={styles.indicator}
            labelStyle={styles.label}/>;
    };

    _animateGeoIcon(){
        this.state.bounceValue.setValue(1.5);
        Animated.spring(
            this.state.bounceValue,
            {
                toValue: 1,
                friction: 2,
            }
        ).start();
    }

   async _findLocation(){
        this._animateGeoIcon();
        navigator.geolocation.getCurrentPosition(
            (position) => {
                this._retriveAddress(JSON.stringify(position.coords.latitude), JSON.stringify(position.coords.longitude));
            },
            (error) => {alert(JSON.stringify(error)); console.log("coords " + error.message);},
            {enableHighAccuracy: false, timeout: 15000, maximumAge: 300000}
        );


   }

    async _retriveAddress(latitude, longitude){
        try {
            let response = await fetch(('https://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&language=ru&key=*****'), {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                }
            });
            let res = await response.json();
            if (response.status >= 200 && response.status < 300) {
                let city = res.results[0].address_components[2].long_name;
                this.setState({
                    address: city
                });
                this.setAddress();
            }
        } catch(message) {
        }
    }

    setAddress() {
        textInput.setAddressText(this.state.address);
    }

    clearAddress() {
        textInput.setAddressText('');
    }




    _renderScene = ({ route }) => {
        switch (route.key) {
            case '1':
                return <KeyboardAwareScrollView style={styles.container} extraHeight={150}>
                    <Text style={{ flex:0, backgroundColor: 'white', color:'black', fontSize:14, borderColor:'#c98d41', borderWidth:1, padding:8, margin: 8}}>
                        Приглашаем на первую официальную работу молодых ребят, а также пенсионеров и всех, желающих посвятить себя полезному труду
                    </Text>
                    <View style = {{flex: 1,justifyContent: 'flex-start', alignItems: 'flex-start', backgroundColor:'white'}}>
                        <View style = {{flex: 1,justifyContent: 'flex-start', alignItems: 'flex-start',flexDirection: 'row'}}>
                                    <GooglePlacesAutocomplete
                                    minLength={2}
                                    autoFocus={false}
                                    listViewDisplayed={true}
                                    fetchDetails={true}
                                    renderDescription={(row) => row.description}
                                    onPress={(data, details = null) => {

                                    }}
                                    ref={(input) => { textInput = input; }}
                                    textInputProps={{ userProps: {autoCorrect : false},
                                    onFocus: () => {
                                        this._animateGeoIcon();
                                    },
                                    onChangeText: (text) => {
                                        this.setState({
                                            address: text
                                        });
                                        if (this.state.address.length >=2) {
                                            this.setState({
                                                showClearIcon: true});
                                        } else {
                                            this.setState({
                                                showClearIcon: false});
                                        }
                                    }
                                    }}
                                    enablePoweredByContainer={false}
                                    underlineColorAndroid={'transparent'}
                                    clearButtonMode={'while-editing'}
                                    getDefaultValue={() => {
                                        return this.state.address;
                                    }}
                                    query={{
                                        key: '***',
                                        language: 'ru',
                                        types: '(cities)'
                                    }}
                                    styles={{
                                        textInputContainer: {
                                            backgroundColor: 'rgba(0,0,0,0)',
                                            borderTopWidth: 0,
                                            borderBottomWidth:0,

                                        },
                                         textInput: {
                                            marginLeft: 16,
                                            marginRight: 0,
                                            paddingBottom:8,
                                            color: '#5d5d5d',
                                            fontSize: 14,
                                            height:40,
                                            borderBottomWidth:1,
                                            borderBottomColor:'#e4e4e4'
                                        },
                                        listView: {
                                            marginLeft: 16,
                                            marginRight: 0
                                        }
                                    }}

                                    currentLocation={false}
                                    nearbyPlacesAPI='GooglePlacesSearch'
                                    GooglePlacesSearchQuery={{
                                        rankby: 'distance',
                                        types: 'cemetery',
                                        }}
                                    filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}
                                    debounce={200} />
                            {this.state.showClearIcon &&<TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', ...Platform.select({ios: {height: 0, width:0}, android: { height: 40,}})}}
                                                                          onPress={(e) => this.setState({address: ''},this.clearAddress())}>
                                <Image source={require('./../components/drawables/clear.png')} style={{borderRadius: 15,width: 16,height: 16}}/>
                            </TouchableOpacity>}
                            <TouchableOpacity
                                style={{height:40, marginRight:12, marginLeft:20, padding:4, justifyContent: 'center', alignItems: 'center'}}
                                onPress={(e) => this._findLocation()}>
                                <Animated.Image source={require('./../components/drawables/location.png')} style={{borderRadius: 15,width: 24,height: 24, transform: [{scale: this.state.bounceValue}]}}/>
                            </TouchableOpacity>
                        </View>
                        <ScrollView style={{ flex:0, backgroundColor: 'white', paddingLeft:10, paddingRight:10, paddingTop:10}}
                                    showsVerticalScrollIndicator={false}>
                        </ScrollView>
                    </View>
                </KeyboardAwareScrollView>
                ;
            case '2':
                return <View style={[ styles.page, { backgroundColor: 'white' } ]} />;
            default:
                return null;
        }
    };




    render() {
        return (
            <View style={styles.container}>
                <View style = {{ flex: 0, ...Platform.select({ios: {height: 44,}, android: { height: 56,}}), backgroundColor: 'white', justifyContent: 'flex-start',alignItems: 'center',flexDirection: 'row', padding:16}}>
                    <Text style={{flex:1, color:'#212121', fontSize:18, alignItems: 'center', fontWeight: 'bold'}}>Память</Text>
                </View>
                <TabViewAnimated
                    style={styles.container}
                    navigationState={this.state}
                    renderScene={this._renderScene}
                    renderHeader={this._renderHeader}
                    onRequestChangeTab={this._handleChangeTab}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor: '#EEEEEE'

    },
    page: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    indicator: {
        backgroundColor: '#c98d41',
    },
    tabbar: {
        backgroundColor: 'white'
    },
    label: {
        color: 'black',
        fontWeight: 'bold',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize:12
    }
});

Please give me friendly advice )

Most helpful comment

Very useful library, but unfortunately (in my opinion) - poorly documented.
Refused it

>All comments

Very useful library, but unfortunately (in my opinion) - poorly documented.
Refused it

Was this page helpful?
0 / 5 - 0 ratings

Related issues

quandevelopment picture quandevelopment  ·  4Comments

DennisMuchiri picture DennisMuchiri  ·  4Comments

sohel-tech picture sohel-tech  ·  3Comments

biks152207 picture biks152207  ·  4Comments

aymkin picture aymkin  ·  4Comments