我在我的Web应用程序中使用带有RestClient gem的Google Web Service API来查找具有特定字符串的企业。例如,传入'car dealership'应该返回我附近所有汽车经销商的结果。
目前,我可以得到第一页的结果。已经传入了next_page_token,但仍然无法得到相同的结果。我不知道我的代码哪里出错了。真的很感谢帮助!
SEARCH_ENDPOINT = 'https://maps.googleapis.com/maps/api/place/textsearch/json'.freeze
DETAILS_ENDPOINT = 'https://maps.googleapis.com/maps/api/place/details/json'.freeze
def initialize(query)
@params = {
query: query,
fields: 'name,formatted_phone_number,formatted_address,website,place_id,types',
key: API_KEY
}
@results = []
end
def extract
loop do
page_token = @results.last&.dig('next_page_token')
page = fetch_page(page_token)
break if page.nil?
@results += page['results']
break if page['next_page_token'].nil?
# Add a delay to avoid OVER_QUERY_LIMIT errors (10 requests per second)
sleep(10)
end
@results = @results.map do |result|
result_details = fetch_place_details(result['place_id'])
result.merge(result_details)
end
upsert_businesses(clean_data(@results))
end
private
def fetch_page(page_token)
response = RestClient.get(SEARCH_ENDPOINT, params: @params.merge({page_token: page_token}))
return nil unless response.code == 200
JSON.parse(response.body)
end
def fetch_place_details(place_id)
response = RestClient.get(DETAILS_ENDPOINT, params: @params.merge({place_id: place_id}))
return {} unless response.code == 200
details = JSON.parse(response.body)['result']
details || {}
end
将下一页标记传递给参数,期望新的响应页。但得到同样的结果。
1条答案
按热度按时间68de4m5k1#
下面这行代码每次都会删除page_token:
此外,page_token参数的正确语法是
pagetoken
(至少在Ruby中是这样)。