CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-googlemaps

Python client library for Google Maps Platform providing access to mapping services, geocoding, routing, and location APIs

Pending
Overview
Eval results
Files

places.mddocs/

Places API

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.

Capabilities

Place Search

Find places using text queries with support for location biasing, filtering, and pagination.

def find_place(client, input, input_type, fields=None, location_bias=None,
               language=None):
    """
    Find places by text input or phone number.
    
    Args:
        client (Client): Google Maps API client instance
        input (str): Text query or phone number to search for
        input_type (str): Input type - "textquery" or "phonenumber"
        fields (list): Place data fields to return (e.g., ["place_id", "name", "geometry"])
        location_bias (dict): Location biasing with point, circle, or rectangle
        language (str): Language code for returned results (ISO 639-1)
    
    Returns:
        dict: Find place response with candidates list containing place information
    """

def places(client, query=None, location=None, radius=None, language=None,
          min_price=None, max_price=None, open_now=False, type=None,
          region=None, page_token=None):
    """
    Text-based place search with location and filtering options.
    
    Args:
        client (Client): Google Maps API client instance
        query (str): Text query (e.g., "restaurants in Sydney")
        location (tuple): Center point as (lat, lng) for location bias
        radius (int): Search radius in meters (max 50,000)
        language (str): Language code for returned results
        min_price (int): Minimum price level (0-4)
        max_price (int): Maximum price level (0-4)
        open_now (bool): Only return places currently open
        type (str): Place type filter (e.g., "restaurant", "gas_station")
        region (str): Region code for result biasing
        page_token (str): Token for next page of results
    
    Returns:
        dict: Places search response with results list and next_page_token
    """

def places_nearby(client, location=None, radius=None, keyword=None,
                 language=None, min_price=None, max_price=None, name=None,
                 open_now=False, rank_by=None, type=None, page_token=None):
    """
    Search for places within a specified area.
    
    Args:
        client (Client): Google Maps API client instance
        location (tuple): Center point as (lat, lng) coordinates
        radius (int): Search radius in meters (max 50,000, required unless rank_by='distance')
        keyword (str): Keyword to match against place names and types
        language (str): Language code for returned results
        min_price (int): Minimum price level (0-4)
        max_price (int): Maximum price level (0-4)
        name (str): Name to match against place names
        open_now (bool): Only return places currently open
        rank_by (str): Ranking preference - "prominence" or "distance"
        type (str): Place type filter (e.g., "restaurant", "hospital")
        page_token (str): Token for next page of results
    
    Returns:
        dict: Nearby search response with results list and next_page_token
    """

Place Details

Get comprehensive information about specific places including contact details, reviews, photos, and attributes.

def place(client, place_id, session_token=None, fields=None, language=None,
         reviews_no_translations=False, reviews_sort="most_relevant"):
    """
    Get detailed information about a specific place.
    
    Args:
        client (Client): Google Maps API client instance
        place_id (str): Unique place identifier
        session_token (str): Session token for billing optimization
        fields (list): Place data fields to return (controls billing)
        language (str): Language code for returned results
        reviews_no_translations (bool): Disable review translations
        reviews_sort (str): Review sorting - "most_relevant" or "newest"
    
    Returns:
        dict: Place details response with comprehensive place information
    """

def places_photo(client, photo_reference, max_width=None, max_height=None):
    """
    Get place photo by reference.
    
    Args:
        client (Client): Google Maps API client instance
        photo_reference (str): Photo reference from place details
        max_width (int): Maximum photo width in pixels (1-1600)
        max_height (int): Maximum photo height in pixels (1-1600)
    
    Returns:
        requests.Response: HTTP response containing photo image data
    """

Place Autocomplete

Get place predictions and suggestions as users type for enhanced user experience in location input.

def places_autocomplete(client, input_text, session_token=None, offset=None,
                       origin=None, location=None, radius=None, language=None,
                       types=None, components=None, strict_bounds=False):
    """
    Get place predictions for user input.
    
    Args:
        client (Client): Google Maps API client instance
        input_text (str): User input text to get predictions for
        session_token (str): Session token for billing optimization
        offset (int): Character position in input_text where autocomplete kicks in
        origin (tuple): Origin point as (lat, lng) for distance calculations
        location (tuple): Center point as (lat, lng) for location bias
        radius (int): Distance in meters for location bias
        language (str): Language code for returned results
        types (list): Place type restrictions (e.g., ["establishment"], ["geocode"])
        components (dict): Component filters (e.g., {"country": ["us", "ca"]})
        strict_bounds (bool): Restrict results to location bounds
    
    Returns:
        dict: Autocomplete response with predictions list containing
              place suggestions and session tokens
    """

