Thực hiện yêu cầu lớp dữ liệu

Nhà phát triển ở Khu vực kinh tế Châu Âu (EEA)

Điểm cuối dataLayers cung cấp thông tin chi tiết về bức xạ năng lượng mặt trời cho một khu vực xung quanh một vị trí được chỉ định. Điểm cuối này trả về 17 tệp TIFF có thể tải xuống, bao gồm:

  • Mô hình bề mặt kỹ thuật số (DSM)
  • Lớp tổng hợp RGB (hình ảnh từ trên không hoặc hình ảnh vệ tinh)
  • Một lớp mặt nạ xác định ranh giới của quá trình phân tích
  • Thông lượng bức xạ năng lượng mặt trời hằng năm hoặc sản lượng hằng năm của một bề mặt nhất định
  • Thông lượng bức xạ năng lượng mặt trời hằng tháng hoặc sản lượng hằng tháng của một bề mặt nhất định
  • Bóng râm theo giờ (24 giờ)

Để biết thêm thông tin về cách Solar API xác định thông lượng, hãy xem Các khái niệm về Solar API.

Giới thiệu về yêu cầu lớp dữ liệu

Ví dụ sau đây cho thấy URL của một yêu cầu REST đối với phương thức dataLayers:

https://solar.googleapis.com/v1/dataLayers:get?parameters

Thêm các tham số URL yêu cầu của bạn để chỉ định những thông tin sau:

  • Toạ độ vĩ độ và kinh độ của vị trí
  • Bán kính của khu vực xung quanh vị trí
  • Tập hợp con của dữ liệu cần trả về (DSM, RGB, mặt nạ, thông lượng hằng năm hoặc thông lượng hằng tháng)
  • Chất lượng tối thiểu được phép trong kết quả
  • Tỷ lệ tối thiểu của dữ liệu cần trả về, tính bằng mét trên mỗi pixel

Ví dụ về yêu cầu lớp dữ liệu

Ví dụ sau đây yêu cầu tất cả thông tin chi tiết về toà nhà trong bán kính 100 mét cho vị trí có toạ độ vĩ độ = 37.4450 và kinh độ = -122.1390:

Khóa API

Để đưa ra yêu cầu đối với URL trong phản hồi, hãy thêm khoá API vào URL:

curl -X GET "https://solar.googleapis.com/v1/dataLayers:get?location.latitude=37.4450&location.longitude=-122.1390&radiusMeters=100&view=FULL_LAYERS&requiredQuality=HIGH&exactQualityRequired=true&pixelSizeMeters=0.5&key=YOUR_API_KEY"

Bạn cũng có thể đưa ra yêu cầu HTTP bằng cách dán URL trong yêu cầu cURL vào thanh URL của trình duyệt. Việc truyền khoá API giúp bạn có khả năng sử dụng và phân tích tốt hơn, cũng như kiểm soát quyền truy cập tốt hơn đối với dữ liệu phản hồi.

Mã thông báo OAuth

Lưu ý: Định dạng này chỉ dành cho môi trường thử nghiệm. Để biết thêm thông tin, hãy xem bài viết Sử dụng OAuth.

Để đưa ra yêu cầu đối với URL trong phản hồi, hãy truyền tên dự án thanh toán và mã thông báo OAuth:

curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "X-Goog-User-Project: PROJECT_NUMBER_OR_ID" \
  "https://solar.googleapis.com/v1/dataLayers:get?location.latitude=37.4450&location.longitude=-122.1390&radius_meters=100&required_quality=HIGH&exactQualityRequired=true"
        

TypeScript

Để đưa ra yêu cầu đối với URL trong phản hồi, hãy thêm khoá API hoặc mã thông báo OAuth vào yêu cầu. Ví dụ sau đây sử dụng khoá API khoá:

