简要说明
在java,使用gdal ,使用裁剪范围的geojson 对 目标shpfile 进行裁剪,裁剪结果为一份新的shpfile;前置条件是geojson的坐标系和 shpfile 的坐标系一致,不然裁剪结果可能为空。
maven依赖
<!--需要安装完gdal后,本地install gdal包才能使用 --><!--gdal安装可参考 https://blog.csdn.net/qq_41613913/article/details/135743562 --><dependency><groupId>org.gdal</groupId><artifactId>gdal</artifactId><version>3.7.3</version></dependency>
样例代码
public static void main(String[] args) {String geojsonStr = "your geojson";if(StringUtils.isEmpty(geojsonStr )) {System.out.println("geojson 字符串为空");return;}JSONObject jsonObject = JSONUtil.parseObj(overlayRange);String features = jsonObject.getStr("features");//将geoJson转成Geometry集合对象Geometry geometry = ogr.CreateGeometryFromJson(JsonUtil.toJsonString(JsonUtil.jsonStringToList(features).get(0).get("geometry")));//临时的裁剪结果目录String clippingParentDirFileStr = "D:/tmp/clipping" + File.separator ;DataSource originalDataSource = null;try {File clippingParentDir = new File(clippingParentDirFileStr);if (!clippingParentDir.exists()) {clippingParentDir.mkdirs();}//打开数据org.gdal.ogr.Driver shpDriver = ogr.GetDriverByName("ESRI Shapefile");//被裁剪shp文件String originalFilePath = "D:/data/shp/xxxx.shp";originalDataSource = shpDriver.Open(originalFilePath, 0);//通过hutools工具获取文件名String originalName = FileUtil.getName(originalFilePath);String layerName = originalName.replace(".shp", "");//拿到图层Layer originalLayer = originalDataSource.GetLayer(layerName);//结果图层文件String outputFilePath = clippingParentDirFileStr + "output.shp";DataSource outDataSource = shpDriver.CreateDataSource(outputFileStr);//设置坐标系String originalSrid = originalLayer.GetSpatialRef().GetAttrValue("AUTHORITY", 1);if("0".equals(originalSrid)) {System.out.println("源文件不存在坐标系");return;}SpatialReference sr = new SpatialReference();sr.ImportFromEPSG(Integer.valueOf(originalSrid));Layer outlayer = outDataSource.CreateLayer("output", sr);//设置字段FeatureDefn originalfeatureDefn = originalLayer.GetLayerDefn();int fieldCount = originalfeatureDefn.GetFieldCount();for (int i = 0; i < fieldCount; i++) {FieldDefn defn = originalfeatureDefn.GetFieldDefn(i);outlayer.CreateField(defn);}//根据相交结果进行裁剪long featureCount = originalLayer.GetFeatureCount();Feature feature2 = null;for (int i = 0; i < featureCount ;i++) {feature2 = originalLayer.GetFeature(i);Geometry geometry2 = feature2.GetGeometryRef();if (geometry.Intersect(geometry2)) {Geometry intersection = geometry.Intersection(geometry2);feature2.SetGeometry(intersection);outlayer.CreateFeature(feature2);}}outlayer.delete();outDataSource.delete();shpDriver.delete();originalDataSource.delete();} catch (Exception e) {e.printStackTrace();}}