1

I am trying to get the kml file by giving simple polygon data but not able get exact kml Please suggest me if iam wrong.

code snippet:

GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

WKTReader reader = new WKTReader( geometryFactory );

Encoder lEncoder = new Encoder(new KMLConfiguration());

OutputStream lFileOutputStream = null;

lEncoder.setIndenting(true);

try 
{
    lFileOutputStream = new FileOutputStream("my.kml");

    Polygon polygon = (Polygon) reader.read("POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))");
    lEncoder.encode(polygon, KML.kml, lFileOutputStream);
    lFileOutputStream.close(); 
}
catch (FileNotFoundException e1)
{
    e1.printStackTrace();
} 
catch (ParseException e)
{ 
    e.printStackTrace(); 
}
catch (IOException e)
{  
    e.printStackTrace();
}

output getting in KML File

< ?xml version="1.0" encoding="UTF-8"?> < kml:kml xmlns:atom="http://www.w3.org/2005/Atom" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"/>

2

The KML Encoder (like most of GeoTools) works with features not geometries so you need to wrap your polygon in a feature, this gives you the opportunity to add some attributes to make your KML more useful too.

public static void main(String[] args) throws IOException {
    File t = new File("test1.kml");
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();

    builder.setName("test");
    builder.setNamespaceURI("http://www.geotools.org/");
    builder.setSRS("EPSG:4326");
    builder.add("the_geom", Point.class);
    // builder.add("id",Integer.class);
    SimpleFeatureType schema = builder.buildFeatureType();
    ArrayList<SimpleFeature> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      list.add(GenerateRandomData.createSimplePointFeature(schema));
    }
    SimpleFeatureCollection collection = DataUtilities.collection(list);
    exportFeatures(t, collection);

  }

  static void exportFeatures(File outfile, SimpleFeatureCollection features) throws IOException {
    OutputStream outputstream = new BufferedOutputStream(new FileOutputStream(outfile));
    Encoder encoder = new Encoder(new KMLConfiguration());
    encoder.setIndenting(true);
    encoder.encode(features, KML.kml, outputstream);
  }
  • thanks .I am able get KML file.How can i add style like line color, fill color to features . – Suri Apr 9 '16 at 16:30
  • Please ask another question – Ian Turton Apr 9 '16 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.