0
# Places API
1
2
Search for places, get detailed place information, autocomplete suggestions, and place photos using Google's comprehensive places database with support for text search, nearby search, and autocomplete functionality.
3
4
## Capabilities
5
6
### Place Search
7
8
Find places using text queries with support for location biasing, filtering, and pagination.
9
10
```python { .api }
11
def find_place(client, input, input_type, fields=None, location_bias=None,
12
language=None):
13
"""
14
Find places by text input or phone number.
15
16
Args:
17
client (Client): Google Maps API client instance
18
input (str): Text query or phone number to search for
19
input_type (str): Input type - "textquery" or "phonenumber"
20
fields (list): Place data fields to return (e.g., ["place_id", "name", "geometry"])
21
location_bias (dict): Location biasing with point, circle, or rectangle
22
language (str): Language code for returned results (ISO 639-1)
23
24
Returns:
25
dict: Find place response with candidates list containing place information
26
"""
27
28
def places(client, query=None, location=None, radius=None, language=None,
29
min_price=None, max_price=None, open_now=False, type=None,
30
region=None, page_token=None):
31
"""
32
Text-based place search with location and filtering options.
33
34
Args:
35
client (Client): Google Maps API client instance
36
query (str): Text query (e.g., "restaurants in Sydney")
37
location (tuple): Center point as (lat, lng) for location bias
38
radius (int): Search radius in meters (max 50,000)
39
language (str): Language code for returned results
40
min_price (int): Minimum price level (0-4)
41
max_price (int): Maximum price level (0-4)
42
open_now (bool): Only return places currently open
43
type (str): Place type filter (e.g., "restaurant", "gas_station")
44
region (str): Region code for result biasing
45
page_token (str): Token for next page of results
46
47
Returns:
48
dict: Places search response with results list and next_page_token
49
"""
50
51
def places_nearby(client, location=None, radius=None, keyword=None,
52
language=None, min_price=None, max_price=None, name=None,
53
open_now=False, rank_by=None, type=None, page_token=None):
54
"""
55
Search for places within a specified area.
56
57
Args:
58
client (Client): Google Maps API client instance
59
location (tuple): Center point as (lat, lng) coordinates
60
radius (int): Search radius in meters (max 50,000, required unless rank_by='distance')
61
keyword (str): Keyword to match against place names and types
62
language (str): Language code for returned results
63
min_price (int): Minimum price level (0-4)
64
max_price (int): Maximum price level (0-4)
65
name (str): Name to match against place names
66
open_now (bool): Only return places currently open
67
rank_by (str): Ranking preference - "prominence" or "distance"
68
type (str): Place type filter (e.g., "restaurant", "hospital")
69
page_token (str): Token for next page of results
70
71
Returns:
72
dict: Nearby search response with results list and next_page_token
73
"""
74
```
75
76
### Place Details
77
78
Get comprehensive information about specific places including contact details, reviews, photos, and attributes.
79
80
```python { .api }
81
def place(client, place_id, session_token=None, fields=None, language=None,
82
reviews_no_translations=False, reviews_sort="most_relevant"):
83
"""
84
Get detailed information about a specific place.
85
86
Args:
87
client (Client): Google Maps API client instance
88
place_id (str): Unique place identifier
89
session_token (str): Session token for billing optimization
90
fields (list): Place data fields to return (controls billing)
91
language (str): Language code for returned results
92
reviews_no_translations (bool): Disable review translations
93
reviews_sort (str): Review sorting - "most_relevant" or "newest"
94
95
Returns:
96
dict: Place details response with comprehensive place information
97
"""
98
99
def places_photo(client, photo_reference, max_width=None, max_height=None):
100
"""
101
Get place photo by reference.
102
103
Args:
104
client (Client): Google Maps API client instance
105
photo_reference (str): Photo reference from place details
106
max_width (int): Maximum photo width in pixels (1-1600)
107
max_height (int): Maximum photo height in pixels (1-1600)
108
109
Returns:
110
requests.Response: HTTP response containing photo image data
111
"""
112
```
113
114
### Place Autocomplete
115
116
Get place predictions and suggestions as users type for enhanced user experience in location input.
117
118
```python { .api }
119
def places_autocomplete(client, input_text, session_token=None, offset=None,
120
origin=None, location=None, radius=None, language=None,
121
types=None, components=None, strict_bounds=False):
122
"""
123
Get place predictions for user input.
124
125
Args:
126
client (Client): Google Maps API client instance
127
input_text (str): User input text to get predictions for
128
session_token (str): Session token for billing optimization
129
offset (int): Character position in input_text where autocomplete kicks in
130
origin (tuple): Origin point as (lat, lng) for distance calculations
131
location (tuple): Center point as (lat, lng) for location bias
132
radius (int): Distance in meters for location bias
133
language (str): Language code for returned results
134
types (list): Place type restrictions (e.g., ["establishment"], ["geocode"])
135
components (dict): Component filters (e.g., {"country": ["us", "ca"]})
136
strict_bounds (bool): Restrict results to location bounds
137
138
Returns:
139
dict: Autocomplete response with predictions list containing
140
place suggestions and session tokens
141
"""
142
143
def places_autocomplete_query(client, input_text, offset=None, location=None,
144
radius=None, language=None):
145
"""
146
Get place predictions for search queries.
147
148
Args:
149
client (Client): Google Maps API client instance
150
input_text (str): Search query text
151
offset (int): Character position where autocomplete applies
152
location (tuple): Center point as (lat, lng) for location bias
153
radius (int): Distance in meters for location bias
154
language (str): Language code for returned results
155
156
Returns:
157
dict: Query autocomplete response with predictions for search queries
158
"""
159
```
160
161
## Field Constants
162
163
Pre-defined field sets for controlling returned data and billing costs:
164
165
```python { .api }
166
# Find Place field sets
167
PLACES_FIND_FIELDS_BASIC = [
168
"place_id", "name", "formatted_address", "geometry"
169
]
170
171
PLACES_FIND_FIELDS_CONTACT = [
172
"formatted_phone_number", "international_phone_number", "website"
173
]
174
175
PLACES_FIND_FIELDS_ATMOSPHERE = [
176
"price_level", "rating", "user_ratings_total"
177
]
178
179
PLACES_FIND_FIELDS = PLACES_FIND_FIELDS_BASIC + PLACES_FIND_FIELDS_CONTACT + PLACES_FIND_FIELDS_ATMOSPHERE
180
181
# Place Details field sets
182
PLACES_DETAIL_FIELDS_BASIC = [
183
"place_id", "name", "formatted_address", "geometry", "types"
184
]
185
186
PLACES_DETAIL_FIELDS_CONTACT = [
187
"formatted_phone_number", "international_phone_number", "website", "url"
188
]
189
190
PLACES_DETAIL_FIELDS_ATMOSPHERE = [
191
"price_level", "rating", "user_ratings_total", "reviews", "photos"
192
]
193
194
PLACES_DETAIL_FIELDS = PLACES_DETAIL_FIELDS_BASIC + PLACES_DETAIL_FIELDS_CONTACT + PLACES_DETAIL_FIELDS_ATMOSPHERE
195
```
196
197
## Usage Examples
198
199
### Text-Based Place Search
200
201
```python
202
import googlemaps
203
204
gmaps = googlemaps.Client(key='YOUR_API_KEY')
205
206
# Search for restaurants in a city
207
places_result = gmaps.places(
208
query="restaurants in Sydney, Australia",
209
type="restaurant",
210
language="en"
211
)
212
213
# Process search results
214
for place in places_result['results']:
215
name = place['name']
216
address = place['formatted_address']
217
rating = place.get('rating', 'No rating')
218
print(f"{name} - {address} (Rating: {rating})")
219
220
# Get next page of results if available
221
if 'next_page_token' in places_result:
222
# Wait a few seconds before using token
223
import time
224
time.sleep(2)
225
226
next_results = gmaps.places(
227
query="restaurants in Sydney, Australia",
228
page_token=places_result['next_page_token']
229
)
230
```
231
232
### Nearby Places Search
233
234
```python
235
import googlemaps
236
237
gmaps = googlemaps.Client(key='YOUR_API_KEY')
238
239
# Find gas stations near a location
240
sydney_coords = (-33.8688, 151.2093)
241
242
nearby_result = gmaps.places_nearby(
243
location=sydney_coords,
244
radius=2000, # 2km radius
245
type="gas_station",
246
open_now=True
247
)
248
249
# Sort by rating
250
sorted_places = sorted(
251
nearby_result['results'],
252
key=lambda x: x.get('rating', 0),
253
reverse=True
254
)
255
256
for place in sorted_places[:5]: # Top 5
257
name = place['name']
258
rating = place.get('rating', 'No rating')
259
vicinity = place['vicinity']
260
print(f"{name} - {vicinity} (Rating: {rating})")
261
```
262
263
### Find Place by Phone or Text
264
265
```python
266
import googlemaps
267
268
gmaps = googlemaps.Client(key='YOUR_API_KEY')
269
270
# Find place by phone number
271
phone_result = gmaps.find_place(
272
input="+12345678900",
273
input_type="phonenumber",
274
fields=["place_id", "name", "formatted_address", "geometry"]
275
)
276
277
if phone_result['candidates']:
278
place = phone_result['candidates'][0]
279
print(f"Found: {place['name']} at {place['formatted_address']}")
280
281
# Find place by text query
282
text_result = gmaps.find_place(
283
input="Eiffel Tower",
284
input_type="textquery",
285
fields=["place_id", "name", "geometry", "photos"],
286
location_bias={
287
"circle": {
288
"center": {"lat": 48.8566, "lng": 2.3522}, # Paris center
289
"radius": 10000 # 10km radius
290
}
291
}
292
)
293
```
294
295
### Detailed Place Information
296
297
```python
298
import googlemaps
299
300
gmaps = googlemaps.Client(key='YOUR_API_KEY')
301
302
# Get comprehensive place details
303
place_id = "ChIJN1t_tDeuEmsRUsoyG83frY4" # Google Sydney office
304
305
place_details = gmaps.place(
306
place_id=place_id,
307
fields=[
308
"name", "formatted_address", "formatted_phone_number",
309
"website", "rating", "user_ratings_total", "reviews",
310
"photos", "opening_hours", "price_level"
311
],
312
language="en"
313
)
314
315
# Extract detailed information
316
result = place_details['result']
317
print(f"Name: {result['name']}")
318
print(f"Address: {result['formatted_address']}")
319
print(f"Phone: {result.get('formatted_phone_number', 'N/A')}")
320
print(f"Website: {result.get('website', 'N/A')}")
321
print(f"Rating: {result.get('rating', 'N/A')} ({result.get('user_ratings_total', 0)} reviews)")
322
323
# Get opening hours
324
if 'opening_hours' in result:
325
hours = result['opening_hours']
326
print("Hours:")
327
for period in hours['weekday_text']:
328
print(f" {period}")
329
330
# Get recent reviews
331
if 'reviews' in result:
332
print("\nRecent reviews:")
333
for review in result['reviews'][:3]: # First 3 reviews
334
rating = review['rating']
335
text = review['text'][:100] + "..." if len(review['text']) > 100 else review['text']
336
print(f" {rating}/5: {text}")
337
```
338
339
### Place Photos
340
341
```python
342
import googlemaps
343
344
gmaps = googlemaps.Client(key='YOUR_API_KEY')
345
346
# Get place with photos
347
place_id = "ChIJN1t_tDeuEmsRUsoyG83frY4"
348
place_result = gmaps.place(
349
place_id=place_id,
350
fields=["photos"]
351
)
352
353
# Download place photos
354
if 'photos' in place_result['result']:
355
for i, photo in enumerate(place_result['result']['photos'][:3]): # First 3 photos
356
photo_reference = photo['photo_reference']
357
358
# Get photo response
359
photo_response = gmaps.places_photo(
360
photo_reference=photo_reference,
361
max_width=800,
362
max_height=600
363
)
364
365
# Save photo to file
366
with open(f'place_photo_{i}.jpg', 'wb') as f:
367
for chunk in photo_response.iter_content(chunk_size=1024):
368
f.write(chunk)
369
370
print(f"Downloaded photo {i+1}")
371
```
372
373
### Place Autocomplete
374
375
```python
376
import googlemaps
377
378
gmaps = googlemaps.Client(key='YOUR_API_KEY')
379
380
# Generate session token for billing optimization
381
import uuid
382
session_token = str(uuid.uuid4())
383
384
# Get autocomplete suggestions
385
autocomplete_result = gmaps.places_autocomplete(
386
input_text="Starbucks near",
387
session_token=session_token,
388
types=["establishment"],
389
location=(37.7749, -122.4194), # San Francisco
390
radius=10000, # 10km
391
language="en"
392
)
393
394
# Display suggestions
395
print("Autocomplete suggestions:")
396
for prediction in autocomplete_result['predictions']:
397
description = prediction['description']
398
place_id = prediction['place_id']
399
print(f" {description} (ID: {place_id})")
400
401
# Use the same session token when getting place details
402
# to optimize billing
403
if autocomplete_result['predictions']:
404
selected_place_id = autocomplete_result['predictions'][0]['place_id']
405
406
place_details = gmaps.place(
407
place_id=selected_place_id,
408
session_token=session_token, # Same session token
409
fields=["name", "formatted_address", "rating"]
410
)
411
```
412
413
### Query Autocomplete
414
415
```python
416
import googlemaps
417
418
gmaps = googlemaps.Client(key='YOUR_API_KEY')
419
420
# Get query suggestions (not tied to specific places)
421
query_autocomplete = gmaps.places_autocomplete_query(
422
input_text="pizza deliver",
423
location=(40.7128, -74.0060), # New York City
424
radius=50000, # 50km
425
language="en"
426
)
427
428
print("Query suggestions:")
429
for prediction in query_autocomplete['predictions']:
430
description = prediction['description']
431
print(f" {description}")
432
```
433
434
### Advanced Place Filtering
435
436
```python
437
import googlemaps
438
439
gmaps = googlemaps.Client(key='YOUR_API_KEY')
440
441
# Search with multiple filters
442
filtered_search = gmaps.places_nearby(
443
location=(34.0522, -118.2437), # Los Angeles
444
radius=5000,
445
type="restaurant",
446
min_price=2, # Moderate pricing
447
max_price=4, # Expensive pricing
448
open_now=True, # Currently open
449
keyword="italian" # Italian cuisine
450
)
451
452
# Filter results by rating
453
high_rated = [
454
place for place in filtered_search['results']
455
if place.get('rating', 0) >= 4.0
456
]
457
458
print(f"Found {len(high_rated)} highly-rated Italian restaurants:")
459
for place in high_rated:
460
name = place['name']
461
rating = place.get('rating', 'N/A')
462
price_level = place.get('price_level', 'N/A')
463
print(f" {name} - Rating: {rating}/5, Price: {'$' * price_level if isinstance(price_level, int) else price_level}")
464
```