Skip to content

Chandangowdatk/Google-Maps-Platform

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

29 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Google Maps Platform - An unofficial Python Library

Python Version License: MIT PyPI version

An unofficial Python client library for Google Maps Platform APIs, providing comprehensive support for Google Places API (New) and Google Environment API (Weather) with field mask management and developer-friendly features.

🌟 What is Google Maps Platform?

Google Maps Platform provides powerful APIs for location-based services, weather data, and more. This library supports:

🏒 Google Places API

A powerful web service that provides detailed information about millions of places around the world:

  • Place Discovery: Find places using text queries or location-based searches
  • Detailed Information: Access comprehensive data including ratings, reviews, photos, contact details, and business hours
  • Real-time Data: Get current information about place status, opening hours, and availability
  • Rich Content: Access user reviews, photos, editorial summaries, and business information
  • Global Coverage: Search places worldwide with localized results

The API is widely used in:

  • Travel Applications: Hotel booking, restaurant discovery, attraction guides
  • Mapping Services: Location-based features and place markers
  • Local Business Directories: Business listings and contact information
  • Mobile Apps: Location-aware applications and navigation
  • E-commerce: Store locators and local business integration

🌀️ Google Environment API (Weather)

Comprehensive weather information for locations worldwide:

  • Current Conditions: Real-time weather data including temperature, precipitation, wind, and cloud cover
  • Daily Forecast: Up to 10 days of weather forecast data
  • Hourly Forecast: Up to 240 hours of weather forecast data
  • Historical Data: Up to 24 hours of historical weather data
  • Global Coverage: Weather data for locations worldwide

The Weather API is used in:

  • Weather Applications: Current conditions, forecasts, and historical data
  • Travel Planning: Weather-aware trip planning and recommendations
  • Agriculture: Weather monitoring and crop management
  • Sports & Recreation: Weather-dependent activity planning
  • Business Intelligence: Weather impact analysis and reporting

πŸ“š About This Unofficial Client Library

This library provides independent modular components for Google Maps Platform APIs with enhanced functionality and developer-friendly features:

πŸš€ Independent Modules

🏒 Places API Modules

  • TextSearch - Search places using natural language queries with pagination support
  • NearbySearch - Find places within a specific radius of a location
  • PlaceDetails - Get comprehensive information about specific places
  • PlacePhoto - Retrieve high-quality photos from the Places database
  • Geocoding - Convert addresses to coordinates and vice versa

🌍 Environment API Modules

🌀️ Weather API
  • weather.Weather - Main weather API client with all endpoints
  • weather.CurrentConditions - Current weather conditions
  • weather.DailyForecast - Daily weather forecast (up to 10 days)
  • weather.HourlyForecast - Hourly weather forecast (up to 240 hours)
  • weather.HourlyHistory - Historical weather data (up to 24 hours)
🌬️ Air Quality API
  • air_quality.AirQuality - Main air quality API client
  • air_quality.CurrentConditions - Current air quality conditions
  • Air Quality Index - AQI data and health recommendations
  • Pollutant Data - Detailed pollutant levels and analysis
🌸 Pollen API
  • pollen.Pollen - Main pollen API client
  • pollen.CurrentConditions - Current pollen conditions
  • Pollen Types - Tree, grass, and weed pollen data
  • Allergy Information - Health recommendations and sensitive groups
β˜€οΈ Solar API
  • solar.Solar - Main solar API client
  • solar.CurrentConditions - Current solar conditions
  • Solar Potential - Solar irradiance and energy production estimates
  • Panel Placement - Optimal solar panel placement recommendations

