从Google Maps API中提取JSON返回的formatted_address

时间:2017-10-25 20:23:55

标签: react-native reverse-geocoding

我正在使用google maps API进行反向地理编码,但我无法提取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 })
          });
      });
  }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

  • 首先,您需要在getCurrentPosition完成后调用api
  • 确保您的api密钥正确并且可以访问geocode api
  • 从response.data.results [0] .formatted_address访问第一个地址注意我将结果更改为响应,因为它是更具描述性的名称还请注意formatted_address with double t
  • 最后在没有setState
  • 之后调用catch

完整的工作示例

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