目录
一、引言
本文讲解了如何读取shp数据,如何新建shp数据,并将新建的shp数据返回到客户端进行显示。
二、代码操作
1、服务端
list对象是为了最后将新建的shp数据返回,pointgbk数据是源文件,pointgbkbuffer是新建文件。
@RequestMapping("/buffer")
@ResponseBody
public Object buffer()
{
List<Map<String,Object>>list=new ArrayList<>();
long start = System.currentTimeMillis();
String shpfile = this.getClass().getResource("/").getFile()+"file/pointgbk.shp";
String buffile = this.getClass().getResource("/").getFile()+"file/pointgbkbuffer.shp";
try{
//读取shp文件
File file = new File(shpfile);
ShapefileDataStore shpDataStore = null;
shpDataStore = new ShapefileDataStore(file.toURL());
//设置编码
Charset charset = Charset.forName("GBK");
shpDataStore.setCharset(charset);
String typeName = shpDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = null;
featureSource = shpDataStore.getFeatureSource (typeName);
SimpleFeatureCollection result = featureSource.getFeatures();
SimpleFeatureIterator itertor = result.features();
//创建shape文件对象
File fileBuf = new File(buffile);
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put( ShapefileDataStoreFactory.URLP.key, fileBuf.toURI().toURL() );
ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
//获取原shp文件字段名
SimpleFeatureType sft = featureSource.getSchema();
List<AttributeDescriptor> attrs = sft.getAttributeDescriptors();
//定义图形信息和属性信息
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
//tb.setCRS(DefaultGeographicCRS.WGS84);
tb.setName("shapefile");
for(int i=0;i<attrs.size();i++){
AttributeDescriptor attr = attrs.get(i);
String fieldName = attr.getName().toString();
if(fieldName=="the_geom"){
tb.add(fieldName, Polygon.class);
}
else{
tb.add(fieldName, String.class);
}
}
ds.createSchema(tb.buildFeatureType());
//设置编码
ds.setCharset(charset);
//设置Writer,遍历原feature,添加到新feature
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());
//Object temp=feature.getAttribute("the_geom");