在 FeatureCollection 上进行映射

如需对 FeatureCollection 中的每个 Feature 应用相同的操作,请使用 featureCollection.map()。例如,如需向流域 FeatureCollection 中的每个地图项添加另一个面积属性,请使用以下命令:

Code Editor (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 API 以及如何使用 geemap 进行交互式开发,请参阅 Python 环境页面。

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。 以下示例将流域转换为质心:

Code Editor (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 API 以及如何使用 geemap 进行交互式开发,请参阅 Python 环境页面。

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

请注意,只有部分属性会传播到新集合中的地图项。