TransWikia.com

How to print properties of a clicked feature to a panel in Earth Engine Apps

Geographic Information Systems Asked by Justin Braaten on July 12, 2021

I have an Earth Engine App where I display a ee.FeatureCollection. I want to be able to click on a feature and have its properties printed to a ui.Panel widget. How can I do this?

One Answer

Here is one method that will work for polygon features.

var fc = ee.FeatureCollection('FAO/GAUL_SIMPLIFIED_500m/2015/level1');

function getProps(loc) {
  loc = ee.Dictionary(loc);
  var point = ee.Geometry.Point(loc.getNumber('lon'), loc.getNumber('lat'));
  var thisFeature = fc.filterBounds(point).first();
  var props = thisFeature.toDictionary();
  
  props.evaluate(function(props) {
    var str = '';
    Object.keys(props).forEach(function(i) {
      str = str + i + ': ' + props[i] + 'n';
    });
    info.setValue(str);
  });
}

var panel = ui.Panel({style: {position: 'bottom-left', width: '300px', height: '200px'}});
var info = ui.Label({value: 'Click on a feature', style: {whiteSpace: 'pre'}});
panel.add(info);

Map.add(panel);
Map.style().set('cursor', 'crosshair');
Map.onClick(getProps);
Map.addLayer(fc);

Here is the same method modified to work for point features. It searches for the nearest feature in a given radius around the clicked location.

var fc = ee.FeatureCollection('WRI/GPPD/power_plants');

var SEARCH_DISTANCE = 5000;  // Meters.

function getProps(loc) {
  loc = ee.Dictionary(loc);
  var point = ee.Geometry.Point(loc.getNumber('lon'), loc.getNumber('lat'));
  var thisFeature = fc.filterBounds(
    point.buffer(SEARCH_DISTANCE)).map(function(ft) {
      return ft.set('system:click_distance', point.distance(ft.geometry()));
  })
  .sort('system:click_distance').first();
  
  var props = thisFeature.toDictionary();
  
  props.evaluate(function(props) {
    var str = '';
    Object.keys(props).forEach(function(i) {
      str = str + i + ': ' + props[i] + 'n';
    });
    info.setValue(str);
  });
}

var panel = ui.Panel({style: {position: 'bottom-left', width: '300px', height: '200px'}});
var info = ui.Label({value: 'Click on a feature', style: {whiteSpace: 'pre'}});
panel.add(info);

Map.add(panel);
Map.style().set('cursor', 'crosshair');
Map.onClick(getProps);
Map.setCenter(-105.593, 39.228, 7);
Map.addLayer(fc);

Answered by Justin Braaten on July 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP