javascript 如何有效地从Google Places API检索数据

nlejzf6q  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(152)

我正在尝试从Google Places API检索数据,它是JSON格式的。每个查询最多返回20个结果,如果有更多的结果,则会在响应中出现“next_page_token”。该令牌是指向下一页结果的链接,否则,它是未定义的。
我一直在尝试获取数据,但无法获得一致的结果。下面是我的代码示例:

function getdatafirsttry(url) {
  fetch(url, {
      method: 'get'
    })
    .then(response =>
      response.json())
    .then(data => {
        next_token = data.next_page_token;

        if (next_token !== undefined) {
          url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=32.0333332,34.7666636&radius=1500&type=restaurant&key=...&fields=opening_hours,photos,rating.json&pagetoken=' + next_token;
          toContinue = true;
        } else {
          toContinue = false
        }
      }
      //Next page token
      function alltogheter(url) {
        getdatafirsttry(url);
      }
      getdatafirsttry(url);
iezvtpos

iezvtpos1#

伪代码比实际的JS多一点,但概念如下:

const yourGoogleMapsFunction = async (params you need, nextToken, listOfPlaces) => {

let options = {
    method: 'GET',
    uri: "https://maps.googleapis.com/maps/api/nearbysearch/json",
    qs : {
        key: process.env.GOOGLE_API_KEY,
        pageToken: ...,
        radius: ...,
        location: ...
        ...
    },
    json: true
};

let response = await rp(options);

if (response && response.status === "OK" && response.results && response.results.length > 0) {
    listOfPlaces.push(... the results);
    yourGoogleMapsFunction(params you need, response.results...token, listOfPlaces);
}
};

您需要使用{}作为listOfPlaces调用它,它最终将包含所有位置
在递归调用中,还要考虑限制为最大值

相关问题