Magas
Magas

Reputation: 514

Extract formatted_address from JSON return from Google Maps API

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

  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=__API_KEY__')
      .then(results => {
          this.setState({
              place: results[0].formated_address
          })
          .catch((error) => {
            this.setState({ error: error.message })
          });
      });
  }

How do I do that?

Upvotes: 0

Views: 2444

Answers (1)

Mohamed Khalil
Mohamed Khalil

Reputation: 3126

  • first you need to call the api after getCurrentPosition is finished
  • be sure your api key is correct and has access to the geocode api
  • access the first place address from response.data.results[0].formatted_address note that i changed results to response since it is more descriptive name also note that formatted_address with double t
  • finally catch is called after then not after setState

full working example

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

Upvotes: 1

Related Questions