幾何運算

Earth Engine 支援對 Geometry 物件執行的各種作業。這些運算包括對個別幾何圖形執行的運算,例如計算緩衝區、中位點、邊界框、周邊、凸包等。例如:

程式碼編輯器 (JavaScript)

// Create a geodesic polygon.
var polygon = ee.Geometry.Polygon([
  [[-5, 40], [65, 40], [65, 60], [-5, 60], [-5, 60]]
]);

// Compute a buffer of the polygon.
var buffer = polygon.buffer(1000000);

// Compute the centroid of the polygon.
var centroid = polygon.centroid();
Map.addLayer(buffer, {}, 'buffer');
Map.addLayer(centroid, {}, 'centroid');

請注意,上一個範例中的緩衝區距離是以公尺為單位。

支援的幾何運算也包括幾何圖形之間的關係運算,例如交集、並集、差集、距離、包含等。為了測試其中部分關係,幾何圖形預設會使用「奇偶」規則。根據奇偶規則,如果從該點到某個位於多邊形外側的點的線條會與其他邊交錯,則該點就位於多邊形內。多邊形內部是指外殼內的所有內容,而非洞內的內容。舉個簡單的例子,圓形多邊形內的點必須跨越一個邊,才能離開多邊形。幾何圖形可視需要使用「左側內側」規則。請想像以指定順序沿著環狀路線行走,內側會在左側。

為了說明使用「左側內側」規則 (evenOdd: false) 和「奇數-奇數」規則建立的幾何圖形有何不同,以下範例會將一個點與兩個不同的多邊形進行比較:

程式碼編輯器 (JavaScript)

// Create a left-inside polygon.
var holePoly = ee.Geometry.Polygon({
  coords: [
    [[-35, -10], [-35, 10], [35, 10], [35, -10], [-35, -10]]
  ],
  evenOdd: false
});

// Create an even-odd version of the polygon.
var evenOddPoly = ee.Geometry({
  geoJson: holePoly,
  evenOdd: true
});

// Create a point to test the insideness of the polygon.
var pt = ee.Geometry.Point([1.5, 1.5]);

// Check insideness with a contains operator.
print(holePoly.contains(pt));       // false
print(evenOddPoly.contains(pt));    // true

上一個範例說明提供給 Polygon 建構函式的座標順序,如何影響建構左內側多邊形的結果。具體來說,該點位於左側內部多邊形外,但位於奇偶多邊形內。

以下範例會根據兩個多邊形之間的關係,計算及視覺化衍生幾何圖形:

程式碼編輯器 (JavaScript)

// Create two circular geometries.
var poly1 = ee.Geometry.Point([-50, 30]).buffer(1e6);
var poly2 = ee.Geometry.Point([-40, 30]).buffer(1e6);

// Display polygon 1 in red and polygon 2 in blue.
Map.setCenter(-45, 30);
Map.addLayer(poly1, {color: 'FF0000'}, 'poly1');
Map.addLayer(poly2, {color: '0000FF'}, 'poly2');

// Compute the intersection, display it in green.
var intersection = poly1.intersection(poly2, ee.ErrorMargin(1));
Map.addLayer(intersection, {color: '00FF00'}, 'intersection');

// Compute the union, display it in magenta.
var union = poly1.union(poly2, ee.ErrorMargin(1));
Map.addLayer(union, {color: 'FF00FF'}, 'union');

// Compute the difference, display in yellow.
var diff1 = poly1.difference(poly2, ee.ErrorMargin(1));
Map.addLayer(diff1, {color: 'FFFF00'}, 'diff1');

// Compute symmetric difference, display in black.
var symDiff = poly1.symmetricDifference(poly2, ee.ErrorMargin(1));
Map.addLayer(symDiff, {color: '000000'}, 'symmetric difference');

請注意,在這些範例中,maxError 參數會設為一公尺,以便執行幾何運算。maxError 是轉換 (例如投影或重新投影) 可能會變更幾何圖形的最大允許誤差,以公尺為單位。如果其中一個幾何圖形的經緯度與另一個不同,Earth Engine 會在球形座標系統中執行運算,並由 maxError 提供投影精確度。您也可以視需要指定要執行運算的特定投影。