def places_autocomplete_query(client, input_text, offset=None, location=None,
                             radius=None, language=None):
    """
    Get place predictions for search queries.
    
    Args:
        client (Client): Google Maps API client instance
        input_text (str): Search query text
        offset (int): Character position where autocomplete applies
        location (tuple): Center point as (lat, lng) for location bias
        radius (int): Distance in meters for location bias
        language (str): Language code for returned results
    
    Returns:
        dict: Query autocomplete response with predictions for search queries
    """

Field Constants

Pre-defined field sets for controlling returned data and billing costs:

# Find Place field sets
PLACES_FIND_FIELDS_BASIC = [
    "place_id", "name", "formatted_address", "geometry"
]

PLACES_FIND_FIELDS_CONTACT = [
    "formatted_phone_number", "international_phone_number", "website"
]

PLACES_FIND_FIELDS_ATMOSPHERE = [
    "price_level", "rating", "user_ratings_total"
]

PLACES_FIND_FIELDS = PLACES_FIND_FIELDS_BASIC + PLACES_FIND_FIELDS_CONTACT + PLACES_FIND_FIELDS_ATMOSPHERE

# Place Details field sets
PLACES_DETAIL_FIELDS_BASIC = [
    "place_id", "name", "formatted_address", "geometry", "types"
]

PLACES_DETAIL_FIELDS_CONTACT = [
    "formatted_phone_number", "international_phone_number", "website", "url"
]

PLACES_DETAIL_FIELDS_ATMOSPHERE = [
    "price_level", "rating", "user_ratings_total", "reviews", "photos"
]

PLACES_DETAIL_FIELDS = PLACES_DETAIL_FIELDS_BASIC + PLACES_DETAIL_FIELDS_CONTACT + PLACES_DETAIL_FIELDS_ATMOSPHERE

Usage Examples

Text-Based Place Search

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Search for restaurants in a city
places_result = gmaps.places(
    query="restaurants in Sydney, Australia",
    type="restaurant",
    language="en"
)

# Process search results
for place in places_result['results']:
    name = place['name']
    address = place['formatted_address']
    rating = place.get('rating', 'No rating')
    print(f"{name} - {address} (Rating: {rating})")

# Get next page of results if available
if 'next_page_token' in places_result:
    # Wait a few seconds before using token
    import time
    time.sleep(2)
    
    next_results = gmaps.places(
        query="restaurants in Sydney, Australia",
        page_token=places_result['next_page_token']
    )

Nearby Places Search

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Find gas stations near a location
sydney_coords = (-33.8688, 151.2093)

nearby_result = gmaps.places_nearby(
    location=sydney_coords,
    radius=2000,  # 2km radius
    type="gas_station",
    open_now=True
)

# Sort by rating
sorted_places = sorted(
    nearby_result['results'],
    key=lambda x: x.get('rating', 0),
    reverse=True
)

for place in sorted_places[:5]:  # Top 5
    name = place['name']
    rating = place.get('rating', 'No rating')
    vicinity = place['vicinity']
    print(f"{name} - {vicinity} (Rating: {rating})")

Find Place by Phone or Text

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Find place by phone number
phone_result = gmaps.find_place(
    input="+12345678900",
    input_type="phonenumber",
    fields=["place_id", "name", "formatted_address", "geometry"]
)

if phone_result['candidates']:
    place = phone_result['candidates'][0]
    print(f"Found: {place['name']} at {place['formatted_address']}")

# Find place by text query
text_result = gmaps.find_place(
    input="Eiffel Tower",
    input_type="textquery",
    fields=["place_id", "name", "geometry", "photos"],
    location_bias={
        "circle": {
            "center": {"lat": 48.8566, "lng": 2.3522},  # Paris center
            "radius": 10000  # 10km radius
        }
    }
)

Detailed Place Information

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get comprehensive place details
place_id = "ChIJN1t_tDeuEmsRUsoyG83frY4"  # Google Sydney office

