Code Monkey home page Code Monkey logo

python-google-places's Introduction

python-google-places

python-google-places provides a simple wrapper around the experimental Google Places API.

Installation

pip install https://github.com/slimkrazy/python-google-places/zipball/master

OR

pip install python-google-places

OR

Download source and then:

python setup.py install

Prerequisites

A Google API key with Google Places API Web Service and Google Maps Geocoding API activated against it. Please check the Google API console, here: http://code.google.com/apis/console

Usage

Code is easier to understand than words, so let us dive right in:

from googleplaces import GooglePlaces, types, lang

YOUR_API_KEY = 'AIzaSyAiFpFd85eMtfbvmVNEYuNds5TEF9FjIPI'

google_places = GooglePlaces(YOUR_API_KEY)

# You may prefer to use the text_search API, instead.
query_result = google_places.nearby_search(
        location='London, England', keyword='Fish and Chips',
        radius=20000, types=[types.TYPE_FOOD])
# If types param contains only 1 item the request to Google Places API
# will be send as type param to fullfil:
# http://googlegeodevelopers.blogspot.com.au/2016/02/changes-and-quality-improvements-in_16.html

if query_result.has_attributions:
    print query_result.html_attributions


for place in query_result.places:
    # Returned places from a query are place summaries.
    print place.name
    print place.geo_location
    print place.place_id

    # The following method has to make a further API call.
    place.get_details()
    # Referencing any of the attributes below, prior to making a call to
    # get_details() will raise a googleplaces.GooglePlacesAttributeError.
    print place.details # A dict matching the JSON response from Google.
    print place.local_phone_number
    print place.international_phone_number
    print place.website
    print place.url

    # Getting place photos

    for photo in place.photos:
        # 'maxheight' or 'maxwidth' is required
        photo.get(maxheight=500, maxwidth=500)
        # MIME-type, e.g. 'image/jpeg'
        photo.mimetype
        # Image URL
        photo.url
        # Original filename (optional)
        photo.filename
        # Raw image data
        photo.data


# Are there any additional pages of results?
if query_result.has_next_page_token:
    query_result_next_page = google_places.nearby_search(
            pagetoken=query_result.next_page_token)


# Adding and deleting a place
try:
    added_place = google_places.add_place(name='Mom and Pop local store',
            lat_lng={'lat': 51.501984, 'lng': -0.141792},
            accuracy=100,
            types=types.TYPE_HOME_GOODS_STORE,
            language=lang.ENGLISH_GREAT_BRITAIN)
    print added_place.place_id # The Google Places identifier - Important!
    print added_place.id

    # Delete the place that you've just added.
    google_places.delete_place(added_place.place_id)
except GooglePlacesError as error_detail:
    # You've passed in parameter values that the Places API doesn't like..
    print error_detail

Reference

googleplaces.GooglePlacesError
googleplaces.GooglePlacesAttributeError


googleplaces.geocode_location(location, sensor=False, api_key=None)
  Converts a human-readable location to a Dict containing the keys: lat, lng.
  Raises googleplaces.GooglePlacesError if the geocoder fails to find the
  specified location.


