// Load a pre-computed Landsat composite for input.
var input = ee.Image('LANDSAT/LE7_TOA_1YEAR/2001');
// Define a region in which to generate a sample of the input.
var region = ee.Geometry.Rectangle(29.7, 30, 32.5, 31.7);
// Display the sample region.
Map.setCenter(31.5, 31.0, 8);
//display border
Map.addLayer(ee.Image().paint(region, 0, 2), {}, 'region');
function addLegend(palette, names) {
//图例的底层Panel
var legend = ui.Panel({
style: {
position: 'bottom-right',
padding: '5px 10px'
}
});
//图例标题
var title = ui.Label({
value: 'Classification',
style: {
fontWeight: 'bold',
color: "red",
fontSize: '16px'
}
});
legend.add(title);
//添加每一列图例颜色以及说明
var addLegendLabel = function(color, name) {
var showColor = ui.Label({
style: {
backgroundColor: '#' + color,
padding: '8px',
margin: '0 0 4px 0'
}
});
var desc = ui.Label({
value: name,
style: {margin: '0 0 4px 8px'}
});
//颜色和说明是水平放置
return ui.Panel({
widgets: [showColor, desc],
layout: ui.Panel.Layout.Flow('horizontal')
});
};
//添加所有的图例列表
for (var i = 0; i < palette.length; i++) {
var label = addLegendLabel(palette[i], names[i]);
legend.add(label);
}
Map.add(legend);
}
var training = input.sample({
region: region,
scale: 30,
numPixels:5000
});
//颜色列表和说明列表
var palette = ['006400','32CD32','EEE8AA','8B4513'];
var names = ["分类A","分类B","分类C","分类D"];
//添加图例
addLegend(palette, names);
//分类
var clusterer = ee.Clusterer.wekaKMeans(palette.length).train(training);
var result = input.cluster(clusterer);
Map.addLayer(result, {palette: palette, min:0, max:palette.length-1}, "classification");
Map.centerObject(region, 9);