开发者

Obtaining more than 20 results with Google Places API

开发者 https://www.devze.com 2023-03-26 03:01 出处:网络
I want to develop a map application which will display the banks near a given place. I use the Places library to search and everytime it just retur开发者_C百科n 20 results. What should I do if I want

I want to develop a map application which will display the banks near a given place.

I use the Places library to search and everytime it just retur开发者_C百科n 20 results. What should I do if I want more results?


UPDATE: Since I originally wrote this answer, the API was enhanced, making this answer out of date (or, at least, incomplete). See How to get 20+ result from Google Places API? for more information.

ORIGINAL ANSWER:

The documentation says that the Places API returns up to 20 results. It does not indicate that there is any way to change that limit. So, the short answer seems to be: You can't.

Of course, you might be able to sort of fake it by doing queries for several locations, and then merging/de-duplicating the results. It's kind of a cheap hack, though, and might not work very well. And I'd check first to make sure it doesn't violate the terms of service.


Now it is possible to have more than 20 results (but up to 60), a parameter page_token was added to the API.

Returns the next 20 results from a previously run search. Setting a page_token parameter will execute a search with the same parameters used previously — all parameters other than page_token will be ignored.

Also you can refer to the accessing additional results section to see an example on how to do the pagination.


In response to Eduardo, Google did add that now, but the Places documentation also states:

The maximum number of results that can be returned is 60.

so it still has a cap. also FYI, there is a delay for when the "next_page_token" will become valid, as Google states:

There is a short delay between when a next_page_token is issued, and when it will become valid.

and here is the official Places API docs:

https://developers.google.com/places/documentation/


Here's code sample that will look for additional results

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Script.Serialization;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={args[0]}&radius={args[1]}&type=restaurant&keyword={args[2]}&key={args[3]}";

            dynamic res = null;
            var places = new List<PlacesAPIRestaurants>();
            using (var client = new HttpClient())
            {
                while (res == null || HasProperty(res, "next_page_token"))
                {
                    if (res != null && HasProperty(res, "next_page_token"))
                    {
                        if (url.Contains("pagetoken"))
                            url = url.Split(new string[] { "&pagetoken=" }, StringSplitOptions.None)[0];
                        url += "&pagetoken=" + res["next_page_token"];

                    }
                    var response = client.GetStringAsync(url).Result;
                    JavaScriptSerializer json = new JavaScriptSerializer();
                    res = json.Deserialize<dynamic>(response);
                    if (res["status"] == "OK")
                    {
                        foreach (var place in res["results"])
                        {
                            var name = place["name"];
                            var rating = HasProperty(place,"rating") ? place["rating"] : null;
                            var address = place["vicinity"];
                            places.Add(new PlacesAPIRestaurants
                            {
                                Address = address,
                                Name = name,
                                Rating = rating
                            });
                        }
                    }
                    else if (res["status"] == "OVER_QUERY_LIMIT")
                    {
                        return;
                    }
                }
            }
        }

        public static bool HasProperty(dynamic obj, string name)
        {
            try
            {
                var value = obj[name];
                return true;
            }
            catch (KeyNotFoundException)
            {
                return false;
            }
        }
    }
}

Hope this saves you some time.


Not sure you can get more.

The Places API returns up to 20 establishment results.

http://code.google.com/apis/maps/documentation/places/#PlaceSearchResponses


You can scrape Google Places results and follow pagination to get 200-300 places for a specific location (from 10 to 15 pages of search results).

Alternatively, you can use SerpApi to access extracted data from Google Places. It has a free trial.

Full example

# Package: https://pypi.org/project/google-search-results

from serpapi import GoogleSearch
import os

params = {
    "api_key": os.getenv("API_KEY"),
    "engine": "google",
    "q": "restaurants",
    "location": "United States",
    "tbm": "lcl",
    "start": 0
}

search = GoogleSearch(params)
data = search.get_dict()

for local_result in data['local_results']:
    print(
        f"Position: {local_result['position']}\nTitle: {local_result['title']}\n"
    )

while ('next' in data['serpapi_pagination']):
    search.params_dict["start"] += len(data['local_results'])
    data = search.get_dict()

    print(f"Current page: {data['serpapi_pagination']['current']}\n")

    for local_result in data['local_results']:
        print(
            f"Position: {local_result['position']}\nTitle: {local_result['title']}\n"
        )

Output

Current page: 11

Position: 1
Title: Carbone

Position: 2
Title: Elmer's Restaurant (Palm Springs, CA)

Position: 3
Title: The Table Vegetarian Restaurant

...

Disclaimer: I work at SerpApi.


If the problem is that not all banks that exists inside the search radius might not be returned, I would suggest limiting the search radius instead of issuing multiple automated queries.

Set the radius to some value in which it is impossible to get more then 20 (60) banks. Then make it easy (GUI-wise) for the user to hammer out more queries manually - sort of painting a query.

Returning thousands of banks in a larger region will likely require you to rely on your own database of banks - which could be achievable if you work on it systematically.

0

精彩评论

暂无评论...
验证码 换一张
取 消