在GeoTools中如何将Geometry作为要素源添加到图层?
嘿,我刚好做过类似的需求,其实核心就是把你的Geometry包装成GeoTools的Feature,再构建成可加载的要素源,和加载shp的流程本质是通的,给你一步步拆解:
具体实现步骤
1. 先把WKT/GeoJSON转成GeoTools的Geometry对象
不管你手里是WKT还是GeoJSON,都得先转成GeoTools依赖的JTS Geometry对象:
- 从WKT转换:用
WKTReader就行,代码示例:
import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.io.WKTReader; // 替换成你实际的WKT字符串 String wktStr = "POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))"; WKTReader wktReader = new WKTReader(); Geometry geometry = wktReader.read(wktStr);
- 从GeoJSON转换:用GeoTools的
GeometryJSON工具,记得引入相关依赖,代码示例:
import org.geotools.geojson.geom.GeometryJSON; import org.locationtech.jts.geom.Geometry; import java.io.StringReader; // 替换成你实际的GeoJSON字符串 String geoJsonStr = "{\"type\":\"Polygon\",\"coordinates\":[[[0,0],[10,0],[10,10],[0,10],[0,0]]]}"; GeometryJSON geoJsonReader = new GeometryJSON(); Geometry geometry = geoJsonReader.read(new StringReader(geoJsonStr));
2. 定义FeatureType(要素的结构模板)
GeoTools的Feature需要对应的类型定义,哪怕只有几何属性也得先创建:
import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.opengis.feature.simple.SimpleFeatureType; SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("CustomGeometryLayer"); // 图层的内部标识名 // 设置坐标系,比如常用的WGS84(EPSG:4326)或墨卡托(EPSG:3857),要和你的Geometry坐标系一致 typeBuilder.setCRS(org.geotools.referencing.CRS.decode("EPSG:4326")); typeBuilder.add("geom", Geometry.class); // 几何属性的名称,后面要对应上 SimpleFeatureType featureType = typeBuilder.buildFeatureType();
3. 把Geometry包装成Feature
用刚才的FeatureType创建单个Feature,相当于把几何数据变成可被GeoTools识别的要素:
import org.geotools.feature.simple.SimpleFeatureBuilder; import org.opengis.feature.simple.SimpleFeature; SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); featureBuilder.set("geom", geometry); // 属性名要和上面FeatureType里的一致 // 给要素生成一个唯一ID,随便编一个就行,比如"custom-feature-1" SimpleFeature feature = featureBuilder.buildFeature("custom-feature-1");
4. 构建要素集并创建图层加载到内容面板
把Feature放到要素集合里,再转成可加载的图层,最后添加到内容面板(这步和你加载shp的操作几乎一样):
import org.geotools.data.collection.DefaultFeatureCollection; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.styling.SLD; import org.geotools.styling.Style; // 创建要素集合,把刚才的Feature加进去,如果有多个Geometry就循环添加 DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal-id", featureType); featureCollection.add(feature); // 创建默认样式,也可以自定义样式(比如改颜色、线宽) Style layerStyle = SLD.createSimpleStyle(featureType); // 创建图层并设置显示名称 Layer customLayer = new FeatureLayer(featureCollection, layerStyle); customLayer.setTitle("我的自定义几何图层"); // 这个名称会显示在内容面板里 // 把图层添加到你的MapContent(和加载shp时的逻辑一致) // 假设你已经有MapContent对象: // MapContent mapContent = new MapContent(); mapContent.addLayer(customLayer);
几个关键注意点
- 一定要保证Geometry的坐标系和FeatureType设置的CRS一致,不然可能出现图层显示偏移甚至不显示的问题;
- 如果要添加多个Geometry,只需要循环创建Feature并加到
DefaultFeatureCollection里就行; - 自定义样式的话,可以参考GeoTools的SLD相关API,比如
SLD.setLineColor、SLD.setFillColor来修改图层样式。
内容的提问来源于stack exchange,提问作者leomessi
相关产品推荐
相关产品推荐

