對 FeatureCollection 進行對應

如要將相同的作業套用至 FeatureCollection 中的每個 Feature,請使用 featureCollection.map()。舉例來說,如要在集水區 FeatureCollection 中的每個要素中新增其他區域屬性,請使用以下方式:

程式碼編輯器 (JavaScript)

// Load watersheds from a data table.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06');

// This function computes the feature's geometry area and adds it as a property.
var addArea = function(feature) {
  return feature.set({areaHa: feature.geometry().area().divide(100 * 100)});
};

// Map the area getting function over the FeatureCollection.
var areaAdded = sheds.map(addArea);

// Print the first feature from the collection with the added property.
print('First feature:', areaAdded.first());

Python 設定

請參閱「 Python 環境」頁面,瞭解 Python API 和如何使用 geemap 進行互動式開發。

import ee
import geemap.core as geemap

Colab (Python)

# Load watersheds from a data table.
sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06')

# Map an area calculation function over the FeatureCollection.
area_added = sheds.map(
    lambda feature: feature.set(
        {'areaHa': feature.geometry().area().divide(100 * 100)}
    )
)

# Print the first feature from the collection with the added property.
display('First feature:', area_added.first())

請注意,在上一個範例中,新屬性是根據使用地圖項目幾何形狀的運算設定。您也可以使用涉及現有屬性的運算來設定屬性。

您可以使用 map() 產生全新的 FeatureCollection。以下範例會將集水區轉換為中心點:

程式碼編輯器 (JavaScript)

// This function creates a new feature from the centroid of the geometry.
var getCentroid = function(feature) {
  // Keep this list of properties.
  var keepProperties = ['name', 'huc6', 'tnmid', 'areasqkm'];
  // Get the centroid of the feature's geometry.
  var centroid = feature.geometry().centroid();
  // Return a new Feature, copying properties from the old Feature.
  return ee.Feature(centroid).copyProperties(feature, keepProperties);
};

// Map the centroid getting function over the features.
var centroids = sheds.map(getCentroid);

// Display the results.
Map.addLayer(centroids, {color: 'FF0000'}, 'centroids');

Python 設定

請參閱「 Python 環境」頁面,瞭解 Python API 和如何使用 geemap 進行互動式開發。

import ee
import geemap.core as geemap

Colab (Python)

# This function creates a new feature from the centroid of the geometry.
def get_centroid(feature):
  # Keep this list of properties.
  keep_properties = ['name', 'huc6', 'tnmid', 'areasqkm']
  # Get the centroid of the feature's geometry.
  centroid = feature.geometry().centroid()
  # Return a new Feature, copying properties from the old Feature.
  return ee.Feature(centroid).copyProperties(feature, keep_properties)

# Map the centroid getting function over the features.
centroids = sheds.map(get_centroid)

# Display the results.
m = geemap.Map()
m.set_center(-96.25, 40, 4)
m.add_layer(centroids, {'color': 'FF0000'}, 'centroids')
m

請注意,只有部分屬性會傳播至新集合中的功能。