Problems returning address through geolocation

2

I'm trying to use the react-native-geocoder library to return the address through the latitude and longitude of the device .

By replying to other question and some more research, I came to this code :

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

Geocoder.apiKey = 'AIzaSyDtQ0zsYr1c_V7UmlHFekeFIGM2nDwnDEA';

export default class testeGeocoder extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      place: 'Localizando endereço...',
      error: null,
    };
  }

  componentDidMount() {
    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 },
    );

    Geocoder.geocodePosition({ lat: this.state.latitude, long: this.state.longitude})
      .then(res => {
          this.setState({
              place: res[0].formatedAddress
          })
          .catch((error) => {
            this.setState({ error: error.message })
          });
      });
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>{this.state.place.toString()}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

AppRegistry.registerComponent('testeGeocoder', () => testeGeocoder);

But this returns me to the correct latitude and longitude, but stays Localizando endereço... and never returns.

Where am I going wrong?

    
asked by anonymous 23.10.2017 / 20:05

1 answer

1

The problem is in componentDidMount , getCurrentPosition is an asynchronous function, so when you call Geocoder.geocodePosition in its state latitude and longitude are still null . Try to put Geocoder.geocodePosition inside getCurrentPosition as below:

componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
         Geocoder.geocodePosition( { lat: position.coords.latitude, lng: position.coords.longitude})
          .then(res => {
              this.setState({
                  place: res[0].formatedAddress
              });
          });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );

  }
    
24.10.2017 / 16:13