Use Geocoder to return the device address

1

I want to put in my application a button that, when pressed, returns the current address of the cell phone.

Latitude and longitude I'm able to return correctly, and to convert this data into an address I got to the react-native library -geocoder .

My current code looks like this:

import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import Geocoder from 'react-native-geocoder';
 // 0.4.8

class GeolocationExample extends Component {
  constructor(props) {
    super(props);

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

  refresh = () => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  };

  render() {
    Geocoder.geocodePosition(this.state.latitude,this.state.longitude)
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>

        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
         <Button
          style={{ marginTop: 30 }}
          onPress={() => { this.refresh(); }}
          title="Refresh"
        />
      </View>
    );
  }
}

export default GeolocationExample;

As far as I understand in Geocoder.geocodePosition(this.state.latitude,this.state.longitude) would be returning the address, however I did not understand how to get this data from there.

The code in the Snack: link

    
asked by anonymous 04.10.2017 / 22:54

1 answer

1

The Geocoder.geocodePosition returns a Promise, so you should capture the address with .then . Ex:

Geocoder.geocodePosition(coords) .then(res => { this.setState({address: res[0].formatedAddress} ); console.log(res[0].formattedAddress)} )

    
06.10.2017 / 15:09