首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Google返回的JSON中提取formatted_address

从Google返回的JSON中提取formatted_address
EN

Stack Overflow用户
提问于 2017-10-25 20:23:55
回答 1查看 1.9K关注 0票数 0

我正在使用google进行反向地理编码,但我无法提取formatted_address

代码语言:javascript
复制
  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 })
          });
      });
  }

我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-26 00:53:13

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

全工作实例

代码语言:javascript
复制
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 })
 });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46941447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档