🎯 Advanced Features

  • Pagination Support - Automatic multi-page result fetching with nextPageToken handling
  • 73+ Field Masks - Complete coverage of Google Places API fields
  • Field Validation - Automatic validation and cleaning of field masks
  • Photo Downloads - Binary image data retrieval and file saving
  • Geocoding - Forward/reverse geocoding, Place ID geocoding, component filtering
  • Weather Data - Current conditions, forecasts, and historical weather data
  • Air Quality Data - Air quality index, pollutants, and health recommendations
  • Pollen Data - Pollen levels, types, and allergy information
  • Solar Data - Solar potential, irradiance, and energy production estimates
  • Location Validation - Automatic validation of coordinates and time ranges
  • Unit Systems - Support for metric, imperial, and kelvin units
  • Space Handling - Automatic removal of spaces around commas in field masks
  • Field Discovery - List all available field masks with list_field_masks()
  • Performance Optimization - Minimize API costs with targeted field selection

πŸ› οΈ Developer-Friendly Features

  • Global API Key Configuration - Set API key once, use everywhere
  • Type Hints - Full type annotation support for better IDE experience
  • Error Handling - Robust error handling and validation
  • Utility Functions - Helper functions for data formatting and filtering
  • Parameter Builders - Easy construction of complex API parameters
  • Comprehensive Documentation - Detailed docstrings and examples

πŸš€ Environment Setup

Prerequisites

  • Python 3.8 or higher
  • Google Places API key (with Places API (New) enabled)

Installation

Option 1: Install from PyPI (Recommended)

pip install google-maps-platform

Option 2: Install from Source

git clone https://github.com/Chandangowdatk/Google-Maps-Platform.git
cd Google-Maps-Platform
pip install -e .

Option 3: Development Installation

git clone https://github.com/Chandangowdatk/Google-Maps-Platform.git
cd Google-Maps-Platform
pip install -e ".[dev]"

Library Setup

1. Get Google Places API Key

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the Places API (New) for your project
  4. Create credentials (API Key)
  5. Restrict your API key for security (recommended)

2. Set Up Your API Key

Option A: Environment Variable (Recommended)

export GOOGLE_PLACES_API_KEY="your_api_key_here"

Option B: Direct in Code

import google_maps_platform as gmp

# Set API key globally
gmp.set_api_key("your_api_key_here")

Option C: Load from Environment

import google_maps_platform as gmp

# Load from environment variable
gmp.load_from_environment()

3. Verify Installation

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key
gmp.set_api_key("your_api_key_here")

# Test your setup
text_search = TextSearch()
result = text_search.search("restaurants in San Francisco")
print("βœ… Setup successful!" if result else "❌ Setup failed")

πŸ“– Usage Instructions

Basic Usage

1. Set API Key Once (Global Configuration)

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch, NearbySearch, PlaceDetails, PlacePhoto, Geocoding
from google_maps_platform.environment import weather, air_quality, pollen, solar

# Set API key once globally
gmp.set_api_key("your_api_key_here")

# Now use all modules without passing API key
text_search = TextSearch()      # No API key needed!
nearby_search = NearbySearch()  # No API key needed!
place_details = PlaceDetails()  # No API key needed!
place_photo = PlacePhoto()      # No API key needed!
geocoding = Geocoding()         # No API key needed!

# Environment API modules
weather_client = weather.Weather()                    # No API key needed!
air_quality_client = air_quality.AirQuality()        # No API key needed!
pollen_client = pollen.Pollen()                     # No API key needed!
solar_client = solar.Solar()                         # No API key needed!

2. Text Search with Pagination

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key once
gmp.set_api_key("your_api_key_here")

# Use module without API key
text_search = TextSearch()

# Single page search
results = text_search.search(
    text_query="Italian restaurants in San Francisco",
    field_mask="places.id,places.displayName,places.rating",
    number_of_pages=1  # Default: 1 page
)

# Multi-page search (fetch 3 pages)
results = text_search.search(
    text_query="pizza in New York",
    field_mask="places.id,places.displayName,places.rating",
    number_of_pages=3,  # Fetch 3 pages
    page_size=20
)

