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

elevation-geography.mddocs/

Elevation and Geography

Retrieve elevation data for specific locations or along paths, and access timezone information for any location worldwide with support for various coordinate formats and sampling options.

Capabilities

Elevation Data

Get elevation information for specific coordinates or sample elevation along a path.

def elevation(client, locations):
    """
    Get elevation data for specific locations.
    
    Args:
        client (Client): Google Maps API client instance
        locations (list): List of coordinate points as (lat, lng) tuples,
                         coordinate dicts, or encoded polyline string
    
    Returns:
        list: List of elevation result dictionaries containing:
              - elevation: Height above sea level in meters
              - location: Lat/lng coordinates
              - resolution: Accuracy of elevation data in meters
    
    Raises:
        googlemaps.exceptions.ApiError: When API returns an error
        googlemaps.exceptions.TransportError: When HTTP request fails
        googlemaps.exceptions.Timeout: When request times out
    """

def elevation_along_path(client, path, samples):
    """
    Get elevation data along a path with specified sampling.
    
    Args:
        client (Client): Google Maps API client instance
        path (list): Path as list of (lat, lng) tuples, coordinate dicts,
                    or encoded polyline string
        samples (int): Number of sample points along path (max 512)
    
    Returns:
        list: List of elevation result dictionaries with elevation data
              sampled along the path at equal intervals
    
    Raises:
        googlemaps.exceptions.ApiError: When API returns an error
        googlemaps.exceptions.TransportError: When HTTP request fails
        googlemaps.exceptions.Timeout: When request times out
    """

Timezone Information

Get timezone data for any location including offset information and timezone identifiers.

def timezone(client, location, timestamp=None, language=None):
    """
    Get timezone information for a location.
    
    Args:
        client (Client): Google Maps API client instance
        location (tuple): Coordinates as (lat, lng) tuple or coordinate dict
        timestamp (datetime): Timestamp for timezone calculation (default: current time)
        language (str): Language code for timezone names (ISO 639-1)
    
    Returns:
        dict: Timezone information containing:
              - timeZoneId: IANA timezone identifier (e.g., "America/New_York")
              - timeZoneName: Human-readable timezone name
              - dstOffset: Daylight saving offset in seconds
              - rawOffset: Base timezone offset from UTC in seconds
              - status: Request status
    
    Raises:
        googlemaps.exceptions.ApiError: When API returns an error
        googlemaps.exceptions.TransportError: When HTTP request fails
        googlemaps.exceptions.Timeout: When request times out
    """

Usage Examples

Basic Elevation Lookup

import googlemaps

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

# Get elevation for specific coordinates
locations = [
    (40.714728, -73.998672),  # NYC coordinates
    (34.052235, -118.243683), # LA coordinates
    (41.878113, -87.629799)   # Chicago coordinates
]

elevation_result = gmaps.elevation(locations)

# Display elevation data
for result in elevation_result:
    lat = result['location']['lat']
    lng = result['location']['lng']
    elevation = result['elevation']
    resolution = result['resolution']
    
    print(f"Location: ({lat:.6f}, {lng:.6f})")
    print(f"Elevation: {elevation:.2f} meters")
    print(f"Resolution: {resolution:.2f} meters")
    print("---")

Elevation Along a Route

import googlemaps

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

# Define a path (e.g., hiking trail coordinates)
trail_path = [
    (36.579, -118.292),   # Start point
    (36.582, -118.295),   # Point 2
    (36.585, -118.298),   # Point 3
    (36.588, -118.301),   # End point
]

# Sample elevation along the path
elevation_profile = gmaps.elevation_along_path(
    path=trail_path,
    samples=20  # Get 20 elevation points along the path
)

# Create elevation profile
print("Elevation Profile:")
for i, point in enumerate(elevation_profile):
    elevation = point['elevation']
    print(f"Point {i+1}: {elevation:.1f}m")

# Calculate elevation gain/loss
elevations = [point['elevation'] for point in elevation_profile]
total_gain = sum(max(0, elevations[i] - elevations[i-1]) for i in range(1, len(elevations)))
total_loss = sum(max(0, elevations[i-1] - elevations[i]) for i in range(1, len(elevations)))

print(f"\nTotal elevation gain: {total_gain:.1f}m")
print(f"Total elevation loss: {total_loss:.1f}m")

Using Encoded Polylines for Elevation

import googlemaps

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

# Use an encoded polyline (from directions API)
directions_result = gmaps.directions(
    origin="Denver, CO",
    destination="Boulder, CO"
)

# Extract polyline from route
polyline = directions_result[0]['overview_polyline']['points']

# Get elevation along the route
route_elevation = gmaps.elevation_along_path(
    path=polyline,
    samples=50  # Sample 50 points along route
)

# Find highest and lowest points
elevations = [point['elevation'] for point in route_elevation]
max_elevation = max(elevations)
min_elevation = min(elevations)

print(f"Route elevation range: {min_elevation:.0f}m - {max_elevation:.0f}m")
print(f"Elevation difference: {max_elevation - min_elevation:.0f}m")

Basic Timezone Lookup

import googlemaps
from datetime import datetime

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

# Get timezone for coordinates
location = (37.7749, -122.4194)  # San Francisco

timezone_result = gmaps.timezone(location)

print(f"Timezone ID: {timezone_result['timeZoneId']}")
print(f"Timezone Name: {timezone_result['timeZoneName']}")
print(f"UTC Offset: {timezone_result['rawOffset'] / 3600:.1f} hours")
print(f"DST Offset: {timezone_result['dstOffset'] / 3600:.1f} hours")

