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方式更为保险安全,第一种可读性更为好点。
转载自:https://blog.csdn.net/weixin_40184249/article/details/84480652