googleplaces.GooglePlaces
  nearby_search(**kwargs)
    Returns googleplaces.GooglePlacesSearchResult
      kwargs:
        keyword  -- A term to be matched against all available fields, including but
                    not limited to name, type, and address (default None)

        language -- The language code, indicating in which language the results
                    should be returned, if possble. (default en)

        lat_lng  -- A dict containing the following keys: lat, lng (default None)

        location -- A human readable location, e.g 'London, England' (default None)

        name     -- A term to be matched against the names of the Places.
                    Results will be restricted to those containing the passed name value. (default None)

        pagetoken-- Optional parameter to force the search result to return the next
                    20 results from a previously run search. Setting this parameter
                    will execute a search with the same parameters used previously. (default None)

        radius   -- The radius (in meters) around the location/lat_lng to restrict
                    the search to. The maximum is 50000 meters (default 3200)

        rankby   -- Specifies the order in which results are listed:
                    'prominence' (default) or 'distance' (imply no radius argument)

        sensor   -- Indicates whether or not the Place request came from a device
                    using a location sensor (default False)

        type     -- An optional type used for restricting the results to Places (default None)

        types    -- An optional list of types, restricting the results to Places (default []).
                    This kwarg has been deprecated in favour of the 'type' kwarg.



  text_search(**kwargs)
    Returns googleplaces.GooglePlacesSearchResult
      kwargs:
        query  --  The text string on which to search, for example:
                   "Restaurant in New York".

        lat_lng  -- A dict containing the following keys: lat, lng (default None)

        location -- A human readable location, e.g 'London, England' (default None)

        language -- The language code, indicating in which language the results
                    should be returned, if possble. (default en)

        pagetoken-- Optional parameter to force the search result to return the next
                    20 results from a previously run search. Setting this parameter
                    will execute a search with the same parameters used previously. (default None)

        radius   -- The radius (in meters) around the location/lat_lng to restrict
                    the search to. The maximum is 50000 meters (default 3200)

        type     -- An optional type used for restricting the results to Places (default None)

        types    -- An optional list of types, restricting the results to Places (default [])
                    This kwarg has been deprecated in favour of the 'type' kwarg.

  autocomplete(**kwargs):
    Returns googleplaces.GoogleAutocompleteSearchResult
      kwargs:
        input  --   The text string on which to search, for example:
                    "Hattie B's".

        lat_lng -- A dict containing the following keys: lat, lng (default None)

        location -- A human readable location, e.g 'London, England' (default None)

        radius   -- The radius (in meters) around the location to which the
                    search is to be restricted. The maximum is 50000 meters.
                    (default 3200)

        language -- The language code, indicating in which language the
                    results should be returned, if possible. (default lang.ENGLISH)

        types    -- A type to search against. See `types.py` "autocomplete types"
                    for complete list
                    https://developers.google.com/places/documentation/autocomplete#place_types.

        components -- An optional grouping of places to which you would
                    like to restrict your results. An array containing one or
                    more tuples of:
                    * country: matches a country name or a two letter ISO 3166-1 country code.
                    eg: [('country','US')]

  radar_search(**kwargs)
    Returns googleplaces.GooglePlacesSearchResult
      kwargs:
        keyword  -- A term to be matched against all available fields, including
                    but not limited to name, type, and address (default None)

        name     -- A term to be matched against the names of Places. Results will
                    be restricted to those containing the passed name value.

        opennow  -- Returns only those Places that are open for business at the time
                    the query is sent

        lat_lng  -- A dict containing the following keys: lat, lng (default None)

        location -- A human readable location, e.g 'London, England' (default None)

        language -- The language code, indicating in which language the results
                    should be returned, if possble. (default en)

        radius   -- The radius (in meters) around the location/lat_lng to restrict
                    the search to. The maximum is 50000 meters (default 3200)

        sensor   -- Indicates whether or not the Place request came from a
                    device using a location sensor (default False).

        type     -- An optional type used for restricting the results to Places (default None)

        types    -- An optional list of types, restricting the results to Places (default [])
                    This kwarg has been deprecated in favour of the 'type' kwarg.

  get_place(**kwargs)
    Returns a detailed instance of googleplaces.Place
      place_id  -- The unique Google identifier for the required place.

      language   -- The language code, indicating in which language the results
                    should be returned, if possble. (default en)

      sensor     -- Indicates whether or not the Place request came from a
                    device using a location sensor (default False).


  checkin(place_id, sensor=False)
    Checks in an anonymous user in to the Place that matches the place_id.
      kwargs:
        place_id   -- The unique Google identifier for the required place.

        sensor      -- Boolean flag denoting if the location came from a device
                       using its location sensor (default False).


  add_place(**kwargs)
    Returns a dict containing the following keys: place_id, id.
      kwargs:
        name        -- The full text name of the Place. Limited to 255
                       characters.

        lat_lng     -- A dict containing the following keys: lat, lng.

        accuracy    -- The accuracy of the location signal on which this request
                       is based, expressed in meters.

        types       -- The category in which this Place belongs. Only one type
                       can currently be specified for a Place. A string or
                       single element list may be passed in.

        language    -- The language in which the Place's name is being reported.
                       (default googleplaces.lang.ENGLISH).

        sensor      -- Boolean flag denoting if the location came from a device
                       using its location sensor (default False).


  delete_place(place_id, sensor=False)
    Deletes a place from the Google Places database.
      kwargs:
        place_id   -- The unique Google identifier for the required place.

        sensor      -- Boolean flag denoting if the location came from a
                       device using its location sensor (default False).


googleplaces.GoogleAutocompleteSearchResult
  raw_response
    Returns the raw JSON response from the Autocomplete API.

  predictions
    Returns an array of prediction objects.


googleplaces.GooglePlacesSearchResult
  raw_response
    The raw JSON response returned by the Google Places API.

  places
    A list of summary googleplaces.Place instances.

  has_attributions()
    Returns a flag indicating if the search result has html attributions that
    must be displayed.

  html_attributions()
    Returns a List of String html attributions that must be displayed along with
    the search results.


googleplaces.Prediction
  description
    String representation of a Prediction location. Generally contains
    name, country, and elements contained in the terms property.

  id
    Returns a unique stable identifier denoting this Place. This identifier
    may not be used to retrieve information about this Place, but can be used
    to consolidate data about this Place, and to verify the identity of a
    Place across separate searches

  matched_substrings
    Returns the placement and offset of the matched strings for this search.
    A an array of dicts, each with the keys 'length' and 'offset', will be returned.

  place_id
    Returns the unique stable identifier denoting this place.
    This identifier may be used to retrieve information about this
    place.
    This should be considered the primary identifier of a place.

  reference
    Returns a unique identifier for the Place that can be used to fetch full
    details about it. It is recommended that stored references for Places be
    regularly updated. A Place may have many valid reference tokens.

  terms
    A list of terms which build up the description string
    A an array of dicts, each with the keys `offset` and `value`, will be returned.

  types
    Returns a List of feature types describing the given result.

  place
    Returns a Dict representing the full response from the details API request.
    This property will raise a googleplaces.GooglePlacesAttributeError if it is
    referenced prior to get_details()

  get_details(**kwargs)
    Retrieves full information on the place matching the reference.
      kwargs:
        language   -- The language code, indicating in which language the
                      results should be returned, if possible. This value defaults
                      to the language that was used to generate the
                      GooglePlacesSearchResult instance.


