Extract formatted_address from JSON return from Google Maps API

Asked

Viewed 802 times

0

I’m using the google maps API to do the reverse geocoding but I’m not getting the 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?

2 answers

1


Code working (I got the answer on stackoverflow.with):

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 })
 });
}

0

The problem is that you are using the state before it upgrade. Try to run with 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 },
    );
  }
  • It’s not, it was the format of the return that was wrong, it has to be like this: response.data.results[0].formatted_address

Browser other questions tagged

You are not signed in. Login or sign up in order to post.