Run the app in Production mode
mainFor a production-ready version, you must first build the application and then start it. This process optimizes the code and removes development-only tools.
npm run build
npm run startrepository·main·Indexed 41 days ago
https://github.com/googlemaps-samples/js-solar-potentialA 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.
For a production-ready version, you must first build the application and then start it. This process optimizes the code and removes development-only tools.
npm run build
npm run startThe application uses Vite to manage environment variables. To authenticate your requests, create or update a .env file in the project root and add your API key to the VITE_GOOGLE_MAPS_API_KEY variable.
VITE_GOOGLE_MAPS_API_KEY="YOUR_API_KEY"To start the application with hot-reloading enabled (the app will automatically reload when you change files), use the dev script.
npm install
npm run devBefore running the application, ensure you have the following:
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-unauthenticatedUse the following commands to maintain code quality:
npm run check performs type checking. Use npm run check:watch to run it continuously during development.npm run lint checks for styling and formatting issues.npm run format automatically fixes linting issues by formatting the codebase.npm run check
npm run check:watch
npm run lint
npm run formatUse 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
});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);
}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:
layerId: The identifier for the layer you want to retrieve.urls: A DataLayersResponse object containing the URLs for the various data assets (mask, dsm, rgb, etc.).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'
);Mathematical utilities for data processing:
normalize(x, max, min): Scales a value x to a range between 0 and 1 based on the provided min and max.lerp(x, y, t): Performs linear interpolation between x and y based on factor t (0 to 1).clamp(x, min, max): Constrains a value x to stay within the [min, max] range.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'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']);