place_details = gmaps.place(
    place_id=place_id,
    fields=[
        "name", "formatted_address", "formatted_phone_number",
        "website", "rating", "user_ratings_total", "reviews",
        "photos", "opening_hours", "price_level"
    ],
    language="en"
)

# Extract detailed information
result = place_details['result']
print(f"Name: {result['name']}")
print(f"Address: {result['formatted_address']}")
print(f"Phone: {result.get('formatted_phone_number', 'N/A')}")
print(f"Website: {result.get('website', 'N/A')}")
print(f"Rating: {result.get('rating', 'N/A')} ({result.get('user_ratings_total', 0)} reviews)")

# Get opening hours
if 'opening_hours' in result:
    hours = result['opening_hours']
    print("Hours:")
    for period in hours['weekday_text']:
        print(f"  {period}")

# Get recent reviews
if 'reviews' in result:
    print("\nRecent reviews:")
    for review in result['reviews'][:3]:  # First 3 reviews
        rating = review['rating']
        text = review['text'][:100] + "..." if len(review['text']) > 100 else review['text']
        print(f"  {rating}/5: {text}")

Place Photos

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get place with photos
place_id = "ChIJN1t_tDeuEmsRUsoyG83frY4"
place_result = gmaps.place(
    place_id=place_id,
    fields=["photos"]
)

# Download place photos
if 'photos' in place_result['result']:
    for i, photo in enumerate(place_result['result']['photos'][:3]):  # First 3 photos
        photo_reference = photo['photo_reference']
        
        # Get photo response
        photo_response = gmaps.places_photo(
            photo_reference=photo_reference,
            max_width=800,
            max_height=600
        )
        
        # Save photo to file
        with open(f'place_photo_{i}.jpg', 'wb') as f:
            for chunk in photo_response.iter_content(chunk_size=1024):
                f.write(chunk)
        
        print(f"Downloaded photo {i+1}")

Place Autocomplete

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Generate session token for billing optimization
import uuid
session_token = str(uuid.uuid4())

# Get autocomplete suggestions
autocomplete_result = gmaps.places_autocomplete(
    input_text="Starbucks near",
    session_token=session_token,
    types=["establishment"],
    location=(37.7749, -122.4194),  # San Francisco
    radius=10000,  # 10km
    language="en"
)

# Display suggestions
print("Autocomplete suggestions:")
for prediction in autocomplete_result['predictions']:
    description = prediction['description']
    place_id = prediction['place_id']
    print(f"  {description} (ID: {place_id})")

# Use the same session token when getting place details
# to optimize billing
if autocomplete_result['predictions']:
    selected_place_id = autocomplete_result['predictions'][0]['place_id']
    
    place_details = gmaps.place(
        place_id=selected_place_id,
        session_token=session_token,  # Same session token
        fields=["name", "formatted_address", "rating"]
    )

Query Autocomplete

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get query suggestions (not tied to specific places)
query_autocomplete = gmaps.places_autocomplete_query(
    input_text="pizza deliver",
    location=(40.7128, -74.0060),  # New York City
    radius=50000,  # 50km
    language="en"
)

print("Query suggestions:")
for prediction in query_autocomplete['predictions']:
    description = prediction['description']
    print(f"  {description}")

Advanced Place Filtering

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Search with multiple filters
filtered_search = gmaps.places_nearby(
    location=(34.0522, -118.2437),  # Los Angeles
    radius=5000,
    type="restaurant",
    min_price=2,      # Moderate pricing
    max_price=4,      # Expensive pricing
    open_now=True,    # Currently open
    keyword="italian" # Italian cuisine
)

# Filter results by rating
high_rated = [
    place for place in filtered_search['results']
    if place.get('rating', 0) >= 4.0
]

print(f"Found {len(high_rated)} highly-rated Italian restaurants:")
for place in high_rated:
    name = place['name']
    rating = place.get('rating', 'N/A')
    price_level = place.get('price_level', 'N/A')
    print(f"  {name} - Rating: {rating}/5, Price: {'$' * price_level if isinstance(price_level, int) else price_level}")

Install with Tessl CLI

npx tessl i tessl/pypi-googlemaps

docs

address-validation.md

client-config.md

elevation-geography.md

geocoding.md

geolocation-maps.md

index.md

places.md

roads.md

routing.md

tile.json