Wednesday, January 23, 2008

How to really create a ShapeFile

I have been struggling around for a very long while and went through many different methods of creating a shapefile. Thanks to Jody Garnett and the geotools team this has now come to a (temporary) end. Adapted from some mailinglist thread and this page:


// Create the DataStoreFactory
FileDataStoreFactorySpi factory = new IndexedShapefileDataStoreFactory();

// Create the file you want to write to
File file = null;
if (pathToFile.toLowerCase().endsWith(".shp")) {
file = new File(pathToFile);
} else {
file = new File(pathToFile + ".shp");
}
// Create a Map object used by our DataStore Factory
// NOTE: file.toURI().toURL() is used because file.toURL() is deprecated
Map map = Collections.singletonMap("shapefile url", file.toURI().toURL());

// Create the ShapefileDataStore from our factory based on our Map object
ShapefileDataStore myData = (ShapefileDataStore) factory.createNewDataStore(map);

// Tell this shapefile what type of data it will store
// Shapefile handle only : MultiPoint, MultiLineString, MultiPolygon
FeatureType featureType = DataUtilities.createType("some name", fieldsSpec);
// where fieldsSpec is a string description of the contents of the shapefile,
// somthing like "geom:MultiPoint,name:String,id:Integer,description:String


// Create the Shapefile (empty at this point)
myData.createSchema(featureType);

// Tell the DataStore what type of Coordinate Reference System (CRS) to use
myData.forceSchemaCRS(crs);

FeatureCollection collection = FeatureCollections.newCollection();

Object[][] attr = attributes;
// where attributes is an array of arrays (sometimes called matrix,
// but it is easier to understand in this context :)) of the attributes
// of the future shapefile, also containing in the first array the geometries
try {
for( int i = 0; i < record =" new" j =" 0;" featurename =" myData.getTypeNames()[0];" transaction =" null;" store =" null;" transaction =" new" store =" (FeatureStore)">
Post a Comment