代码之家  ›  专栏  ›  技术社区  ›  KT-mongo

如何使用axios获取google地图中placeid的数据并做出反应?

  •  1
  • KT-mongo  · 技术社区  · 7 年前

    我有一个数组 restaurantsFetchedFromGoogle 它目前存储了20个以前从谷歌地图上获取的placeid。它们以这样的方式存储在数组中:

    0:"ChIJTb1qU315MhMRiL7pihnMWfg"
    1:"ChIJGZ0jXCCNMRMRrH8VHRAgEYE"
    2:"ChIJQ5jaX8eMMRMRnRoZxl6X95w"
    ...
    19:"ChIJQ5jaX8errrMRnRoZxl6X95w"
    

    现在,我尝试使用axios get请求迭代数组,例如:

    componentDidMount(){
        navigator.geolocation.getCurrentPosition(position=>{
        this.setState({geoLat:position.coords.latitude,geoLng:position.coords.longitude});
        axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${position.coords.latitude},${position.coords.longitude}&radius=50000&keyword=recensioni&type=ristorante&keyword=cena&key=MYAPIKEY`)
             .then(response => this.setState({restaurantsFetchedFromGoogle:response.data.results}));
        });
        this.state.restaurantsFetchedFromGoogle.map(item=>{
          axios.get(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${item.place_id}&key=AIzaSyCZ7rgMN34kWkGvr8Pzkf_8nkT7W6gowBA`)
               .then(response => this.setState({placeId:response.data}))
               .catch(err =>{
               console.log(err);
               console.log(err.response.data.error);
        });
      });
        axios.get('/restaurants.json')
             .then(response =>this.setState({restaurants:response.data}));
      }
    

    第一个和第三个axios请求通过,而不是第二个。我做错什么了?

    1 回复  |  直到 7 年前
        1
  •  1
  •   nxSolari    7 年前

    添加错误处理程序以记录错误消息!这应该可以告诉你为什么请求失败。

    this.state.restaurantsFetchedFromGoogle.map(item=>{
    axios.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+ 
    item + '&key=MYAPIKEY')
       .then(response => this.setState({placeId:response.data}))
       .catch(err => {
         console.log(err)                     //Axios entire error message
         console.log(err.response.data.error) //Google API error message 
       })
    });
    

    即使没有.catch,也可以使用chrome开发工具在开发工具的network选项卡下查看错误。

    如果你仍然有问题后-张贴具体的错误信息,我会采取一个看看。