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
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();
}
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'});
-
1Thanks for the quick update Ulas. Probably geotools will be the solution which I will be able to work on readily at the back end.– NehaCommented Feb 5, 2019 at 6:08