-
Notifications
You must be signed in to change notification settings - Fork 61
/
solar.ts
294 lines (265 loc) · 9.03 KB
/
solar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
Copyright 2023 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// [START solar_api_data_types]
export interface DataLayersResponse {
imageryDate: Date;
imageryProcessedDate: Date;
dsmUrl: string;
rgbUrl: string;
maskUrl: string;
annualFluxUrl: string;
monthlyFluxUrl: string;
hourlyShadeUrls: string[];
imageryQuality: 'HIGH' | 'MEDIUM' | 'LOW';
}
export interface Bounds {
north: number;
south: number;
east: number;
west: number;
}
// https://developers.google.com/maps/documentation/solar/reference/rest/v1/buildingInsights/findClosest
export interface BuildingInsightsResponse {
name: string;
center: LatLng;
boundingBox: LatLngBox;
imageryDate: Date;
imageryProcessedDate: Date;
postalCode: string;
administrativeArea: string;
statisticalArea: string;
regionCode: string;
solarPotential: SolarPotential;
imageryQuality: 'HIGH' | 'MEDIUM' | 'LOW';
}
export interface SolarPotential {
maxArrayPanelsCount: number;
panelCapacityWatts: number;
panelHeightMeters: number;
panelWidthMeters: number;
panelLifetimeYears: number;
maxArrayAreaMeters2: number;
maxSunshineHoursPerYear: number;
carbonOffsetFactorKgPerMwh: number;
wholeRoofStats: SizeAndSunshineStats;
buildingStats: SizeAndSunshineStats;
roofSegmentStats: RoofSegmentSizeAndSunshineStats[];
solarPanels: SolarPanel[];
solarPanelConfigs: SolarPanelConfig[];
financialAnalyses: object;
}
export interface SizeAndSunshineStats {
areaMeters2: number;
sunshineQuantiles: number[];
groundAreaMeters2: number;
}
export interface RoofSegmentSizeAndSunshineStats {
pitchDegrees: number;
azimuthDegrees: number;
stats: SizeAndSunshineStats;
center: LatLng;
boundingBox: LatLngBox;
planeHeightAtCenterMeters: number;
}
export interface SolarPanel {
center: LatLng;
orientation: 'LANDSCAPE' | 'PORTRAIT';
segmentIndex: number;
yearlyEnergyDcKwh: number;
}
export interface SolarPanelConfig {
panelsCount: number;
yearlyEnergyDcKwh: number;
roofSegmentSummaries: RoofSegmentSummary[];
}
export interface RoofSegmentSummary {
pitchDegrees: number;
azimuthDegrees: number;
panelsCount: number;
yearlyEnergyDcKwh: number;
segmentIndex: number;
}
export interface LatLng {
latitude: number;
longitude: number;
}
export interface LatLngBox {
sw: LatLng;
ne: LatLng;
}
export interface Date {
year: number;
month: number;
day: number;
}
export interface RequestError {
error: {
code: number;
message: string;
status: string;
};
}
// [END solar_api_data_types]
// https://developers.google.com/maps/documentation/solar/reference/rest/v1/dataLayers
export type LayerId = 'mask' | 'dsm' | 'rgb' | 'annualFlux' | 'monthlyFlux' | 'hourlyShade';
// [START solar_api_building_insights]
/**
* Fetches the building insights information from the Solar API.
* https://developers.google.com/maps/documentation/solar/building-insights
*
* @param {LatLng} location Point of interest as latitude longitude.
* @param {string} apiKey Google Cloud API key.
* @return {Promise<DataLayersResponse>} Building Insights response.
*/
export async function findClosestBuilding(
location: google.maps.LatLng,
apiKey: string,
): Promise<BuildingInsightsResponse> {
const args = {
'location.latitude': location.lat().toFixed(5),
'location.longitude': location.lng().toFixed(5),
};
console.log('GET buildingInsights\n', args);
const params = new URLSearchParams({ ...args, key: apiKey });
// https://developers.google.com/maps/documentation/solar/reference/rest/v1/buildingInsights/findClosest
return fetch(`https://solar.googleapis.com/v1/buildingInsights:findClosest?${params}`).then(
async (response) => {
const content = await response.json();
if (response.status != 200) {
console.error('findClosestBuilding\n', content);
throw content;
}
console.log('buildingInsightsResponse', content);
return content;
},
);
}
// [END solar_api_building_insights]
// [START solar_api_data_layers]
/**
* Fetches the data layers information from the Solar API.
* https://developers.google.com/maps/documentation/solar/data-layers
*
* @param {LatLng} location Point of interest as latitude longitude.
* @param {number} radiusMeters Radius of the data layer size in meters.
* @param {string} apiKey Google Cloud API key.
* @return {Promise<DataLayersResponse>} Data Layers response.
*/
export async function getDataLayerUrls(
location: LatLng,
radiusMeters: number,
apiKey: string,
): Promise<DataLayersResponse> {
const args = {
'location.latitude': location.latitude.toFixed(5),
'location.longitude': location.longitude.toFixed(5),
radius_meters: radiusMeters.toString(),
// The Solar API always returns the highest quality imagery available.
// By default the API asks for HIGH quality, which means that HIGH quality isn't available,
// but there is an existing MEDIUM or LOW quality, it won't return anything.
// Here we ask for *at least* LOW quality, but if there's a higher quality available,
// the Solar API will return us the highest quality available.
required_quality: 'LOW',
};
console.log('GET dataLayers\n', args);
const params = new URLSearchParams({ ...args, key: apiKey });
// https://developers.google.com/maps/documentation/solar/reference/rest/v1/dataLayers/get
return fetch(`https://solar.googleapis.com/v1/dataLayers:get?${params}`).then(
async (response) => {
const content = await response.json();
if (response.status != 200) {
console.error('getDataLayerUrls\n', content);
throw content;
}
console.log('dataLayersResponse', content);
return content;
},
);
}
// [END solar_api_data_layers]
// [START solar_api_data_layer_custom_type]
export interface GeoTiff {
width: number;
height: number;
rasters: Array<number>[];
bounds: Bounds;
}
// [END solar_api_data_layer_custom_type]
// [START solar_api_download_geotiff]
// npm install geotiff geotiff-geokeys-to-proj4 proj4
import * as geotiff from 'geotiff';
import * as geokeysToProj4 from 'geotiff-geokeys-to-proj4';
import proj4 from 'proj4';
/**
* Downloads the pixel values for a Data Layer URL from the Solar API.
*
* @param {string} url URL from the Data Layers response.
* @param {string} apiKey Google Cloud API key.
* @return {Promise<GeoTiff>} Pixel values with shape and lat/lon bounds.
*/
export async function downloadGeoTIFF(url: string, apiKey: string): Promise<GeoTiff> {
console.log(`Downloading data layer: ${url}`);
// Include your Google Cloud API key in the Data Layers URL.
const solarUrl = url.includes('solar.googleapis.com') ? url + `&key=${apiKey}` : url;
const response = await fetch(solarUrl);
if (response.status != 200) {
const error = await response.json();
console.error(`downloadGeoTIFF failed: ${url}\n`, error);
throw error;
}
// Get the GeoTIFF rasters, which are the pixel values for each band.
const arrayBuffer = await response.arrayBuffer();
const tiff = await geotiff.fromArrayBuffer(arrayBuffer);
const image = await tiff.getImage();
const rasters = await image.readRasters();
// Reproject the bounding box into lat/lon coordinates.
const geoKeys = image.getGeoKeys();
const projObj = geokeysToProj4.toProj4(geoKeys);
const projection = proj4(projObj.proj4, 'WGS84');
const box = image.getBoundingBox();
const sw = projection.forward({
x: box[0] * projObj.coordinatesConversionParameters.x,
y: box[1] * projObj.coordinatesConversionParameters.y,
});
const ne = projection.forward({
x: box[2] * projObj.coordinatesConversionParameters.x,
y: box[3] * projObj.coordinatesConversionParameters.y,
});
return {
// Width and height of the data layer image in pixels.
// Used to know the row and column since Javascript
// stores the values as flat arrays.
width: rasters.width,
height: rasters.height,
// Each raster reprents the pixel values of each band.
// We convert them from `geotiff.TypedArray`s into plain
// Javascript arrays to make them easier to process.
rasters: [...Array(rasters.length).keys()].map((i) =>
Array.from(rasters[i] as geotiff.TypedArray),
),
// The bounding box as a lat/lon rectangle.
bounds: {
north: ne.y,
south: sw.y,
east: ne.x,
west: sw.x,
},
};
}
// [END solar_api_download_geotiff]
export function showLatLng(point: LatLng) {
return `(${point.latitude.toFixed(5)}, ${point.longitude.toFixed(5)})`;
}
export function showDate(date: Date) {
return `${date.month}/${date.day}/${date.year}`;
}