Acabo de descubrir el tutorial de GeoTools para generar un Shapefile a partir de un CSV que contiene una lista de ciudades. He conseguido que funcione pero cuando intento crear una nueva Geografía en SpaceStat, importando el Shapefile recién creado, me sale un error que dice:
Import failed: No valid objects were found
He intentado echar un vistazo a los documentos de SpaceStat pero no he encontrado nada sobre este error. Hay requisitos particulares para el Shapefile para ser importados en SpaceStat?
Este es el código que utilizo para generar el shapefile.
public class Csv2Shape {
SimpleFeatureType TYPE = null;
public Csv2Shape() {
System.out.println("Constructor");
try {
TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String," + "number:Integer");
System.out.println("Type init: "+ TYPE);
} catch (SchemaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
File file = JFileDataStoreChooser.showOpenFile("csv", null);
if (file == null) {
return;
}
Csv2Shape csvshape = new Csv2Shape();
System.out.println("TYPE:"+csvshape.TYPE);
/*
* We create a FeatureCollection into which we will put each Feature created from a record
* in the input csv data file
*/
List<SimpleFeature> collection = new ArrayList<SimpleFeature>();
/*
* GeometryFactory will be used to create the geometry attribute of each feature (a Point
* object for the location)
*/
GeometryFactory geometryFactory = new GeometryFactory();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(csvshape.TYPE);
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
/* First line of the data file is the header */
String line = reader.readLine();
System.out.println("Header: " + line);
for (line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.trim().length() > 0) { // skip blank lines
String tokens[] = line.split("\\,");
double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);
String name = tokens[2].trim();
int number = Integer.parseInt(tokens[3].trim());
/* Longitude (= x coord) first ! */
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
featureBuilder.add(point);
featureBuilder.add(name);
featureBuilder.add(number);
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
} finally {
reader.close();
}
File newFile = getNewShapeFile(file);
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(csvshape.TYPE);
/*
* You can comment out this line if you are using the createFeatureType method (at end of
* class file) rather than DataUtilities.createType
*/
newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
/*
* Write the features to the shapefile
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
SimpleFeatureCollection sfcollection = DataUtilities.collection(collection);
featureStore.addFeatures(sfcollection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
}
/**
* Prompt the user for the name and path to use for the output shapefile
*
* @param csvFile
* the input csv file used to create a default shapefile name
*
* @return name and path for the shapefile as a new File object
*/
private static File getNewShapeFile(File csvFile) {
String path = csvFile.getAbsolutePath();
String newPath = path.substring(0, path.length() - 4) + ".shp";
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(newPath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
// the user cancelled the dialog
System.exit(0);
}
File newFile = chooser.getSelectedFile();
if (newFile.equals(csvFile)) {
System.out.println("Error: cannot replace " + csvFile);
System.exit(0);
}
return newFile;
}
}