googleplaces.Place
  reference
    (DEPRECATED) Returns a unique identifier for the Place that can be used to
    fetch full details about it. It is recommended that stored references for
    Places be regularly updated. A Place may have many valid reference tokens.

  id
    (DEPECATED) Returns a unique stable identifier denoting this Place. This
    identifier may not be used to retrieve information about this Place, but
    can be used to consolidate data about this Place, and to verify the identity
    of a Place across separate searches.

  place_id
    A textual identifier that uniquely identifies a place. To retrieve information
    about the place, pass this identifier in the placeId field of a Places API
    request.

  icon
    contains the URL of a suggested icon which may be displayed to the user when
    indicating this result on a map.

  types
    Returns a List of feature types describing the given result.

  geo_location
    Returns the geocoded latitude,longitude value for this Place.

  name
    Returns the human-readable name for the Place.

  vicinity
    Returns a feature name of a nearby location. Often this feature refers to a
    street or neighborhood.

  rating
    Returns the Place's rating, from 0.0 to 5.0, based on user reviews.

  details
    Returns a Dict representing the full response from the details API request.
    This property will raise a googleplaces.GooglePlacesAttributeError if it is
    referenced prior to get_details()

  photos
    returns a list of available googleplaces.Photo objects.

  formatted_address
    Returns a string containing the human-readable address of this place. Often
    this address is equivalent to the "postal address".
    This property will raise a googleplaces.GooglePlacesAttributeError if it is
    referenced prior to get_details()

  local_phone_number
    Returns the Place's phone number in its local format.
    This property will raise a googleplaces.GooglePlacesAttributeError if it is
    referenced prior to get_details()

  international_phone_number
    Returns the Place's phone number in international format. International
    format includes the country code, and is prefixed with the plus (+) sign.
    This property will raise a googleplaces.GooglePlacesAttributeError if it is
    referenced prior to get_details()

  website
    Returns the authoritative website for this Place, such as a business'
    homepage.

  url
    Returns the official Google Place Page URL of this Place.

  has_attributions
    Returns a flag indicating if the search result has html attributions that
    must be displayed. along side the detailed query result.

  html_attributions
    Returns a List of String html attributions that must be displayed along with
    the detailed query result.

  checkin()
    Checks in an anonynomous user in.

  get_details(**kwargs)
    Retrieves full information on the place matching the place_id.
      kwargs:
        language   -- The language code, indicating in which language the
                      results should be returned, if possible. This value defaults
                      to the language that was used to generate the
                      GooglePlacesSearchResult instance.

googleplaces.Photo
  orig_height
    the maximum height of the origin image.

  orig_width
    the maximum height of the origin image.

  html_attributions
     Contains any required attributions. This field will always be present,
     but may be empty.

  photo_reference
     A string used to identify the photo when you perform a Photo request
     via the get method.

  get
    Fetches the actual photo data from the Google places API.

  mimetype
    Specifies the mimetype if the fetched image. This property is only
    available after the get API has been invoked.

  filename
    Specifies the filename of the fetched image. This property is only
    available after the get API has been invoked.

  data
    The binary data of the image. This property is only available after the
    get API has been invoked.

  url
    The url of the image. This property is only available after the get API
    has been invoked.

python-google-places's People

Contributors

adamchainz avatar alexeysofin avatar beamerblvd avatar commadelimited avatar daniil-shumko avatar drootnar avatar fela avatar isms avatar joejasinski avatar jpulec avatar justinbricker-eb avatar keradus avatar kingb avatar nspaeth avatar pidelport avatar pplayground avatar prateekjassal avatar ruhman avatar scottcode avatar slimkrazy avatar yati-sagade avatar yyl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-google-places's Issues

KeyError: 'html_attributions'

Hello,
I've been having some difficult with the python googleplaces module. Yesterday, I imported some Google places data using code similar to that below. I kept importing until I expectedly reached my free quota and received a OVER_QUERY_LIMIT exception. 24 hours later, I tried to do another data pull. However, this time, I am getting a completely different exception:

KeyError: 'html_attributions'

I don't know why the same code would return a new exception, and this doesn't seem to be related to quota overage. However, I'm not sure why this would be occurring. I have installed the newest stable version of python-google-places. Any ideas?

In [1]: from django.conf import settings
In [2]: from googleplaces import GooglePlaces, types, lang, GooglePlacesError
In [3]: radius=250
In [4]: longitude = '-87.776812'
In [5]: lattitude = '41.870851'
In [6]: google_places = GooglePlaces("**********")
In [7]: query_result = google_places.query(
   ...:             lat_lng={'lat':lattitude, 'lng':longitude,}, radius=radius, )
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/jaz/sites/mysite/lib/python2.6/site-packages/django_extensions/management/commands/shell_plus.pyc in <module>()
      1 query_result = google_places.query(
----> 2             lat_lng={'lat':lattitude, 'lng':longitude,}, radius=radius, )

/jaz/sites/mysite/lib/python2.6/site-packages/googleplaces/__init__.pyc in query(self, language, keyword, location, lat_lng, name, radius, rankby, sensor, types)
    198                 GooglePlaces.QUERY_API_URL, self._request_params)
    199         _validate_response(url, places_response)
--> 200         return GooglePlacesSearchResult(self, places_response)
    201 
    202     def checkin(self, reference, sensor=False):

/jaz/sites/mysite/lib/python2.6/site-packages/googleplaces/__init__.pyc in __init__(self, query_instance, response)
    334         for place in response['results']:
    335             self._places.append(Place(query_instance, place))
--> 336         self._html_attributions = response['html_attributions']
    337 
    338     @property

KeyError: 'html_attributions'