/**
 * 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 BASE quality, it won't return anything.
    // Here we ask for *at least* BASE quality, but if there's a higher quality available,
    // the Solar API will return us the highest quality available.
    required_quality: 'BASE',
  };
  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;
    },
  );
}

Trường và loại dữ liệu là "loại" trong TypeScript. Trong ví dụ này, chúng ta xác định một loại tuỳ chỉnh để lưu trữ các trường mà bạn quan tâm trong phản hồi, chẳng hạn như giá trị pixel và hộp giới hạn vĩ độ/kinh độ. Bạn có thể thêm nhiều trường hơn nếu muốn.

export interface GeoTiff {
  width: number;
  height: number;
  rasters: Array<number>[];
  bounds: Bounds;
}

Định nghĩa loại dữ liệu

Chúng tôi hỗ trợ các loại dữ liệu sau:

export interface DataLayersResponse {
  imageryDate: Date;
  imageryProcessedDate: Date;
  dsmUrl: string;
  rgbUrl: string;
  maskUrl: string;
  annualFluxUrl: string;
  monthlyFluxUrl: string;
  hourlyShadeUrls: string[];
  imageryQuality: 'HIGH' | 'MEDIUM' | 'BASE';
}

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' | 'BASE';
}

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;
  };
}

API trả về URL theo định dạng sau:

https://solar.googleapis.com/v1/solar/geoTiff:get?id=HASHED_ID

Bạn có thể sử dụng các URL này để truy cập vào tệp GeoTIFF có dữ liệu được yêu cầu.

Ví dụ về phản hồi

Yêu cầu tạo ra phản hồi JSON ở dạng:

{
  "imageryDate": {
    "year": 2022,
    "month": 4,
    "day": 6
  },
  "imageryProcessedDate": {
    "year": 2023,
    "month": 8,
    "day": 4
  },
  "dsmUrl": "https://solar.googleapis.com/v1/geoTiff:get?id=MmQyMzI0NTMyZDc3YjBjNmQ3OTgyM2ZhNzMyNzk5NjItN2ZjODJlOThkNmQ5ZDdmZDFlNWU3MDY4YWFlMWU0ZGQ6UkdCOkhJR0g=",
  "rgbUrl": "https://solar.googleapis.com/v1/geoTiff:get?id=NzQwNGQ0NmUyMzAzYWRiNmMxNzMwZTJhN2IxMTc4NDctOTI5YTNkZTlkM2MzYjRiNjE4MGNkODVmNjNiNDhkMzE6UkdCOkhJR0g=",
  "maskUrl": "https://solar.googleapis.com/v1/geoTiff:get?id=ZTk1YTBlZmY5Y2FhMThlNWYzMWEzZGZhYzEzMGQzOTAtM2Q4NmUyMmM5ZThjZmE0YjhhZWMwN2UzYzdmYmQ3ZjI6TUFTSzpISUdI",
  "annualFluxUrl": "https://solar.googleapis.com/v1/geoTiff:get?id=OTE0OWIxZDM3NmNlYjkzMWY2YjQyYjY5Y2RkYzNiOTAtZjU5YTVjZGQ3MzE3ZTQ4NTNmN2M4ZmY2MWZlZGZkMzg6QU5OVUFMX0ZMVVg6SElHSA==",
  "monthlyFluxUrl": "https://solar.googleapis.com/v1/geoTiff:get?id=Y2NhOGRhOWI2MjVmYmNiZTY3Njk4Yjk0MGJhNTk1NDUtY2MyYTI4NDJmN2Q5YTI0MmY2NDQyZGUwZWJkMWQ0ZDg6TU9OVEhMWV9GTFVYOkhJR0g=",
  "hourlyShadeUrls": [
    "https://solar.googleapis.com/v1/geoTiff:get?id=OWFhOTZmNDU2OGQyNTYxYWQ4YjZkYjQ5NWI4Zjg1ODItZGEwNDNhMmM3NDU0MTY2OGIzZDY2OGU1NTY0NTFlMzE6TU9OVEhMWV9GTFVYOkhJR0g=",
    "https://solar.googleapis.com/v1/geoTiff:get?id=MTI1ZTI2YzM1ZTRlYjA3ZDM4NWE2ODY4MjUzZmIxZTMtNTRmYTI3YmQyYzVjZDcyYjc5ZTlmMTRjZjBmYTk4OTk6TU9OVEhMWV9GTFVYOkhJR0g=",
    ...
  ],
  "imageryQuality": "HIGH"
}

Truy cập vào dữ liệu phản hồi

Việc truy cập vào dữ liệu thông qua URL phản hồi yêu cầu phải xác thực bổ sung. Nếu sử dụng khoá xác thực, bạn phải thêm khoá API vào URL. Nếu sử dụng phương thức xác thực OAuth, bạn phải thêm tiêu đề OAuth.

Khóa API

Để đưa ra yêu cầu đối với URL trong phản hồi, hãy thêm khoá API vào URL:

curl -X GET "https://solar.googleapis.com/v1/solar/geoTiff:get?id=fbde33e9cd16d5fd10d19a19dc580bc1-8614f599c5c264553f821cd034d5cf32&key=YOUR_API_KEY"

Bạn cũng có thể đưa ra yêu cầu HTTP bằng cách dán URL trong yêu cầu cURL vào thanh URL của trình duyệt. Việc truyền khoá API giúp bạn có khả năng sử dụng và phân tích tốt hơn, cũng như kiểm soát quyền truy cập tốt hơn đối với dữ liệu phản hồi.

Mã thông báo OAuth

Để đưa ra yêu cầu đối với URL trong phản hồi, hãy truyền tên dự án thanh toán và mã thông báo OAuth:

curl -X GET \
-H 'X-Goog-User-Project: PROJECT_NUMBER_OR_ID' \
-H "Authorization: Bearer $TOKEN" \
"https://solar.googleapis.com/v1/solar/geoTiff:get?id=fbde33e9cd16d5fd10d19a19dc580bc1-8614f599c5c264553f821cd034d5cf32"
        

TypeScript

Ví dụ sau đây cho thấy cách lấy các giá trị dữ liệu pixel (thông tin được lưu trữ trong từng pixel của hình ảnh kỹ thuật số, bao gồm cả giá trị màu và các thuộc tính khác), tính toán vĩ độ và kinh độ từ GeoTIFF, đồng thời lưu trữ thông tin đó trong một đối tượng TypeScript.

Đối với ví dụ cụ thể này, chúng tôi chọn cho phép kiểm tra loại, giúp giảm lỗi loại, tăng độ tin cậy cho mã và giúp bạn dễ dàng duy trì hơn.

// 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,
    },
  };
}

Ngoại trừ lớp RGB, tất cả các tệp TIFF sẽ hiển thị dưới dạng hình ảnh trống trong các ứng dụng trình xem hình ảnh. Để xem các tệp TIFF đã tải xuống, hãy nhập các tệp đó vào phần mềm ứng dụng lập bản đồ, chẳng hạn như QGIS.

Thông số kỹ thuật đầy đủ của yêu cầu và phản hồi này nằm trong tài liệu tham khảo.