//坐标转换(基于矢量 Geometry)
Geometry transformGeometryCRS(Geometry srcGeom,String srcEpsgId,String dstEpsgId){
try{
CoordinateReferenceSystem srcCRS = CRS.decode(srcEpsgId);
CoordinateReferenceSystem dstCRS = CRS.decode(dstEpsgId);
Geometry geom = FeatureUtils.transformGeometryCRS(srcGeom,srcCRS,dstCRS);
return geom;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 坐标转换
* @return
*/
public static Geometry transformGeometryCRS(Geometry srcGeom, CoordinateReferenceSystem srcCRS ,CoordinateReferenceSystem dstCRS){
try{
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform( srcCRS, dstCRS,lenient);
Geometry newGeom = JTS.transform(srcGeom, transform);
return newGeom;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 坐标转换
* @return
*/
public static boolean transformFile(String shpFile,String epsgId,String dstFile){
try{
CoordinateReferenceSystem dstCRS = CRS.decode(epsgId);
//打开shp文件
File file = new File (shpFile);
ShapefileDataStore featureSource = new ShapefileDataStore(file.toURL());
CoordinateReferenceSystem srcCRS = featureSource.getSchema().getCoordinateReferenceSystem();
SimpleFeatureType featureType = featureSource.getSchema();
SimpleFeatureTypeImpl typeImpl = (SimpleFeatureTypeImpl)featureType;
//创建新的shapefile
File newFile = new File(dstFile);
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);
SimpleFeatureType newType = SimpleFeatureTypeBuilder.retype(featureType,dstCRS);
newDataStore.createSchema(newType);
//处理单个要素
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource newFeatureSource = newDataStore.getFeatureSource(typeName);
Transaction transaction = new DefaultTransaction("Reproject");
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = newDataStore.getFeatureWriter(newDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);
SimpleFeatureIterator iter = featureSource.getFeatureSource().getFeatures().features();
while(iter.hasNext()){
SimpleFeature feature = (SimpleFeature) iter.next();
SimpleFeature newFeature = writer.next();
newFeature.setAttributes(feature.getAttributes());
Geometry geometry = (Geometry) feature.getDefaultGeometry();
Geometry newGeom = FeatureUtils.transformGeometryCRS(geometry,srcCRS,dstCRS);
newFeature.setDefaultGeometry(newGeom);
}
writer.write();
writer.close();
iter.close();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}