# Get all available pages
results = text_search.search(
    text_query="coffee shops",
    field_mask="places.id,places.displayName",
    number_of_pages=-1  # -1 means all pages
)

if results:
    print(f"Total places: {results['pagination_info']['total_places']}")
    print(f"Pages fetched: {results['pagination_info']['pages_fetched']}")
    
    for place in results['places']:
        name = place['displayName']['text']
        rating = place.get('rating', 'N/A')
        print(f"{name} - Rating: {rating}")

3. Nearby Search

import google_maps_platform as gmp
from google_maps_platform.places import NearbySearch

# Set API key once
gmp.set_api_key("your_api_key_here")

# Use module without API key
nearby_search = NearbySearch()

# Search near specific coordinates
location = {"latitude": 37.7749, "longitude": -122.4194}
results = nearby_search.search(
    location=location,
    included_types=["restaurant"],
    radius=1000,  # 1km radius
    max_result_count=10
)

4. Place Details

import google_maps_platform as gmp
from google_maps_platform.places import PlaceDetails

# Set API key once
gmp.set_api_key("your_api_key_here")

# Use module without API key
place_details = PlaceDetails()

# Get detailed information about a place
place_id = "ChIJk35bizx-j4AREil6UPp7Jn4"
details = place_details.get_details(
    place_id=place_id,
    field_mask="id,displayName,formattedAddress,rating,photos"
)

if details:
    print(f"Name: {details['displayName']['text']}")
    print(f"Address: {details['formattedAddress']}")
    print(f"Rating: {details.get('rating', 'N/A')}")

5. Place Photos

import google_maps_platform as gmp
from google_maps_platform.places import PlaceDetails, PlacePhoto

# Set API key once
gmp.set_api_key("your_api_key_here")

# Step 1: Get place details with photos
place_details = PlaceDetails()
result = place_details.get_details(
    place_id="ChIJj61dQgK6j4AR4GeTYWZsKWw",
    field_mask="id,displayName,photos"
)

# Step 2: Download photos
if result and 'photos' in result:
    place_photo = PlacePhoto()
    photo_name = result['photos'][0]['name']
    
    # Option A: Get binary data
    image_data = place_photo.get_photo(
        photo_name=photo_name,
        max_width_px=800
    )
    
    # Option B: Save to file
    place_photo.save_photo(
        photo_name=photo_name,
        output_path="place_photo.jpg",
        max_width_px=1024,
        max_height_px=768
    )
    
    # Option C: Get URI only
    uri_response = place_photo.get_photo_uri(
        photo_name=photo_name,
        max_width_px=400
    )
    print(f"Photo URI: {uri_response['photoUri']}")

Environment Variable Usage

1. Load API Key from Environment

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch, NearbySearch, PlaceDetails

# Load API key from environment variable
gmp.load_from_environment()

# Use modules without API key
text_search = TextSearch()
nearby_search = NearbySearch()
place_details = PlaceDetails()

2. Set Environment Variable

# Set environment variable
export GOOGLE_PLACES_API_KEY="your_api_key_here"

# Or in Python
import os
os.environ["GOOGLE_PLACES_API_KEY"] = "your_api_key_here"

Advanced Usage

1. Field Mask Management

from google_maps_platform.places import TextSearch

# Set API key globally
import google_maps_platform as gmp
gmp.set_api_key("your_api_key_here")

text_search = TextSearch()

# List all available field masks
text_search.list_field_masks()

# Search with specific field masks
results = text_search.search(
    text_query="coffee shops",
    field_mask="places.id,places.name,places.location,places.rating,places.priceLevel"
)

# Field masks are automatically validated and cleaned
# Spaces around commas are automatically removed

2. Field Mask Validation

from google_maps_platform.places import TextSearch

text_search = TextSearch()

# Validate field mask (removes spaces around commas)
validated_mask = text_search.validate_field_mask(
    "places.id, places.name, places.location"
)
# Returns: "places.id,places.name,places.location"

