3

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.

2 Answers 2

5

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

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
  • 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
    Commented Feb 5, 2019 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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