Feature в Earth Engine определяется как объект GeoJSON. В частности, Feature – это объект со свойством geometry, в котором хранится объект Geometry (или null), и свойством properties, в котором хранится словарь других свойств.
Создание объектов Feature
Чтобы создать объект Feature, передайте конструктору объект Geometry и (необязательно) словарь других свойств. Пример:
Редактор кода (JavaScript)
// Create an ee.Geometry. var polygon = ee.Geometry.Polygon([ [[-35, -10], [35, -10], [35, 10], [-35, 10], [-35, -10]] ]); // Create a Feature from the Geometry. var polyFeature = ee.Feature(polygon, {foo: 42, bar: 'tart'});
import ee import geemap.core as geemap
Colab (Python)
# Create an ee.Geometry. polygon = ee.Geometry.Polygon( [[[-35, -10], [35, -10], [35, 10], [-35, 10], [-35, -10]]] ) # Create a Feature from the Geometry. poly_feature = ee.Feature(polygon, {'foo': 42, 'bar': 'tart'})
Как и в случае с Geometry, объект Feature можно распечатать или добавить на карту для проверки и визуализации:
Редактор кода (JavaScript)
print(polyFeature); Map.addLayer(polyFeature, {}, 'feature');
import ee import geemap.core as geemap
Colab (Python)
display(poly_feature) m = geemap.Map() m.add_layer(poly_feature, {}, 'feature') display(m)
Объект Feature не обязательно должен иметь свойство Geometry. Он может просто содержать словарь свойств. Пример:
Редактор кода (JavaScript)
// Create a dictionary of properties, some of which may be computed values. var dict = {foo: ee.Number(8).add(88), bar: 'nihao'}; // Create a null geometry feature with the dictionary of properties. var nowhereFeature = ee.Feature(null, dict);
import ee import geemap.core as geemap
Colab (Python)
# Create a dictionary of properties, some of which may be computed values. dic = {'foo': ee.Number(8).add(88), 'bar': 'nihao'} # Create a null geometry feature with the dictionary of properties. nowhere_feature = ee.Feature(None, dic)
Обратите внимание, что в этом примере словарь, предоставленный Feature, содержит вычисленное значение. Такой способ создания объектов полезен для экспорта результатов длительных вычислений с результатом Dictionary (например, image.reduceRegion()). Подробную информацию можно найти в руководствах FeatureCollections, Importing Table Data и Exporting.
У каждого объекта Feature есть один основной объект Geometry, который хранится в свойстве geometry. Дополнительные геометрические данные могут храниться в других свойствах.
Методы Geometry, такие как intersection и buffer, также существуют в Feature для удобства получения основного Geometry, применения операции и установки результата в качестве нового основного Geometry.
Результат сохранит все остальные свойства объекта Feature, для которого вызывается метод. Также существуют методы для получения и настройки негеометрических свойств объекта Feature. Пример:
Редактор кода (JavaScript)
// Make a feature and set some properties. var feature = ee.Feature(ee.Geometry.Point([-122.22599, 37.17605])) .set('genus', 'Sequoia').set('species', 'sempervirens'); // Get a property from the feature. var species = feature.get('species'); print(species); // Set a new property. feature = feature.set('presence', 1); // Overwrite the old properties with a new dictionary. var newDict = {genus: 'Brachyramphus', species: 'marmoratus'}; var feature = feature.set(newDict); // Check the result. print(feature);
import ee import geemap.core as geemap
Colab (Python)
# Make a feature and set some properties. feature = ( ee.Feature(ee.Geometry.Point([-122.22599, 37.17605])) .set('genus', 'Sequoia') .set('species', 'sempervirens') ) # Get a property from the feature. species = feature.get('species') display(species) # Set a new property. feature = feature.set('presence', 1) # Overwrite the old properties with a new dictionary. new_dic = {'genus': 'Brachyramphus', 'species': 'marmoratus'} feature = feature.set(new_dic) # Check the result. display(feature)
Обратите внимание, что в предыдущем примере свойства можно задать как с помощью пары "ключ-значение", так и с помощью словаря. Также обратите внимание, что feature.set() перезаписывает существующие свойства.