3. Utility Functions

from google_maps_platform.places import TextSearch
from google_maps_platform.places.utils import search_places_formatted

# Set API key globally
import google_maps_platform as gmp
gmp.set_api_key("your_api_key_here")

text_search = TextSearch()

# Search for places
results = text_search.search(
    text_query="restaurants in San Francisco",
    page_size=20
)

if results:
    # Use utility function for formatted output
    formatted_results = search_places_formatted(text_search, results)
    print(formatted_results)

πŸ’‘ Code Examples and Use Cases

Use Case 1: Restaurant Discovery App

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key once
gmp.set_api_key("your_api_key_here")

def find_best_restaurants(city, cuisine_type, min_rating=4.0):
    """Find top-rated restaurants in a city"""
    
    text_search = TextSearch()
    
    # Search for restaurants
    results = text_search.search(
        text_query=f"{cuisine_type} restaurants in {city}",
        included_type="restaurant",
        field_mask="places.id,places.displayName,places.rating,places.priceLevel,places.formattedAddress",
        page_size=20,
        min_rating=min_rating
    )
    
    if not results:
        return []
    
    # Sort by rating
    restaurants = results['places']
    sorted_restaurants = sorted(
        restaurants, 
        key=lambda x: x.get('rating', 0), 
        reverse=True
    )
    
    return sorted_restaurants[:10]

# Usage
best_italian = find_best_restaurants("San Francisco", "Italian")
for restaurant in best_italian:
    name = restaurant['displayName']['text']
    rating = restaurant.get('rating', 'N/A')
    price = restaurant.get('priceLevel', 'N/A')
    print(f"{name} - ⭐ {rating} - {price}")

Use Case 2: Business Directory

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key once
gmp.set_api_key("your_api_key_here")

def create_business_directory(category, location, radius_km=5):
    """Create a business directory for a specific category"""
    
    text_search = TextSearch()
    
    # Search for businesses
    results = text_search.search(
        text_query=f"{category} in {location}",
        field_mask="places.id,places.displayName,places.formattedAddress,places.internationalPhoneNumber,places.websiteUri,places.rating",
        page_size=20
    )
    
    if not results:
        return []
    
    businesses = []
    for place in results['places']:
        business = {
            'name': place['displayName']['text'],
            'address': place.get('formattedAddress', 'N/A'),
            'phone': place.get('internationalPhoneNumber', 'N/A'),
            'website': place.get('websiteUri', 'N/A'),
            'rating': place.get('rating', 'N/A'),
        }
        businesses.append(business)
    
    return businesses

# Usage
restaurants = create_business_directory("restaurants", "Downtown San Francisco", 2)
for restaurant in restaurants:
    print(f"🍽️ {restaurant['name']}")
    print(f"   πŸ“ {restaurant['address']}")
    print(f"   πŸ“ž {restaurant['phone']}")
    print(f"   🌐 {restaurant['website']}")
    print()

Use Case 3: Place Search and Filtering

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key once
gmp.set_api_key("your_api_key_here")

def search_and_filter_places(city, place_type, min_rating=4.0):
    """Search and filter places by type and rating"""
    
    text_search = TextSearch()
    
    # Search for places
    results = text_search.search(
        text_query=f"{place_type} in {city}",
        field_mask="places.id,places.displayName,places.rating,places.types",
        page_size=20,
        min_rating=min_rating
    )
    
    if not results:
        return []
    
    places = results['places']
    
    # Sort by rating
    sorted_places = sorted(
        places, 
        key=lambda x: x.get('rating', 0), 
        reverse=True
    )
    
    return sorted_places

# Usage
restaurants = search_and_filter_places("San Francisco", "restaurants", 4.0)
for restaurant in restaurants[:5]:
    name = restaurant['displayName']['text']
    rating = restaurant.get('rating', 'N/A')
    print(f"🍽️ {name} - ⭐ {rating}")