Getting inconsistent list of POIs when changing radius

Hi! Thanks for writing this. It is very useful!

The problem I am facing is that given a lat/lng, I want to get the POIs nearby based on a radius. Here is an example:

mydict = {}
mydict['lat'] = 38.72961
mydict['lng'] = -75.54783

You may prefer to use the text_search API, instead.

query_result = google_places.nearby_search(
lat_lng=mydict,
types=[types.TYPE_POINT_OF_INTEREST],
radius=3800
)

If I modify the radius to be 7000, there are POIs that disappear when it should be the opposite. It should display more POIs, if available, right?

List with radius of 3800(Ignore the "Yes" and "No"):
No Subway
No Punkin Chunkin
No Royal Farms
No Cardtronics ATM
No ATM (Royal Farms)
No Sonic Drive-In
No Cigars For Less
No Mary Kay Cosmetics
No Scott's Furniture Inc
Yes Horney Industrial Electronics
No Nothing Better LLC
No kristys kakes
No Bridgeville Rifle and Pistol Club
No LR Construction
No Sussex Tree Inc
No Circle C Outfit
No Bay To Beach Builders
No Dance Moves & Manners
Yes DEP PIPES USA LLC
No Fellowship Health Resources

List with radius of 7000(Ignore the "No"):
No Subway
No Royal Farms
No Punkin Chunkin
No Cardtronics ATM
No Walgreens
No ATM (Royal Farms)
No Warren Truss Co Inc
No Dollar General
No Sonic Drive-In
No Cigars For Less
No Tractor Supply Co.
No Bridgeville Emporium
No Ryan Homes
No Fireside Hearth & Home
No Scott's Furniture Inc
No Phillis Wheatley Elementary School
No Jeff's Taproom & Grille
No US Post Office
No Barton's Mini Storage
No Four Paws Animal Hospital

Question about the google.places.text_search

Hi,

I was using your library to query the google places api and I found out that I get the error OVER_QUERY_LIMIT. I've read that this is due to the limit google puts to the user queries to its API (2,500 free requests per day or 50 requests per second) That's why I'd like to know if there is any way of limiting the number of results from the query, so I don't exceed that limit.

Thanks,

Felix.

Location parameter

Minor documentation issue:

location='London, England' is an incorrect type in readme.rst

location โ€” The latitude/longitude around which to retrieve place information. This must be specified as latitude,longitude..

radius โ€” Defines the distance (in meters) within which to return place results. The maximum allowed radius is 50000 meters.

Also

types (deprecated) ....

https://developers.google.com/places/web-service/search

I included the bullet about the 50,000 meters because I believe this is enough to cover the entire globe. I.e., for people who want to do a name search that should work with any latitude and longitude.

Thanks so much, this is really great tool.

Google Places Search URL

I would like to report that after making some tests I realized that there are two differences in the client with regards to the current API (maybe they have changed the URLs):

  1. the URL for querying is now

https://maps.googleapis.com/maps/api/place/textsearch/json

instead of:

https://maps.googleapis.com/maps/api/place/search/json

  1. The parameter "keyword" is now called "query",

Thank you very much in any case for this excellent API!

Best,

PD: the "Details" URL is working other ones I have not yet tested them

Error with example

Hello,

when i run your example

from googleplaces import GooglePlaces, types, lang

YOUR_API_KEY = 'my_key'

google_places = GooglePlaces(YOUR_API_KEY)


query_result = google_places.nearby_search(
        location='London, England', keyword='Fish and Chips',
        radius=20000, types=[types.TYPE_FOOD])

i am getting this error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 542, in _generate_lat_lng_string
    else geocode_location(location))
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 103, in geocode_location
    {'address': location, 'sensor': str(sensor).lower()})
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 71, in _fetch_remote_json
    request_url, response = _fetch_remote(service_url, params, use_http_post)
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 54, in _fetch_remote
    if type(v) in [str, unicode]:
NameError: name 'unicode' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/klofisch/PycharmProjects/Gmaps/Test01/test01.py", line 22, in <module>
    radius=20000, types=[types.TYPE_FOOD])
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 260, in nearby_search
    lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
  File "/usr/local/lib/python3.4/dist-packages/googleplaces/__init__.py", line 545, in _generate_lat_lng_string
    'lat_lng must be a dict with the keys, \'lat\' and \'lng\'')
ValueError: lat_lng must be a dict with the keys, 'lat' and 'lng'

getting SSL Version error

While running script mentioning in Readme file, I am getting this SSL error

urllib2.URLError: <urlopen error [Errno 1] _ssl.c:504: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number>

by doing some search, I am able to find out that it might be because of Open SSL different versions. Can you please tell me which version has been used in creating this API ?

Also if someelse also got it, then please let me know how you fixed it ?

next_page_token in nearbysearch

I noticed that there is no option for getting query result from next page. Because google place api gives at max total 60 results in 3 pages. It will be good to add the next page option.
I don't how can I edit the repository to add that, so if can anyone please do that or guide me how to do that?

Remove deprecated properties: reference & id

At what point would you like me to begin work on removing reference and id? When you do expect you'll merge development into master? Or would you like me to work on removing them before you merge? Do you want to submit two different versions to PyPi, or bump a single cohesive change containing autocomplete and removal of deprecated props?

error: dict object not callable when printing the request

I'm having issues getting the search results. I want to take the results and print them onto an HTML file. I used request to get the JSON reponse, and that worked. But now I don't know what to do with the JSON object. I've tried:

