Geotools创建Feature的两种方式
我们在操作矢量数据的无法避免的是与Feature打交道,在这里介绍两种关于Feature的创建方式,玩了那么久的GIS开发,无论哪种GIS二次开发,始终在模仿人在使用软件操作数据的流程,在学习的GIS开发的时候,首先应该明白,这个功能如果利用GIS商业软件,会有那些流程顺序,按照这个思路,很快就能掌握你所用开发的SDK包中,用那些类完成此任务再加上api事倍功半。
一、SimpleFeatureBuilder方式创建
//创建GeometryFactory工厂
GeometryFactory geometryFactory = new GeometryFactory();
SimpleFeatureCollection collection =null;
//获取类型
SimpleFeatureType TYPE = featureSource.getSchema();
System.out.println(TYPE);
//创建要素集合
List<SimpleFeature> features = new ArrayList<>();
//创建要素模板
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
//创建要素并添加道集合
double latitude = Double.parseDouble("39.9");
double longitude = Double.parseDouble("116.3");
String name ="beijing";
int number = Integer.parseInt("16");
//创建一个点geometry
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
//添加的数据一定按照SimpleFeatureType给的字段顺序进行赋值
//添加name属性
featureBuilder.add(name);
//添加number属性
featureBuilder.add(number);
//添加geometry属性
featureBuilder.add(point);
//构建要素
SimpleFeature feature = featureBuilder.buildFeature(null);
Note:featureBuilder添加的数据一定按照SimpleFeatureType给的字段顺序进行赋值!!!!!!!!!!
二、getFeatureWriter方式创建
SimpleFeatureSource featureSource = null;
//根据图层名称来获取要素的source
featureSource = shpDataStore.getFeatureSource (typeName);
//根据参数创建shape存储空间
ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
SimpleFeatureType sft = featureSource.getSchema();
//创建要素模板
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
//设置坐标系
tb.setCRS(DefaultGeographicCRS.WGS84);
tb.setName("shapefile");
//创建
ds.createSchema(tb.buildFeatureType());
//设置编码
ds.setCharset(charset);
//设置Writer,并设置为自动提交
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
//循环写入要素
while (itertor.hasNext())
{
//获取要写入的要素
SimpleFeature feature = itertor.next();
//将要写入位置
SimpleFeature featureBuf = writer.next();
//设置写入要素所有属性
featureBuf.setAttributes(feature.getAttributes());
//获取the_geom属性的值
Geometry geo =(Geometry) feature.getAttribute("the_geom");
Geometry geoBuffer = geoR.calBuffer(geo, 0.1);
System.out.println(geoBuffer);
//重新覆盖the_geom属性的值,这里的geoBuffer必须为Geometry类型
featureBuf.setAttribute("the_geom", geoBuffer);
}
//将所有数据写入
writer.write();
//关闭写入流
writer.close();
itertor.close();
}
catch(Exception e){
e.printStackTrace();
}
总结:
两种都差不多,个人感觉第二种方式创建更为灵活一点,关于第一种必须保证写入字段的Value的顺序,第二种是采用Key,value方式更为保险安全,第一种可读性更为好点。
分类:
geotools
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!