Use Case 4: Weather-Aware Travel Planning

import google_maps_platform as gmp
from google_maps_platform.environment import Weather, CurrentConditions, DailyForecast

# Set API key once
gmp.set_api_key("your_api_key_here")

def plan_weather_aware_trip(destination, days=7):
    """Plan a trip with weather considerations"""
    
    weather = Weather()
    current = CurrentConditions()
    daily = DailyForecast()
    
    # Get current conditions
    current_weather = current.get_current_conditions(destination)
    
    # Get daily forecast
    forecast = daily.get_daily_forecast(destination, days=days)
    
    print(f"🌀️ Weather for {destination['latitude']}, {destination['longitude']}")
    print(f"Current: {current_weather.get('condition', 'Unknown')} - {current_weather.get('temperature', {}).get('value', 'Unknown')}Β°C")
    
    print(f"\nπŸ“… {days}-Day Forecast:")
    for day in forecast.get('forecast', []):
        print(f"  {day.get('date', 'Unknown')}: {day.get('condition', 'Unknown')} - {day.get('high', {}).get('value', 'Unknown')}Β°C")
    
    return {
        'current': current_weather,
        'forecast': forecast
    }

# Usage
trip_weather = plan_weather_aware_trip({
    'latitude': 37.7749,
    'longitude': -122.4194
}, days=5)

Use Case 5: Weather Monitoring Dashboard

import google_maps_platform as gmp
from google_maps_platform.environment import Weather, HourlyForecast, HourlyHistory

# Set API key once
gmp.set_api_key("your_api_key_here")

def create_weather_dashboard(location, hours=24):
    """Create a comprehensive weather dashboard"""
    
    weather = Weather()
    hourly = HourlyForecast()
    history = HourlyHistory()
    
    # Get comprehensive weather data
    comprehensive = weather.get_comprehensive_weather(
        location,
        include_current=True,
        include_daily=True,
        include_hourly=True,
        include_history=True,
        days=5,
        hours=hours
    )
    
    # Get hourly forecast
    hourly_forecast = hourly.get_hourly_forecast(location, hours=hours)
    
    # Get historical data
    historical = history.get_last_24_hours(location)
    
    print(f"🌍 Weather Dashboard for {location['latitude']}, {location['longitude']}")
    
    # Current conditions
    if 'current' in comprehensive['data']:
        current = comprehensive['data']['current']
        print(f"🌑️ Current: {current.get('condition', 'Unknown')} - {current.get('temperature', {}).get('value', 'Unknown')}°C")
        print(f"πŸ’§ Humidity: {current.get('humidity', 'Unknown')}%")
        print(f"πŸ’¨ Wind: {current.get('wind', {}).get('speed', 'Unknown')} km/h")
    
    # Hourly forecast
    print(f"\n⏰ Next {hours} Hours:")
    for hour in hourly_forecast.get('forecast', [])[:6]:  # Show first 6 hours
        print(f"  {hour.get('time', 'Unknown')}: {hour.get('condition', 'Unknown')} - {hour.get('temperature', {}).get('value', 'Unknown')}Β°C")
    
    return comprehensive

# Usage
dashboard = create_weather_dashboard({
    'latitude': 40.7128,
    'longitude': -74.0060
}, hours=48)

Use Case 6: Weather Data Analysis

import google_maps_platform as gmp
from google_maps_platform.environment import Weather, HourlyForecast
from google_maps_platform.environment.utils import get_weather_statistics, get_weather_alerts

# Set API key once
gmp.set_api_key("your_api_key_here")

