Google Maps Solar API JavaScript Sample

repository·main·Indexed 41 days ago

https://github.com/googlemaps-samples/js-solar-potential

A sample application demonstrating the integration of the Google Maps Solar API and Maps JavaScript API. It showcases how to fetch building insights via findClosestBuilding(), retrieve and render GeoTIFF data layers (such as annualFlux, monthlyFlux, and hourlyShade) using the Layer interface, and visualize solar panel configurations on a custom map using Svelte components.

Tokens
4.6K
Snippets
17
Records
19
Agent score
52%

What's inside Google Maps Solar API Sample

  1. Prerequisites for the Solar Potential demo

    main

    Before running the application, ensure you have the following:

    1. Google Maps Platform Account: Sign up for a project.
    2. Enabled APIs: Your project must have both the Maps JavaScript API and the Solar API enabled.
    3. API Key: An API key associated with the project mentioned above.
    4. Local Environment: A current version of Node.js and NPM installed.
  2. Deploy the app to Cloud Run

    main

    You can deploy this application to Google Cloud Run directly from the source. This command uploads your source, builds it using Cloud Build, and starts the service using npm run start.

    # Choose the Cloud location to deploy the app.
    export LOCATION="us-central1"
    
    # Build and deploy the app from source.
    gcloud run deploy "solar-potential" \
      --source="." \
      --region="$LOCATION" \
      --allow-unauthenticated
  3. Check, lint, and format code

    main

    Use the following commands to maintain code quality:

    • Type Checking: npm run check performs type checking. Use npm run check:watch to run it continuously during development.
    • Linting: npm run lint checks for styling and formatting issues.
    • Formatting: npm run format automatically fixes linting issues by formatting the codebase.
    npm run check
    npm run check:watch
    npm run lint
    npm run format
  4. Render single-band GeoTiff using a color palette

    main

    Use renderPalette to visualize single-value GeoTiff data (like solar potential or temperature) by mapping values to a color gradient. This function normalizes the data within a specified range and applies a color palette to create an RGB image.

    import { renderPalette } from './routes/visualize';
    
    const canvas = renderPalette({
      data: singleBandGeoTiff,
      mask: optionalMaskGeoTiff,
      colors: ['000000', 'ffffff'], // Hex color palette
      min: 0,                         // Minimum data value
      max: 100,                       // Maximum data value
      index: 0                        // The raster index to use
    });
  5. Fetch building insights with findClosestBuilding()

    main

    Use findClosestBuilding to retrieve detailed solar potential information for the building closest to a specific location. This includes solar panel configurations, roof segment statistics, and estimated energy production.

    Parameters:

    • location: A google.maps.LatLng object representing the point of interest.
    • apiKey: Your Google Cloud API key.

    Returns: A Promise that resolves to a BuildingInsightsResponse object containing solarPotential data.

    import { findClosestBuilding } from './src/routes/solar';
    
    const location = { lat: () => 37.7749, lng: () => -122.4194 }; // Example google.maps.LatLng
    const apiKey = 'YOUR_API_KEY';
    
    try {
      const insights = await findClosestBuilding(location, apiKey);
      console.log('Solar Potential:', insights.solarPotential);
    } catch (error) {
      console.error('Failed to fetch building insights:', error);
    }
  6. Retrieve a data layer with getLayer()

    main

    Use the getLayer function to asynchronously fetch and initialize a specific data layer. This function handles downloading the necessary GeoTIFF data, calculating bounds, and setting up the rendering logic and color palettes for the requested layer.

    To use getLayer, you must provide:

    1. layerId: The identifier for the layer you want to retrieve.
    2. urls: A DataLayersResponse object containing the URLs for the various data assets (mask, dsm, rgb, etc.).
    3. googleMapsApiKey: Your valid Google Maps API key required for downloading the data.

    Available LayerId values include:

    • mask: Roof mask data.
    • dsm: Digital Surface Model data.
    • rgb: RGB imagery.
    • annualFlux: Annual solar flux data.
    • monthlyFlux: Monthly solar flux data.
    • hourlyShade: Hourly shade/sunlight data.
    import { getLayer } from './routes/layer';
    
    const layer = await getLayer(
      'annualFlux', 
      urls, 
      'YOUR_GOOGLE_MAPS_API_KEY'
    );
  7. Convert hex colors to RGB or RGB to hex

    main

    Utility functions for color format conversion:

    • colorToRGB(color: string): Converts a hex string (e.g., '0099FF' or '#0099FF') to an { r, g, b } object.
    • rgbToColor({ r, g, b }): Converts an { r, g, b } object back to a hex string (e.g., '#0099ff').
    import { colorToRGB, rgbToColor } from './routes/visualize';
    
    const rgb = colorToRGB('#ff0000'); // { r: 255, g: 0, b: 0 }
    const hex = rgbToColor({ r: 255, g: 0, b: 0 }); // '#ff0000'
  8. Create an interpolated RGB color palette

    main

    The createPalette function generates a 256-color lookup table by interpolating between a provided list of hex colors. This ensures smooth color transitions when rendering data via renderPalette.

    import { createPalette } from './routes/visualize';
    
    // Returns an array of 256 {r, g, b} objects
    const palette = createPalette(['ff0000', '00ff00', '0000ff']);