GeoTools WKT座標系轉換
阿新 • • 發佈:2022-12-06
背景
使用geotools 對WKT字串進行座標系的轉換。
pom包引入
<repositories>
<repository>
<id>osgeo</id>
<name>OSGeo Release Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
<snapshots><enabled>false</enabled></snapshots>
<releases><enabled>true</enabled></releases>
</repository>
<repository>
<id>osgeo-snapshot</id>
<name>OSGeo Snapshot Repository</name>
<url>https://repo.osgeo.org/repository/snapshot/</url>
<snapshots><enabled>true</enabled></snapshots>
<releases><enabled>false</enabled></releases>
</repository>
</repositories>
<!-- gt-epsg-hsql 這個是epsgcode的,一定要引入,不然會出現座標系找不到的問題-->
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>20.0</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-referencing</artifactId>
<version>20.0</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-api</artifactId>
<version>20.0</version>
</dependency>
程式碼實現
/**
* 單個geom轉換
* geotools的安裝包中的x,y座標是反著的,因此,直接用geomtry轉換,匯出的資料是錯誤,先的將
* x,y的座標換過來。所以,我選擇拼裝geomtry。
* @param geom
* @return
*/
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座標的位數是科學計數,所以不建議採用
/*Coordinate source = new Coordinate(y, x);
Coordinate dest = new Coordinate();
JTS.transform(source,dest, transform);
String[] str = dest.toString().substring(1, dest.toString().length() - 1).split(",");*/
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