def analyze_weather_patterns(location, days=7):
    """Analyze weather patterns and trends"""
    
    weather = Weather()
    hourly = HourlyForecast()
    
    # Get comprehensive weather data
    comprehensive = weather.get_comprehensive_weather(
        location,
        include_current=True,
        include_daily=True,
        include_hourly=True,
        days=days,
        hours=168  # 7 days * 24 hours
    )
    
    # Get weather statistics
    stats = get_weather_statistics(comprehensive)
    
    # Get weather alerts
    alerts = get_weather_alerts(comprehensive)
    
    print(f"πŸ“Š Weather Analysis for {location['latitude']}, {location['longitude']}")
    
    # Temperature statistics
    if 'temperature' in stats['statistics']:
        temp_stats = stats['statistics']['temperature']
        print(f"🌑️ Temperature Stats:")
        print(f"  Min: {temp_stats['min']}Β°C")
        print(f"  Max: {temp_stats['max']}Β°C")
        print(f"  Avg: {temp_stats['avg']:.1f}Β°C")
        print(f"  Median: {temp_stats['median']}Β°C")
    
    # Precipitation statistics
    if 'precipitation' in stats['statistics']:
        precip_stats = stats['statistics']['precipitation']
        print(f"🌧️ Precipitation Stats:")
        print(f"  Avg Chance: {precip_stats['avg_chance']:.1f}%")
        print(f"  Max Chance: {precip_stats['max_chance']}%")
        print(f"  Hours with Rain: {precip_stats['hours_with_precipitation']}")
    
    # Weather alerts
    if alerts:
        print(f"⚠️ Weather Alerts:")
        for alert in alerts:
            print(f"  {alert['type']}: {alert['message']}")
    
    return {
        'statistics': stats,
        'alerts': alerts,
        'comprehensive': comprehensive
    }

# Usage
analysis = analyze_weather_patterns({
    'latitude': 51.5074,
    'longitude': -0.1278
}, days=7)

Use Case 7: Geocoding and Address Conversion

import google_maps_platform as gmp
from google_maps_platform.places import Geocoding

# Set API key once
gmp.set_api_key("your_api_key_here")

def geocoding_workflow():
    """Complete geocoding workflow"""
    
    geocoding = Geocoding()
    
    # Forward geocoding (address to coordinates)
    address = "1600 Amphitheatre Parkway, Mountain View, CA"
    lat, lng = geocoding.get_coordinates(address)
    print(f"πŸ“ {address} β†’ {lat}, {lng}")
    
    # Reverse geocoding (coordinates to address)
    reverse_address = geocoding.get_address(lat, lng)
    print(f"🌍 {lat}, {lng} β†’ {reverse_address}")
    
    # Component filtering
    filtered = geocoding.geocode_with_components(
        "Broadway",
        country="US",
        administrative_area="NY"
    )
    print(f"πŸ” Filtered result: {filtered['results'][0]['formatted_address']}")
    
    # Batch geocoding
    addresses = [
        "Times Square, New York, NY",
        "Golden Gate Bridge, San Francisco, CA"
    ]
    results = geocoding.batch_geocode(addresses)
    for result in results:
        if 'error' not in result:
            location = result['results'][0]['geometry']['location']
            print(f"πŸ“¦ {result['address']}: {location['lat']}, {location['lng']}")

# Usage
geocoding_workflow()

Use Case 8: Air Quality Monitoring

import google_maps_platform as gmp
from google_maps_platform.environment import air_quality

# Set API key once
gmp.set_api_key("your_api_key_here")

def monitor_air_quality(location):
    """Monitor air quality for health recommendations"""
    
    air_quality_client = air_quality.AirQuality()
    
    # Get current air quality
    current = air_quality_client.get_current_air_quality(location)
    
    # Get air quality index
    aqi = air_quality_client.get_air_quality_index(location)
    
    # Get health recommendations
    health = air_quality_client.get_health_recommendations(location)
    
    print(f"🌬️ Air Quality for {location['latitude']}, {location['longitude']}")
    print(f"AQI: {aqi.get('air_quality_index', {}).get('value', 'Unknown')}")
    print(f"Overall: {current.get('overallCondition', 'Unknown')}")
    print(f"Health Recommendations: {len(health.get('health_recommendations', []))} items")
    
    return {
        'current': current,
        'aqi': aqi,
        'health': health
    }