resp = requests.get(MyUrl)
data = json.loads(resp.text)
idk = IterJson(data)

def IterJson(place):
x = [place['name'], place['reference'], place['geometry']['location']['lat'],
place['geometry']['location']['lng'], place['vicinity']]
return x

But I keep getting that 'name' in the def IterJson(place) is an error.

I checked the documentation at https://developers.google.com/places/web-service/search
And in the middle of the document, under "Search Responses," is the source code for the JSON object.

I've copied it below. "name" is under "results". How can I access "name"?

{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870775,
"lng" : 151.199025
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
"id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
"name" : "Rhythmboat Cruises",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 270,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
"width" : 519
}
],
"place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
"types" : [ "travel_agency", "restaurant", "food", "establishment" ],
"vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
},
{
"geometry" : {
"location" : {
"lat" : -33.866891,
"lng" : 151.200814
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "45a27fd8d56c56dc62afc9b49e1d850440d5c403",
"name" : "Private Charter Sydney Habour Cruise",
"photos" : [
{
"height" : 426,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAL3n0Zu3U6fseyPl8URGKD49aGB2Wka7CKDZfamoGX2ZTLMBYgTUshjr-MXc0_O2BbvlUAZWtQTBHUVZ-5Sxb1-P-VX2Fx0sZF87q-9vUt19VDwQQmAX_mjQe7UWmU5lJGCOXSgxp2fu1b5VR_PF31RIQTKZLfqm8TA1eynnN4M1XShoU8adzJCcOWK0er14h8SqOIDZctvU",
"width" : 640
}
],
"place_id" : "ChIJqwS6fjiuEmsRJAMiOY9MSms",
"scope" : "GOOGLE",
"reference" : "CpQBhgAAAFN27qR_t5oSDKPUzjQIeQa3lrRpFTm5alW3ZYbMFm8k10ETbISfK9S1nwcJVfrP-bjra7NSPuhaRulxoonSPQklDyB-xGvcJncq6qDXIUQ3hlI-bx4AxYckAOX74LkupHq7bcaREgrSBE-U6GbA1C3U7I-HnweO4IPtztSEcgW09y03v1hgHzL8xSDElmkQtRIQzLbyBfj3e0FhJzABXjM2QBoUE2EnL-DzWrzpgmMEulUBLGrtu2Y",
"types" : [ "restaurant", "food", "establishment" ],
"vicinity" : "Australia"
},
{
"geometry" : {
"location" : {
"lat" : -33.870943,
"lng" : 151.190311
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "30bee58f819b6c47bd24151802f25ecf11df8943",
"name" : "Bucks Party Cruise",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 600,
"html_attributions" : [],
"photo_reference" : "CnRnAAAA48AX5MsHIMiuipON_Lgh97hPiYDFkxx_vnaZQMOcvcQwYN92o33t5RwjRpOue5R47AjfMltntoz71hto40zqo7vFyxhDuuqhAChKGRQ5mdO5jv5CKWlzi182PICiOb37PiBtiFt7lSLe1SedoyrD-xIQD8xqSOaejWejYHCN4Ye2XBoUT3q2IXJQpMkmffJiBNftv8QSwF4",
"width" : 800
}
],
"place_id" : "ChIJLfySpTOuEmsRsc_JfJtljdc",
"scope" : "GOOGLE",
"reference" : "CoQBdQAAANQSThnTekt-UokiTiX3oUFT6YDfdQJIG0ljlQnkLfWefcKmjxax0xmUpWjmpWdOsScl9zSyBNImmrTO9AE9DnWTdQ2hY7n-OOU4UgCfX7U0TE1Vf7jyODRISbK-u86TBJij0b2i7oUWq2bGr0cQSj8CV97U5q8SJR3AFDYi3ogqEhCMXjNLR1k8fiXTkG2BxGJmGhTqwE8C4grdjvJ0w5UsAVoOH7v8HQ",
"types" : [ "restaurant", "food", "establishment" ],
"vicinity" : "37 Bank St, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.867591,
"lng" : 151.201196
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
"id" : "a97f9fb468bcd26b68a23072a55af82d4b325e0d",
"name" : "Australian Cruise Group",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 242,
"html_attributions" : [],
"photo_reference" : "CnRnAAAABjeoPQ7NUU3pDitV4Vs0BgP1FLhf_iCgStUZUr4ZuNqQnc5k43jbvjKC2hTGM8SrmdJYyOyxRO3D2yutoJwVC4Vp_dzckkjG35L6LfMm5sjrOr6uyOtr2PNCp1xQylx6vhdcpW8yZjBZCvVsjNajLBIQ-z4ttAMIc8EjEZV7LsoFgRoU6OrqxvKCnkJGb9F16W57iIV4LuM",
"width" : 200
}
],
"place_id" : "ChIJrTLr-GyuEmsRBfy61i59si0",
"scope" : "GOOGLE",
"reference" : "CoQBeQAAAFvf12y8veSQMdIMmAXQmus1zqkgKQ-O2KEX0Kr47rIRTy6HNsyosVl0CjvEBulIu_cujrSOgICdcxNioFDHtAxXBhqeR-8xXtm52Bp0lVwnO3LzLFY3jeo8WrsyIwNE1kQlGuWA4xklpOknHJuRXSQJVheRlYijOHSgsBQ35mOcEhC5IpbpqCMe82yR136087wZGhSziPEbooYkHLn9e5njOTuBprcfVw",
"types" : [ "travel_agency", "restaurant", "food", "establishment" ],
"vicinity" : "32 The Promenade, King Street Wharf 5, Sydney"
}
],
"status" : "OK"
}

