java - 如何使用 GeoTools API 创建和填充 shp 文件
问题描述
我需要创建一个空的形状文件并用我的 java 集合中的数据填充它。有人可以向我展示如何实现这一目标的示例吗?提前致谢。
解决方案
有关完整详细信息,请参阅CSV 到 Shapefile 教程。
基本上,您需要在SimpleFeatureType
对象中定义 Shapefiles 列,最简单的方法是使用SimpleFeatureTypeBuilder
. 这里是直接使用实用程序方法生成的,以节省时间。
final SimpleFeatureType TYPE =
DataUtilities.createType("Location",
"location:Point:srid=4326," + // <- the geometry attribute: Point type
"name:String," + // <- a String attribute
"number:Integer" // a number attribute
);
现在,您可以创建 Shapefile:
/*
* Get an output file name and create the new shapefile
*/
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(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);
并且,最后将集合写入Features
它:
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 {
featureStore.addFeatures(collection);
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);
}
推荐阅读
- html - 网页突然不显示图像或下载脚本:431错误
- flutter - Flutter,如何制作简单的截图分享?
- google-apps-script - 将一堆单张文件编译成大型电子表格的最简单方法是什么?
- sql - 在 SQL 查询代码中放置未声明的变量会生成输入框?
- javascript - 如何在 ReactJS 中启用悬停
- html - Angular/ HTML5 到 iOS WKWebView 通信
- binary - 如果我有这些文件之一的内容,则破解二进制文件格式
- ios - 将多个自定义 TableViewCell Xib 索引到 TableView
- sql - 如何以 CSV UTF-8 而不是 UTF-8 BOM 导出结果
- ios - 当 iOS 应用程序崩溃时,有没有办法采取行动,从而执行代码?这可能吗?