# Usage
air_quality_data = monitor_air_quality({
    'latitude': 40.7128,
    'longitude': -74.0060
})

Use Case 8: Pollen Allergy Management

import google_maps_platform as gmp
from google_maps_platform.environment import pollen

# Set API key once
gmp.set_api_key("your_api_key_here")

def manage_pollen_allergies(location, days=5):
    """Manage pollen allergies with forecast data"""
    
    pollen_client = pollen.Pollen()
    
    # Get current pollen
    current = pollen_client.get_current_pollen(location)
    
    # Get pollen forecast
    forecast = pollen_client.get_pollen_forecast(location, days=days)
    
    # Get specialized pollen data
    tree_pollen = pollen_client.get_tree_pollen(location)
    grass_pollen = pollen_client.get_grass_pollen(location)
    weed_pollen = pollen_client.get_weed_pollen(location)
    
    print(f"🌸 Pollen Data for {location['latitude']}, {location['longitude']}")
    print(f"Overall Index: {current.get('overallPollenIndex', {}).get('value', 'Unknown')}")
    print(f"Tree Pollen: {tree_pollen.get('tree_pollen', {}).get('value', 'Unknown')}")
    print(f"Grass Pollen: {grass_pollen.get('grass_pollen', {}).get('value', 'Unknown')}")
    print(f"Weed Pollen: {weed_pollen.get('weed_pollen', {}).get('value', 'Unknown')}")
    
    return {
        'current': current,
        'forecast': forecast,
        'tree_pollen': tree_pollen,
        'grass_pollen': grass_pollen,
        'weed_pollen': weed_pollen
    }

# Usage
pollen_data = manage_pollen_allergies({
    'latitude': 51.5074,
    'longitude': -0.1278
}, days=7)

Use Case 9: Solar Energy Planning

import google_maps_platform as gmp
from google_maps_platform.environment import solar

# Set API key once
gmp.set_api_key("your_api_key_here")

def plan_solar_energy(location):
    """Plan solar energy installation"""
    
    solar_client = solar.Solar()
    
    # Get solar potential
    potential = solar_client.get_solar_potential(location)
    
    # Get solar irradiance
    irradiance = solar_client.get_solar_irradiance(location)
    
    # Get panel placement recommendations
    placement = solar_client.get_solar_panel_placement(location)
    
    # Get energy production estimates
    energy = solar_client.get_energy_production_estimate(location)
    
    print(f"β˜€οΈ Solar Analysis for {location['latitude']}, {location['longitude']}")
    print(f"Solar Potential: {potential.get('solarPotential', {}).get('value', 'Unknown')}")
    print(f"Annual Irradiance: {irradiance.get('annual_irradiance', {}).get('value', 'Unknown')} kWh/mΒ²")
    print(f"Annual Energy: {energy.get('annual_energy', {}).get('value', 'Unknown')} kWh")
    
    return {
        'potential': potential,
        'irradiance': irradiance,
        'placement': placement,
        'energy': energy
    }

# Usage
solar_data = plan_solar_energy({
    'latitude': 33.4484,
    'longitude': -112.0740
})

Use Case 10: Comprehensive Environment Dashboard

import google_maps_platform as gmp
from google_maps_platform.environment import weather, air_quality, pollen, solar

# Set API key once
gmp.set_api_key("your_api_key_here")

