Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Can someone please provide me an example of how to convert GeoJSON to Shape file using geotools?

share|improve this question
    
may be useful for you gis.stackexchange.com/questions/13762/… –  Sunil Apr 8 '13 at 11:49

2 Answers 2

up vote 3 down vote accepted

I have followed the resource pointed out by @iant and.. Here's the solution:

public static void toShp(File geojson) throws IOException {     
    File shpFile = new File("test.shp");
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("url", shpFile.toURI().toURL());
    params.put("create spatial index", Boolean.TRUE);

    ShapefileDataStore shpDataStore = (ShapefileDataStore)  dataStoreFactory.createNewDataStore(params);


    InputStream in = new FileInputStream(geojson);
    int decimals = 15; 
    GeometryJSON gjson = new GeometryJSON(decimals); 
    FeatureJSON fjson = new FeatureJSON(gjson);

    FeatureCollection fc = fjson.readFeatureCollection(in);

    SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();        
    shpDataStore.createSchema(type);

    Transaction transaction = new DefaultTransaction("create");

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

    SimpleFeatureSource featureSource = shpDataStore.getFeatureSource(typeName);

    if (featureSource instanceof FeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

        featureStore.setTransaction(transaction);
        try {

            featureStore.addFeatures(fc);

            transaction.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
            transaction.rollback();

        } finally {
            transaction.close();
        }
    } else {
        System.out.println(typeName + " does not support read/write access");
    }


  }
share|improve this answer

I don't think there is a precanned example of this but you should be able to work out the basics from the cvs to shapefile example here. There is an unsupported GeoJSON module that should also be of help.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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