# Calculate local time
utc_offset = (timezone_result['rawOffset'] + timezone_result['dstOffset']) / 3600
print(f"Total offset from UTC: {utc_offset:.1f} hours")

Timezone with Specific Timestamp

import googlemaps
from datetime import datetime, timezone

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

# Check timezone for a specific date (useful for historical data)
location = (40.7128, -74.0060)  # New York City
specific_date = datetime(2024, 7, 15, 12, 0, 0)  # July 15, 2024 (summer)

summer_timezone = gmaps.timezone(
    location=location,
    timestamp=specific_date
)

print("Summer timezone info:")
print(f"  Timezone: {summer_timezone['timeZoneName']}")
print(f"  DST Offset: {summer_timezone['dstOffset'] / 3600:.1f} hours")

# Check same location in winter
winter_date = datetime(2024, 1, 15, 12, 0, 0)  # January 15, 2024 (winter)

winter_timezone = gmaps.timezone(
    location=location, 
    timestamp=winter_date
)

print("\nWinter timezone info:")
print(f"  Timezone: {winter_timezone['timeZoneName']}")
print(f"  DST Offset: {winter_timezone['dstOffset'] / 3600:.1f} hours")

Multiple Location Timezone Lookup

import googlemaps
from datetime import datetime

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

# Major cities around the world
cities = [
    ("New York", (40.7128, -74.0060)),
    ("London", (51.5074, -0.1278)),
    ("Tokyo", (35.6762, 139.6503)),
    ("Sydney", (-33.8688, 151.2093)),
    ("Dubai", (25.2048, 55.2708))
]

current_time = datetime.now()

print("Current timezone information:")
print("=" * 50)

for city_name, coordinates in cities:
    tz_info = gmaps.timezone(
        location=coordinates,
        timestamp=current_time,
        language="en"
    )
    
    # Calculate local offset
    total_offset = (tz_info['rawOffset'] + tz_info['dstOffset']) / 3600
    
    print(f"{city_name}:")
    print(f"  Timezone: {tz_info['timeZoneName']}")
    print(f"  UTC Offset: {total_offset:+.1f} hours")
    print(f"  IANA ID: {tz_info['timeZoneId']}")
    print()

Combined Elevation and Geography Analysis

import googlemaps
from datetime import datetime

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

def analyze_location(name, coordinates):
    """Analyze both elevation and timezone for a location."""
    print(f"Analysis for {name}:")
    print("=" * 30)
    
    # Get elevation
    elevation_result = gmaps.elevation([coordinates])
    elevation_data = elevation_result[0]
    
    print(f"Coordinates: {coordinates}")
    print(f"Elevation: {elevation_data['elevation']:.1f} meters above sea level")
    print(f"Elevation resolution: {elevation_data['resolution']:.1f} meters")
    
    # Get timezone
    timezone_result = gmaps.timezone(
        location=coordinates,
        timestamp=datetime.now()
    )
    
    total_offset = (timezone_result['rawOffset'] + timezone_result['dstOffset']) / 3600
    print(f"Timezone: {timezone_result['timeZoneName']}")
    print(f"UTC Offset: {total_offset:+.1f} hours")
    print()

# Analyze multiple interesting locations
locations = [
    ("Mount Everest Base Camp", (28.0018, 86.8528)),
    ("Death Valley (lowest point in North America)", (36.2548, -116.8275)),
    ("Denver (Mile High City)", (39.7392, -104.9903)),
    ("Amsterdam (below sea level)", (52.3676, 4.9041))
]

for name, coords in locations:
    analyze_location(name, coords)

Elevation Profile Visualization Data

import googlemaps

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

def get_route_elevation_profile(origin, destination, samples=100):
    """Get elevation profile for a route."""
    
    # Get route directions first
    directions = gmaps.directions(origin, destination)
    route_polyline = directions[0]['overview_polyline']['points']
    
    # Get elevation along route
    elevation_data = gmaps.elevation_along_path(
        path=route_polyline,
        samples=samples
    )
    
    # Extract data for visualization
    distances = []
    elevations = []
    
    # Calculate approximate distances (simplified)
    total_distance = directions[0]['legs'][0]['distance']['value']  # meters
    
    for i, point in enumerate(elevation_data):
        distance = (i / (len(elevation_data) - 1)) * total_distance / 1000  # km
        distances.append(distance)
        elevations.append(point['elevation'])
    
    return {
        'distances_km': distances,
        'elevations_m': elevations,
        'route_info': {
            'origin': directions[0]['legs'][0]['start_address'],
            'destination': directions[0]['legs'][0]['end_address'],
            'total_distance_km': total_distance / 1000,
            'total_duration': directions[0]['legs'][0]['duration']['text']
        }
    }

# Example: Get elevation profile for a mountain route
profile = get_route_elevation_profile(
    "Boulder, CO",
    "Rocky Mountain National Park, CO"
)

print(f"Route: {profile['route_info']['origin']} to {profile['route_info']['destination']}")
print(f"Distance: {profile['route_info']['total_distance_km']:.1f} km")
print(f"Duration: {profile['route_info']['total_duration']}")
print("\nElevation profile (first 10 points):")

for i in range(min(10, len(profile['distances_km']))):
    dist = profile['distances_km'][i]
    elev = profile['elevations_m'][i]
    print(f"  {dist:.1f} km: {elev:.0f} m")

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