2

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.

3

You can use Openlayers (javascript) for this. Simply, load a vector layer from Geojson and then export the features in KML. Below code sample should get you going for Openlayers 4 assuming you want to export in EPSG:3857:

var vectorSource = new ol.source.Vector({
    features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var format = new ol.format.KML();
var kml = format.writeFeatures(vectorSource.getFeatures(), {featureProjection: 'EPSG:3857'});
  • 1
    Thanks for the quick update Ulas. Probably geotools will be the solution which I will be able to work on readily at the back end. – Neha Vashishth Feb 5 at 6:08
3

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();
}

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.