我正在尝试通过Google Places API使用附近的搜索,并且正在尝试获取下一页的结果。我了解下一页令牌在您上次请求后的几秒钟之内无效。但是,令牌永远不会返回状态为“ OK”的结果。
如何从附近的搜索请求中获得一致的“确定”状态响应?
const location = {latitude: 37.822919, longitude: -122.000685};
const place_types = ["premise", "establishment"];
//Get initial response (which works) and includes next page token if > 20 results
const response = await fetch(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json? location=' +
location.latitude + ',' + location.longitude + '&radius=150' +
'&types=' + place_types.toString() + '&key=' + API_KEY);
const responseJson = await response.json();
let status, responseJson2;
let now = new Date();
do {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
const response2 = await fetch(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' +
'key=' + API_KEY + '&pagetoken=' + next_page_token,
);
responseJson2 = await response2.json();
status = responseJson2.status;
console.log(status)
if (new Date() - now > 10000) {
console.log('[ERROR] Timeout waiting for valid next page token.');
break;
}
} while (status === 'INVALID_REQUEST');
当前输出:[ERROR] Timeout waiting for valid next page token.
如您所见,如果设置时间超过30秒,我将设置超时条件以中断循环。但是,我已经测试了没有此代码的代码,并且让它等待几分钟的“ OK”响应而没有成功。
还请注意,我没有包括next_page_token
变量的初始化,但它确实具有下一页标记作为其值。
在每个新请求的末尾添加一个请求计数,以避免Google缓存的响应:
const location = {latitude: 37.822919, longitude: -122.000685};
const place_types = ["premise", "establishment"];
//Get initial response (which works) and includes next page token if > 20 results
const response = await fetch(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json? location=' +
location.latitude + ',' + location.longitude + '&radius=150' +
'&types=' + place_types.toString() + '&key=' + API_KEY);
const responseJson = await response.json();
let status, responseJson2;
let now = new Date();
let request_count = 0;
do {
await new Promise(resolve => {
setTimeout(resolve, 100);
});
const response2 = await fetch(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' +
'key=' + API_KEY + '&pagetoken=' + next_page_token + '&request_count=' + request_count,
);
responseJson2 = await response2.json();
status = responseJson2.status;
console.log(status)
if (new Date() - now > 10000) {
console.log('[ERROR] Timeout waiting for valid next page token.');
break;
}
request_count++;
} while (status === 'INVALID_REQUEST');