def create_environment_dashboard(location):
    """Create a comprehensive environment dashboard"""
    
    # Initialize all environment clients
    weather_client = weather.Weather()
    air_quality_client = air_quality.AirQuality()
    pollen_client = pollen.Pollen()
    solar_client = solar.Solar()
    
    # Get all environment data
    weather_data = weather_client.get_current_conditions(location, units='metric')
    air_quality_data = air_quality_client.get_current_air_quality(location)
    pollen_data = pollen_client.get_current_pollen(location)
    solar_data = solar_client.get_solar_potential(location)
    
    print(f"🌍 Environment Dashboard for {location['latitude']}, {location['longitude']}")
    print(f"🌀️ Weather: {weather_data.get('condition', 'Unknown')} - {weather_data.get('temperature', {}).get('value', 'Unknown')}°C")
    print(f"🌬️ Air Quality: {air_quality_data.get('airQualityIndex', {}).get('value', 'Unknown')}")
    print(f"🌸 Pollen: {pollen_data.get('overallPollenIndex', {}).get('value', 'Unknown')}")
    print(f"β˜€οΈ Solar: {solar_data.get('solarPotential', {}).get('value', 'Unknown')}")
    
    return {
        'weather': weather_data,
        'air_quality': air_quality_data,
        'pollen': pollen_data,
        'solar': solar_data
    }

# Usage
dashboard = create_environment_dashboard({
    'latitude': 35.6762,
    'longitude': 139.6503
})

πŸ“Š Available Field Masks

The library provides 73+ available field masks for Google Places API. Here are some key categories:

Basic Information

  • places.id - Unique place identifier
  • places.name - Place name
  • places.displayName - Display name with language support
  • places.formattedAddress - Complete formatted address
  • places.location - Geographic coordinates

Contact Information

  • places.internationalPhoneNumber - International phone number
  • places.nationalPhoneNumber - National phone number
  • places.websiteUri - Website URL
  • places.googleMapsUri - Google Maps URL

Ratings & Reviews

  • places.rating - Average rating
  • places.userRatingCount - Number of user ratings
  • places.reviews - User reviews
  • places.reviewSummary - Review summary

Business Information

  • places.businessStatus - Current business status
  • places.types - Place types/categories
  • places.priceLevel - Price level indicator
  • places.regularOpeningHours - Regular business hours

Visual Content

  • places.photos - Place photos
  • places.iconBackgroundColor - Icon background color
  • places.iconMaskBaseUri - Icon mask URI

Location Details

  • places.addressComponents - Detailed address components
  • places.plusCode - Plus code for location
  • places.viewport - Viewport bounds
  • places.utcOffsetMinutes - UTC offset

πŸ”§ Configuration Options

Environment Variables

export GOOGLE_PLACES_API_KEY="your_api_key"

API Configuration

import google_maps_platform as gmp

# Set API key globally
gmp.set_api_key("your_api_key")

# Check if API key is set
if gmp.is_api_key_set():
    print("API key is configured")

# Get current configuration
config = gmp.get_config()
print(f"API key set: {config['api_key_set']}")

# Clear API key
gmp.clear_api_key()

🚨 Error Handling

The library provides comprehensive error handling:

import google_maps_platform as gmp
from google_maps_platform.places import TextSearch

# Set API key
gmp.set_api_key("your_api_key")

text_search = TextSearch()

try:
    result = text_search.search("restaurants")
    if result is None:
        print("Search failed - check your API key and query")
    else:
        print(f"Found {len(result['places'])} places")
except Exception as e:
    print(f"Error: {e}")

πŸ“ˆ Performance Tips

  1. Use appropriate field masks - Only request fields you need
  2. Implement caching - Cache results to reduce API calls
  3. Batch requests - Process multiple places efficiently
  4. Use location bias - Improve relevance for local searches
  5. Set reasonable limits - Use appropriate page sizes and result counts
  6. Validate field masks - Use the built-in validation to avoid API errors

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Google Places API team for the excellent API
  • Python community for the amazing ecosystem
  • Contributors and users for feedback and suggestions

πŸ“ž Support

πŸ”— Links


Made with ❀️ by Chandan Gowda

About

An unofficial Python library for Google Maps Platform APIs

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages