首页 > 解决方案 > 使用 geotools 将具有 srs 属性的 gml 片段转换为 wkt

问题描述

我有以下 gml 片段:

      <gml:LineString srsName="EPSG:25832"><gml:coordinates>663957.75944074022118,5103981.64908889029175 663955.915655555087142,5103991.151674075052142</gml:coordinates></gml:LineString>

我想用 EPSG:4326 srs 将它转换为 wkt 字符串。

标签: geotoolswktgml-geographic-markup-lan

解决方案


我找到了一个 hacky 解决方案,主要问题是输入只是一个 gml 片段而不是有效文档。所以不可能使用 xpath 来提取 srsName 属性,因为没有绑定命名空间。
我使用正则表达式搜索 srsName 属性并转换了几何图形。

try {                                                                                
    String gml = "<gml:LineString srsName=\"EPSG:25832\"><gml:coordinates>663957.75944074022118,5103981.64908889029175 663955.915655555087142,5103991.151674075052142</gml:coordinates></gml:LineString>";                                              
    Geometry geometry = gmlReader.read(gml, geometryFactory);                        
    Pattern p = Pattern.compile("srsName=\\\"([^\"]*)\\\"");                         
    Matcher m = p.matcher(gml);                                                      
    if (m.find()) {                                                                  
        String srs = m.group(1);                                                     
        CoordinateReferenceSystem crsSource = CRS.decode(srs);                       
        GeographicCRS crsTarget =                                                    
                org.geotools.referencing.crs.DefaultGeographicCRS.WGS84;             
        MathTransform transform = CRS.findMathTransform(crsSource, crsTarget, false);
        geometry = JTS.transform(geometry, transform);                               
    }                                                                                 
    String wktString = wktWriter.write(geometry);                                         
} catch (Exception e) {                                                              
    throw new RuntimeException(e);                                                   
}                                                                                    

丑得要死,有没有更干净的办法?


推荐阅读