Extract formatted_address from JSON return from Google Maps API

0

I'm using the google maps API to do reverse geocoding but I'm not able to extract formatted_address

import React, { Component } from 'react';
import {
  Platform,
  Text,
  View
} from 'react-native';
import axios from 'axios';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);

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

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

    axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude +'&key=AIzaSyDtQ0zsYr1c_V7UmlHFekeFIGM2nDwnDEA')
      .then(results => {
          this.setState({
              place: results[0].formated_address
          })
          .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>
    );
  }
}

How do I do it?

    
asked by anonymous 25.10.2017 / 22:17

2 answers

1

Code working (I got the answer in stackoverflow.com ):

componentWillMount() {
  navigator.geolocation.getCurrentPosition(
  (position) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      error: null,
    }, () => this.getGeocode()); // call the api after getCurrentPosition is finished
  },
   (error) => this.setState({ error: error.message }),
   { enableHighAccuracy: true, timeout: 20000 },
 );

}
getGeocode() {
 axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude +'&key=__API_KEY__') // be sure your api key is correct and has access to the geocode api
.then(response => {
  console.log(response);
    this.setState({
        place: response.data.results[0].formatted_address // access from response.data.results[0].formatted_address
    })
 }).catch((error) => { // catch is called after then
   this.setState({ error: error.message })
 });
}
    
30.10.2017 / 21:27
0

The problem is that you are using the state before it updates. Try running with the willMount like this:

componentWillMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });

        axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ position.coords.longitude +','+ position.coords.latitude +'&key=AIzaSyDtQ0zsYr1c_V7UmlHFekeFIGM2nDwnDEA')
          .then(results => {
              this.setState({
                  place: results[0].formated_address
              })
             .catch((error) => {
                this.setState({ error: error.message })
             });
          });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000 },
    );
  }
    
30.10.2017 / 14:37