参考文章:
java geotools 坐标转换
Maven中GeoTools的引入 - Maven 的 repository 与 mirror的关系
使用geotools 对WKT字符串进行坐标系的转换。pom包引入
代码实现osgeo OSGeo Release Repository https://repo.osgeo.org/repository/release/ false true osgeo-snapshot OSGeo Snapshot Repository https://repo.osgeo.org/repository/snapshot/ true false org.geotools gt-epsg-hsql 20.0 org.geotools gt-referencing 20.0 org.geotools gt-api 20.0
public static Geometry geometryTransform2(Geometry geom, int sourceEPSGCode,int targetEPSGCode ){
try{
//CoordinateReferenceSystem的生成方法有两种,EPSG和WKT,然而,我发现把我需要的坐标系的prj文件中的内容用来转换会报“不存在。。。。什么这样的。。”
//所以采用EPSG,即使使用了EPSG,导出的转换后的投影文件的prj仍然不对,arcgis 无法识别。当然,同一个坐标系下的prj 文件的内容是相同的,用别的替换即可。
CoordinateReferenceSystem crsresource = CRS.decode("EPSG:"+ epsgCode);
CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:"+ targetEPSGCode);
// 投影转换
MathTransform transform = CRS.findMathTransform(crsresource, crsTarget,true);
String wktString = geom.toString();
log.debug("转换前的WKT字符串:" + wktString);
//将WKTString中的坐标进行正则匹配,投影转换后再将字符串中对应的坐标给替换了
Pattern pattern = compile("[1-9]\d*\.?\d*\s[1-9]\d*\.?\d*");
Matcher matcher = pattern.matcher(wktString);
while (matcher.find()){
String cordStr = matcher.group();
String[] cord = cordStr.split("\s+");
double x= Double.parseDouble(cord[0]);
double y= Double.parseDouble(cord[1]);
//使用coordinate时,产生的结果dest中的x坐标的位数是科学计数,所以不建议采用
String point="POINT(" + y + " " + x + ")";
Geometry pointGeom = reader.read(point);
Geometry resGeom = JTS.transform(pointGeom, transform);
String[] str = resGeom.toString().substring(resGeom.toString().lastIndexOf("(")+1, resGeom.toString().length() - 1).split("\s+");
String cordStr2 = str[1]+" "+str[0];
wktString = wktString.replaceAll(cordStr,cordStr2);
}
log.debug("转换后的WKT字符串:" + wktString);
Geometry read = reader.read(wktString);
return read;
} catch (Exception e) {
log.debug("坐标系转换出错:" + e.getMessage());
return null;
}
}
测试
public static void main(String[] args) {
String wktStr = "POLYGON((40535321.97750524 3276858.489317663,40534838.475054964 3276742.437636584,40534885.506722644 3276050.3168770154,40535410.02098725 3276621.3582205614,40535321.97750524 3276858.489317663))";
Geometry geometry = reader.read(wktStr);
Geometry targetGeometry = WKTUtil.geometryTransform2(geometry,4528,4326);
System.out.println(targetGeometry.toString());
}



