I am trying to convert my shapefile to GeoJSON using the below code snippet:

StringWriter writer = new StringWriter();
String geoJson = null;
FeatureJSON fjson = new FeatureJSON();
fjson.writeFeatureCollection(col, writer);

This works fine for small shapefiles but when I try to convert a file that is of 54 MB the system gets hung.

What should I do differently? Or is there another approach to convert big shapefiles to GeoJSON?

  • 1
    Forgot to mention I am using Geotools libraries to implement this. – Neha Vashishth Jan 8 '19 at 5:59
  • 6
    If you think a 54Mb shapefile is bulky, the GeoJSON equivalent is going to blow your socks off -- 20:1 expansion would not be unreasonable for such a conversion. Maybe you should be looking to generalize the dataset... – Vince Jan 8 '19 at 6:02
  • 3
    Please Edit the question to provide clarifications. – Vince Jan 8 '19 at 6:05
  • 1
    We're a little different from other sites; this isn't a discussion forum but a Q&A site. Please check out our short tour to learn about our focussed Q&A format. – PolyGeo Jan 8 '19 at 7:22

As with all of this sort of task in GeoTools you need to make use of FeatureCollections and DataStores to make life easy.

File inFile = new File("/home/ian/Data/states/states.shp");
File outFile = new File("/home/ian/Data/states/states.geojson");
// Read
DataStore inputDataStore = DataStoreFinder.getDataStore(
        Collections.singletonMap("url", URLs.fileToUrl(inFile)));

String inputTypeName = inputDataStore.getTypeNames()[0];
SimpleFeatureType inputType = inputDataStore.getSchema(inputTypeName);

FeatureSource<SimpleFeatureType, SimpleFeature>
        source = inputDataStore.getFeatureSource(inputTypeName);

FeatureCollection<SimpleFeatureType, SimpleFeature>
        inputFeatureCollection = source.getFeatures();

Map<String, Object> params = new HashMap<>();
params.put(GeoJSONDataStoreFactory.URLP.key, URLs.fileToUrl(outFile));
// Write
DataStore newDataStore = DataStoreFinder.getDataStore(params);

String typeName = newDataStore.getTypeNames()[0];

SimpleFeatureStore featureStore =
        (SimpleFeatureStore) newDataStore.getFeatureSource(typeName);

  • Ian Turton.. Thanks man .. it reduces the processing time now. – Neha Vashishth Jan 17 '19 at 6:40

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.