[GIS] Export KML from google earth engine

google-earth-enginehabitat-modeling

I'm using google earth engine to do some simple habitat classification and now want to export the result as a KML or KMZ. When I run this code it is layer 2 that I want to export – the habitat classification map.

  //sat image
    var S1 = ee.ImageCollection("COPERNICUS/S1_GRD"),
    S2 = ee.ImageCollection("COPERNICUS/S2"),
    fc = ee.FeatureCollection("ft:1jvw7bQoChrt-3dk4bQC96TMjZnnyrw6DvaLpfEdk"),//polygon
    fc2 = ee.FeatureCollection("ft:1_uzNGOXOEdfnRmkIYIkVCiMHGx8gCr-1ywGyhjLF"),//points
    fc3 = ee.FeatureCollection("ft:1WXJEHBhLLe1ztmsjzt7WyMe1Go04Uuj96XEQ-C0-");//study area
    //Set a point of interest 
    var aoi = fc; 
    //Set bands of interest
    var bands = ['B2', 'B3', 'B4','B8', 'B11', 'B12'];

//Import and filter Sentinel 2 collection
var S2 = ee.ImageCollection('COPERNICUS/S2')
.filterDate('2017-06-20', '2017-07-20')
.filterBounds(aoi)
 print(S2);
var image = S2.mosaic();
// Clip the image to the polygon geometry
var landcover_roi = image.clip(fc3);

Map.addLayer(landcover_roi, {'bands': 'B12,B8,B4','min': 0,'max': 4000},        'Sentinel 2A SWIR,NIT,R', 0);
var training = landcover_roi.sampleRegions(fc2, ["name"], 59);
var classifier = ee.Classifier.cart()
.train(training, "name", landcover_roi.bandNames());
var out = landcover_roi.classify(classifier);
Map.addLayer(out, {palette: [
'ff0000',// not forest
'387242',// forest
'e0e0d1',// volcano 
], min:1, max:3});

// Create a geometry representing an export region.
var geometry = geometry;

Map.addLayer(ee.Image().paint(fc, 1, 3));
var fc = fc2;
Map.addLayer(fc2);

 //Create a band for each veg type
 var class1 = out.eq(1).select([0],['not forest']);
 var class2 = out.eq(2).select([0],['forest']);
 var class3 = out.eq(3).select([0],['volcano']);
 // Concatanate the bands into a single image
 var total = ee.Image.cat([class1,class2,class3]);


 // Export the FeatureCollection to a KML file.
Export.image.toDrive({
  image: total,
  description: 'imageToDriveExample',
  scale: 30,
  region: geometry
});

Best Answer

You could do it directly in GEE:

var shape = out.reduceToVectors({
  geometry: geometry,
  crs: ee.Projection('EPSG:4326'),
  scale: 10,
  maxPixels: 1e13
})

Export.table.toDrive({
  collection: shape, 
  description: "yourDescription", 
  folder: "yourFolder", 
  fileNamePrefix:"yourName", 
  fileFormat:"KML"
})

But I do not recommend to do it directly like that because there are a lot of small areas and it'll take too long to process (may be it won't do it). You could process it a bit more in GEE, like filtering by count property or apply a focal_mode or something, or you could download the raster and do the process locally with a raster to vector algorithm.