目录
在GIS开发中,前端地图通常使用地理坐标,而后端在计算几何面积等操作时,需要使用投影坐标。这过程中则需要进行坐标转换。下面带来了一个Java基于geotools开发的坐标转换工具类,支持点、线、面等几何图形进行地理坐标与投影坐标间相互转换。
一、转换效果
下图是使用工具类进行地理坐标转投影坐标、投影坐标转地理坐标、带号投影坐标与无带号投影坐标间转换的示例效果。
转换效果
二、实现过程
为便于使用,定义了通用的几何坐标系转换方法coordinateTransform(Geometry sourceGeometry,int targetSrid),传入源几何对象和目标坐标sird即可。
1.固定坐标系轴方向
通过下面代码固定坐标系轴方向,如果不对坐标系轴方向进行固定,则会使不同运行环境的坐标系xy方向不同,进而可能出现本地开发时坐标转换正常,但是部署到服务器后坐标转换结果异常的谜之bug。
CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);
2.创建转换坐标系
通过下面代码创建源坐标系和目标坐标系,这里从传递进来的源几何参数(Geometry sourceGeometry)中获取源坐标系srid(srid指空间参照标识符,每个坐标系定义均有一个唯一的标识,通常为4位整数值)。
CoordinateReferenceSystem source = factory.createCoordinateReferenceSystem("EPSG:" + sourceGeometry.getSRID());
CoordinateReferenceSystem target = factory.createCoordinateReferenceSystem("EPSG:" + targetSrid);
3.建立坐标转换
MathTransform transform = CRS.findMathTransform(source, target,true);
4.进行坐标转换
Geometry res = JTS.transform(sourceGeometry, transform);
5.完整坐标转换方法代码
public static Geometry coordinateTransform(Geometry sourceGeometry,int targetSrid){
if (sourceGeometry == null || sourceGeometry.getSRID() == 0 || targetSrid == 0){
return null;
}
try {
CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);
CoordinateReferenceSystem source = factory.createCoordinateReferenceSystem("EPSG:" + sourceGeometry.getSRID());
CoordinateReferenceSystem target = factory.createCoordinateReferenceSystem("EPSG:" + targetSrid);
MathTransform transform = CRS.findMathTransform(source, target,true);
Geometry res = JTS.transform(sourceGeometry, transform);
if (res != null){
res.setSRID(targetSrid);
}
return res;
}catch (FactoryException | TransformException e){
e.printStackTrace();
}
return null;
}
三、工具类使用
1.创建几何对象
这里使用wkt格式几何坐标串进行示例演示坐标转换,这里写一个wkt转几何对象的通用方法createGeometry(String wkt,int srid),传入wkt和坐标系srid即可,实现代码如下
public static Geometry createGeometry(String wkt,int srid){
if (StringUtil.isEmpty(wkt)){
return null;
}
try {
WKTReader reader = new WKTReader();
Geometry geometry = reader.read(wkt);
geometry.setSRID(srid);
return geometry;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
2.坐标转换示例
public static void main(String[] args) throws IOException{
String wkt = "POINT (106.61 25.32)";
Geometry source = createGeometry(wkt,4490);
Geometry res = coordinateTransform(source, 4524);
int x = 1;
}
使用示例代码
转换结果