20 result only

The script returns 20 result only.
How to get all results?

Language settings not propagated to getDetails

When the language is set to something else than English, the getDetails() does not get notice. Perhaps the same setting should apply as YOUR_API_KEY:

google_places = GooglePlaces(YOUR_API_KEY, YOUR_LANGUAGE)

"ValueError: lat_lng must be a dict with keys, 'lat' and 'lng'" when using location parameter

My call to google places API passes in a keyword and a city, state (i.e. San Antonio, TX). It was working and all of the sudden started failing with ValueError: lat_lng must be a dict with keys, 'lat' and 'lng'. However, in the init.py file, this should only occur if it can't geocode the location. I've tried with different locations but now get the same error. Any idea what would have caused it? I haven't hit my API limits.

Deprecated and missing keys, endpoints

From the Places API docs, reference is a deprecated field, and place_id is now the recommended value to be used instead of id. Do you plan on updating this lib to use the more current standard?

Also, it appears you haven't yet implemented the Autocomplete endpoint:
https://maps.googleapis.com/maps/api/place/autocomplete

Do you plan on working on that anytime soon?

Can't figure out geocide_location

When I try to run
lat_long = google_places.geocode_location("Brighton, MA", sensor=False)

google_places is an instance of GooglePlaces (from the example).

I get the following:Traceback (most recent call last):
File "./google_places.py", line 10, in
lat_long = google_places.geocode_location("Brighton, MA", sensor=False)
AttributeError: 'GooglePlaces' object has no attribute 'geocode_location'

Could someone point me in the right direction? I notice the reference uses a 'googleplaces' object but I cannot figure out how to locate or instantiate it.
googleplaces.geocode_location(location, sensor=False)

Thanks,
Taylor

OVER_QUERY_LIMIT

I am getting an error notifying that I am over the query limit even though I haven't sent any requests today. When I call the url directly, it seems to return the json output just fine.

Code sample:

from googleplaces import GooglePlaces, types, lang

api_key = ''

google_places = GooglePlaces(api_key)
query_result = google_places.nearby_search(sensor=True,
    location="London, England", keyword="Subway")

Error Message:
googleplaces.GooglePlacesError: Request to URL https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=London%2C+England failed with response code: OVER_QUERY_LIMIT

Slow response times with GooglePlaces API; suggestions.

Hey Samuel...

My team and I are starting to implement the Places lib, along with the changes I added last week. We're noticing really high response times, upwards of 400ms in some cases. We've confirmed this by running a simple request and timing it. We also decided to take the lib out of the picture and make raw requests to the API using requests; with the same results. So it turns out that Google simply responds slowly.

We've worked out a way to get around this issue by pooling connections, bringing response times down to 200ms. That's still high, but much better. Problem is that our code uses either requests or raw httplib. We're wondering if you might be amenable to some changes to this lib that allow utilization of connection pooling. We'd be willing to write that, but didn't want to take the time if it wasn't something you'd be cool with. Thoughts?

Here's the tests we ran. It includes 3 different tests, 2 of which are commented out.

from googleplaces import ( GooglePlaces, Prediction, GoogleAutocompleteSearchResult, Place )
import time
from pprint import pprint
import requests
import httplib
import urllib

def ac_search():
    gp = GooglePlaces(GOOGLE_PLACES_API_KEY)

    q = ["H", "Ha", "Hat", "Hatt", "Hatti", "Hattie", "Hattie ", "Hattie+B", "Hattie+B%27", "Hattie+B%27s"]
    p = ["ChIJU9630bUUZIgRdUiNGWH9Cq8", "ChIJsRkJBMlAZIgRpTsxKQe5V-c", "ChIJw-Q333uDQUcREBAeDCnEAAA", "ChIJzzG3cxp1ao8RZIL7toLe0X4", "ChIJAYWNSLS4QIYROwVl894CDco",
        "ChIJLxl_1w9OZzQRRFJmfNR1QvU", "ChIJnXHPxhsq2o4R-g4StcDRoFk", "EjVKYW1lcyBSb2JlcnRzb24gUGFya3dheSwgTmFzaHZpbGxlLCBUTiwgVW5pdGVkIFN0YXRlcw",
        "ChIJP5uQRVlmZIgRFSSD7tYi39M", "Ei5KZWZmZXJzb24gU3RyZWV0LCBOYXNodmlsbGUsIFROLCBVbml0ZWQgU3RhdGVz"]
    conn = None

    start = time.time()
    print start
    # result = gp.autocomplete(input="H")
    # result = gp.autocomplete(input="Ha")
    # result = gp.autocomplete(input="Hat")
    # result = gp.autocomplete(input="Hatt")
    # result = gp.autocomplete(input="Hatti")
    # result = gp.autocomplete(input="Hattie")
    # result = gp.autocomplete(input="Hattie ")
    # result = gp.autocomplete(input="Hattie B")
    # result = gp.autocomplete(input="Hattie B'")
    # result = gp.autocomplete(input="Hattie B's")
    for i in range(0, 10):
        if conn == None:
            conn = requests.Session()
        #   conn = httplib.HTTPSConnection("maps.googleapis.com", 443)
        #url = "/maps/api/place/autocomplete/json?input=" + q[i] + "&radius=3200&sensor=false&language=en&key=" + GOOGLE_PLACES_API_KEY
        #url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + q[i] + "&radius=3200&sensor=false&language=en&key=" + GOOGLE_PLACES_API_KEY
        url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + p[i] + "&language=en&key=" + GOOGLE_PLACES_API_KEY
        request = conn.get(url)
        #pprint(request.json())
        #conn.request("GET", url)
        #response = conn.getresponse().read()
    stop = time.time()
    print stop
    print

    print stop - start
    #pprint(result.raw_response)

