我們在操作矢量數據的無法避免的是與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方式更為保險安全,第一種可讀性更為好點。
