[GIS] GeoJSON to KML conversion

geojsongeotoolskml

Is it possible to convert GeoJSON to KML format using geotools. I am trying to figure out this using Java but I can get results only using node js.

Best Answer

GeoTools will read GeoJSON and write KML quite easily:

URL url = URLs.fileToUrl(new File("/home/ian/Data/states/states.geojson"));
HashMap<String, Object> params = new HashMap<>();
params.put(GeoJSONDataStoreFactory.URLP.key, url);
DataStore in = DataStoreFinder.getDataStore(params);
if(in == null) {
  throw new IOException("couldn't open datastore from "+url);
}
SimpleFeatureCollection features = in.getFeatureSource(in.getTypeNames()[0]).getFeatures();
Encoder encoder = new Encoder(new KMLConfiguration());
encoder.setIndenting(true);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
  encoder.encode(features, KML.kml, os);
  String out = os.toString().replaceAll("kml:", "");
  System.out.println(out);
} catch (Exception e) {
  e.printStackTrace();
}