ac_search()

geocode_location not an attribute?

Hello, I am trying to use the geocoding feature by passing it an address. It says the below doesn't exist. Am I using this wrong?

googleplaces.geocode_location(location, sensor=False)
Converts a human-readable location to a Dict containing the keys: lat, lng.
Raises googleplaces.GooglePlacesError if the geocoder fails to find the
specified location.

My work around is using the places nearby, populating the latitude and longitude from places using a for loop, but my terrible coding is not letting this work, so I figured I'd ask if the geocode_location is supposed to still exist somewhere? I am using 1.3.

Google doesn't always return "vicinity" for place lookup

See for example this code and corresponding stack:

from googleplaces import GooglePlaces
google_service = GooglePlaces('MY_API_KEY')
place = google_service.get_place('CoQBcgAAAAKKdBb2rMvJqSrc_2w2UmTK89hv1oJ6FMZFG__WgfjlkonaegJXnLTmbUbn6vB32VoDr6D-zixAPPkrv421iqp20-UOtJRJjjInbCCAkqIL9pr5r-gioBCNQO3alkd8x-P9HSiqS3EgWpnYUqnhK7VkgTyoMwrjFFh-piuBiGfVEhBuhow_FNUxwdX5LIs4tiLFGhSkKYOUCfqHr-O1bpLtTdPRBRSHNw')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/greg/development/python/projects/dev/lib/python2.7/site-packages/googleplaces/__init__.py", line 205, in get_place
    return Place(self, place_details)
  File "/Users/greg/development/python/projects/dev/lib/python2.7/site-packages/googleplaces/__init__.py", line 262, in __init__
    self._vicinity = place_data['vicinity']
KeyError: 'vicinity'

python-google-places library returns me only 6 results

Dear all,
I have been using this library but when I execute it to search restaurants based on a text_query, it only returns me 6 results. However when I execute the call using my web browser, it returns me 20 results (+ 2 more pages "next_page_token").

image

I use the following code and I haven't seen a similar error searching on Google:

from googleplaces import GooglePlaces, types, lang
YOUR_API_KEY = 'AIzaS.....'
YOUR_QUERY = "restaurantes+el+Born+Barcelona"
google_places = GooglePlaces(YOUR_API_KEY)

query_result = google_places.text_search(
        query=YOUR_QUERY, types=[types.TYPE_FOOD])

print("Number of places: " + str(len(query_result.places)))
for place in query_result.places:
    print place.name
    print place.place_id

urllib2.URLError: <urlopen error [Errno -2] Name or service not known>

Hi everyone,
Sometimes when I call "place.get_details()" python throughs "urllib2.URLError: <urlopen error [Errno -2] Name or service not known>" error I tried to catch it by using "except urllib2.URLError:" but it did not work. Can anyone please let me know How I can deal with this?
Regards,
Shervin

Handle new NOT_FOUND error in Places API

It used to be that ZERO_RESULTS was the only "no results" error that Google would return from the Google Places API. They have added a new error and changed their meanings slightly:

  • ZERO_RESULTS indicates that the reference was valid but no longer refers to a valid result. This may occur if the establishment is no longer in business.
  • NOT_FOUND indicates that the referenced location was not found in the Places database.

When they made this change, the Google Places API started throwing a GooglePlacesError for NOT_FOUND (but it suppresses ZERO_RESULTS). IMO, it should also suppress the new NOT_FOUND error.

Source: https://developers.google.com/places/web-service/details#PlaceDetailsStatusCodes

When parsing JSON response from Google, use parse_float option

We're using Python 2.6.5 and when reviewing lat/lng values within our codebase they're incorrect, from what Google shows when making a direct call:

# python 2.7.5
{
    lat: 36.151442,
    lng: -86.796573
}

versus

# python 2.6.5
{u'lat': 36.151442000000003, u'lng': -86.796572999999995}

We found an option for parsing floats when loading JSON. This might be something worth implementing:

json.loads(x, parse_float = decimal.Decimal)

Next page token for nearby_search fails with lat_lon required.

Hey slimkrazy,

I noticed that nearby_search fails when going to the next page asking for lat_lon. I looked at the code and added on my side that if page_toke is None, then run

lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self.request_params = {'location' : lat_lng_str}

That fixed the issue. But in fact a cleaner way would be to add all the needed parameters when pagetoken is None and when a pagetoken is added, just add the pagetoken and the key to the url.

Hope this helps.

Luis

Radar Search

Is there any way you can add radar search capability in this package

alt_ids in place details

Behavior in the Places API Web Service: If the place has multiple IDs, the Places API Web Service will return the primary ID for the place, and an array containing all the alternative IDs for that place. See the documentation on place details and place search.
This is very useful when you want to look for duplicates basically.

Add status code as property of GooglePlacesError

Currently, if the Google Places API returns a status other than OK or ZERO_RESULTS, the library raises a GooglePlacesError. However, that error simply has the offending status code in the exception message, which makes it hard for consuming code to figure out what happened. status_code should be an attribute of GooglePlacesError.

A text search makes 10 API requests

Hi,

Thanks for setting this up... incredibly helpful! I noticed that a simple .text_search was costing me 10 API requests each time. Is anyone else experiencing this issue?

Sample:
def getCounty(cityState):
API_KEY = 'blahblahabcdefg'
google_places = GooglePlaces(API_KEY)
query_result = google_places.text_search("What county is " + cityState + " in")
for place in query_result.places:
return place.name

Yes, yes, I know I can accomplish the same task with Geocoding! Thanks! :)

Add option to add timeout property to `urlopen` call

When making calls to Google via urlopen:
https://github.com/slimkrazy/python-google-places/blob/master/googleplaces/__init__.py#L68

there's no timeout specified. This means that the call will default to no timeout, or infinite. It would be great to be able to specific a timeout option on a method by method basis, or even a default timeout when instantiating the lib for the first time. Perhaps something like this:

google_places = googleplaces.GooglePlaces(
    settings.GOOGLE_PLACES_API_KEY,
    timeout=2
)

Error while adding a place

Hello, just tried to add place with code from your example and received following error:

Traceback (most recent call last):
File "addgeo.py", line 11, in
language=lang.ENGLISH_GREAT_BRITAIN)
File "\lib\site-packages\googleplaces__init__.py", line 518, in add_place
self.api_key), json.dumps(request_params), use_http_post=True)
File "\lib\site-packages\googleplaces__init__.py", line 72, in fetch_remote_json
request_url, response = fetch_remote(service_url, params, use_http_post)
File "\lib\site-packages\googleplaces__init
.py", line 54, in _fetch_remote
for k, v in params.items():
AttributeError: 'str' object has no attribute 'items'

also tried with different parameters, same situation

Place as dictionary

I am writing a small application in which I want to return the found Places as JSONs. As this is very tedious to do manually, it would be nice to have a dictionary representation of Places (and possibly whole SearchResuts).

If this is an acceptable addition, I would create a pull reques implementing a as_dict() for the classes.

add custom __repr__ to Place and GooglePlacesSearchResult

I just came across this project. Thanks to all of you who've been putting it together. As I start using it, I'll see if there are ways I can help out.

One thing I noticed is that the Place and GooglePlacesSearchResult classes don't override object's repr. I know it's a minor aesthetic thing, but it would be nice to have.

For Place it could look something like <Place name=[obj.name]> (using the name attribute). What do you think?

Sporadic Error

This is similar to issue #44. That issue is closed but I'm still getting a similar error. Sometimes everything runs fine and other times it'll error out.

I'm running:

from googleplaces import GooglePlaces, types, lang

YOUR_API_KEY = 'my_key'

google_places = GooglePlaces(YOUR_API_KEY)

query_result = google_places.nearby_search(
        location='30309', keyword='Wendys',
        types=[types.TYPE_FOOD])

if query_result.has_attributions:
    print query_result.html_attributions

for place in query_result.places:
    print place.name + ":" + str(place.geo_location)

Sometimes I get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-abcc5ffe6e0d> in <module>()
      7 query_result = google_places.nearby_search(
      8         location='30309', keyword='Wendys',
----> 9         types=[types.TYPE_FOOD])
     10 
     11 if query_result.has_attributions:

C:\Python27\ArcGISx6410.3\lib\site-packages\googleplaces\__init__.py in nearby_search(self, language, keyword, location, lat_lng, name, radius, rankby, sensor, types)
    262         radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
    263                   else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
--> 264         lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
    265         self._request_params = {'location': lat_lng_str}
    266         if rankby == 'prominence':

C:\Python27\ArcGISx6410.3\lib\site-packages\googleplaces\__init__.py in _generate_lat_lng_string(self, lat_lng, location)
    547         except:
    548             raise ValueError(
--> 549                 'lat_lng must be a dict with the keys, \'lat\' and \'lng\'')
    550 
    551     @property

ValueError: lat_lng must be a dict with the keys, 'lat' and 'lng'

BUG found in nearby_search with radius parameter

When you complete radius parameter with a value less than 50000, for example, 500, the operator is wrong and you ever use, 50000.

You must change this:
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)

for this:
radius = (radius if radius >= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)

line: 277 in init.py

HTTP connection pooling

Hey.

It would be great if you could abstract away the urllib dependency to allow to choose different transports.
That would allow for example to use requests HTTPConnectionPool which would improve performance a lot i think.

The id and reference fields are deprecated as of June 24, 2014

Quoting the Google Places API, "Note: The id and reference fields are deprecated as of June 24, 2014. They are replaced by the new place ID, a textual identifier that uniquely identifies a place and can be used to retrieve information about the place. The Places API currently returns a place_id in all responses, and accepts a placeid in the Place Details request or place_id in the Place Delete request. Soon after June 24, 2015, the API will stop returning the id and reference fields in responses. Some time later, the API will no longer accept the reference in requests. We recommend that you update your code to use the new place ID instead of id and reference as soon as possible."
At least the line below should be chaned to self._id = place_data['place_id'] before the whole thing break.
https://github.com/slimkrazy/python-google-places/blob/master/googleplaces/__init__.py#L758

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.