I am trying to use a nearby search with the Google Places API and I am trying to get the next page of results. I understand the next page token doesn't become valid for a couple seconds after your previous request. However, the token NEVER returns results with the 'OK' status response.
How do I get a consistent, "OK" status response from the nearby search request?
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');
current output: [ERROR] Timeout waiting for valid next page token.
As you can see I set a timeout condition to break the loop if it takes longer than 30 seconds. However, I have tested the code without that and let it wait for an 'OK' response for minutes without success.
Also note that I didn't include the initialization of next_page_token
variable, but it does indeed have the next page token as its value.