浏览代码

spatialite数据库相关操作以及提交了几个接口

wanger 3 月之前
父节点
当前提交
5f37de4ed1
共有 18 个文件被更改,包括 1373 次插入16 次删除
  1. 2 2
      onemap-modules/onemap-file/src/main/java/com/onemap/file/utils/UnPackageUtils.java
  2. 144 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/controller/DataController.java
  3. 26 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/DataService.java
  4. 309 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/impl/DataImp.java
  5. 13 12
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/impl/SQLiteImp.java
  6. 12 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/CustomUtils.java
  7. 52 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/GeoServerSpatialiteJDBC.java
  8. 121 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/GeoToolsSpatialOverlay.java
  9. 24 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/LoadShapefile.java
  10. 35 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/OverlayAnalysis.java
  11. 150 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileOverlayAnalysis.java
  12. 63 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileToGeoPackage.java
  13. 96 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileToSpatiaLiteWithProjection.java
  14. 159 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShpToSpatiaLite.java
  15. 56 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/SpatialiteSample.java
  16. 22 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/SpatialiteUtils.java
  17. 81 0
      onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/UnPackageUtils.java
  18. 8 2
      onemap-modules/onemap-overlap/src/main/resources/application.yml

+ 2 - 2
onemap-modules/onemap-file/src/main/java/com/onemap/file/utils/UnPackageUtils.java

@@ -8,8 +8,8 @@ import java.io.File;
 import java.io.FileOutputStream;
 
 /**
- * @author : wangping
- * @createDate: 2021/7/12
+ * @author : wanger
+ * @createDate: 2024/12/19
  * @description:解压缩工具
  **/
 

+ 144 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/controller/DataController.java

@@ -0,0 +1,144 @@
+package com.onemap.overlap.controller;
+
+import cn.hutool.json.JSONObject;
+import com.onemap.common.core.web.domain.RequestResult;
+import com.onemap.overlap.service.DataService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@RestController
+@RequestMapping("/data")
+public class DataController {
+
+    @Autowired
+    private DataService dataService;
+
+    /**
+     * 导入数据 file/path 二选一 入库到spatialite
+     *
+     * @param file 前端传入的zip压缩包
+     * @param path 前端选择的shp文件的位置
+     * @return
+     */
+    @PostMapping("/import")
+    public RequestResult importIn(MultipartFile file, String path, String type, String name) {
+        try {
+            return dataService.importIn(file, path, type, name);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 查询模型列表
+     *
+     * @return
+     */
+    @RequestMapping("/modellist")
+    public RequestResult modellist() {
+        try {
+            return dataService.modellist();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 查询模型列表
+     *
+     * @return
+     */
+    @RequestMapping("/modeldetails")
+    public RequestResult modeldetails(String modelname) {
+        try {
+            return dataService.modeldetails(modelname);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 删除分析模型
+     *
+     * @return
+     */
+    @RequestMapping("/modeldelete")
+    public RequestResult modeldelete(String modelname) {
+        try {
+            return dataService.modeldelete(modelname);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 修改或新增模型
+     *
+     * @return
+     */
+    @RequestMapping("/modelupdate")
+    public RequestResult modelupdate(HttpServletRequest request, HttpServletResponse response) {
+        try {
+            return dataService.modelupdate(request);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 查询所有管控数据
+     *
+     * @return
+     */
+    @RequestMapping("/basevector")
+    public RequestResult basevector() {
+        try {
+            return dataService.basevector();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 删除指定管控数据
+     *
+     * @return
+     */
+    @RequestMapping("/basevectordelete")
+    public RequestResult basevectordelete(String tablename) {
+        try {
+            return dataService.basevectordelete(tablename);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+
+    /**
+     * 查询所有分析图斑数据列表
+     *
+     * @return
+     */
+    @RequestMapping("/analysevector")
+    public RequestResult analysevector() {
+        try {
+            return dataService.analysevector();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return RequestResult.error("失败", null);
+        }
+    }
+}

+ 26 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/DataService.java

@@ -0,0 +1,26 @@
+package com.onemap.overlap.service;
+
+import com.onemap.common.core.web.domain.RequestResult;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
+public interface DataService {
+
+    RequestResult importIn(MultipartFile file, String path, String type, String name);
+
+    RequestResult modellist();
+
+    RequestResult modeldetails(String modelname);
+
+    RequestResult basevector();
+
+    RequestResult analysevector();
+
+    RequestResult modeldelete(String modelname);
+
+    RequestResult modelupdate(HttpServletRequest request);
+
+    RequestResult basevectordelete(String tablename);
+}

+ 309 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/impl/DataImp.java

@@ -0,0 +1,309 @@
+package com.onemap.overlap.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.onemap.common.core.utils.StringUtils;
+import com.onemap.common.core.web.domain.RequestResult;
+import com.onemap.common.security.utils.SecurityUtils;
+import com.onemap.overlap.service.DataService;
+import com.onemap.overlap.utils.CustomUtils;
+import com.onemap.overlap.utils.ShpToSpatiaLite;
+import com.onemap.overlap.utils.SpatialiteUtils;
+import com.onemap.overlap.utils.UnPackageUtils;
+import org.apache.poi.xwpf.usermodel.BreakType;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class DataImp implements DataService {
+    @Value("${file.temp}")
+    String localFilePath;
+    @Value("${file.wkid}")
+    Integer shpWkid;
+    @Value("${spatialite.filepath}")
+    String dbpath;
+    @Value("${file.prefix}")
+    String prefix;
+
+    @Override
+    public RequestResult importIn(MultipartFile file, String path, String type, String name) {
+        if (file == null && path == null) {
+            return RequestResult.error("参数未传递", null);
+        }
+        String currentTime = CustomUtils.getCurrentTime();
+        String currentPath = localFilePath + "/" + currentTime + "/";
+        String username = SecurityUtils.getUsername();
+        if (StringUtils.isEmpty(username)) {
+            username = "admin";
+        }
+        String shpPath = path;
+        if (StringUtils.isEmpty(shpPath)) {
+            String fileName = file.getOriginalFilename();
+            String filetype = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
+            String filename = fileName.replace(filetype, "").replace(".", "");
+            if (!filetype.equals("zip") && !filetype.equals("rar")) {
+                return RequestResult.error("请上传zip/rar压缩包文件", null);
+            }
+            String filepath = currentPath + "" + fileName;
+            File dest = new File(filepath);
+            File dir = dest.getParentFile();
+            if (!dir.exists()) {
+                dir.mkdirs();
+            }
+            String unzippath = currentPath;
+            try {
+                //上传文件
+                file.transferTo(dest);
+                //解压zip格式
+                if (filetype.equals("zip")) {
+                    new UnPackageUtils().unPackZip(dest, unzippath);
+                } else {
+                    //解压rar格式
+                    new UnPackageUtils().unPackRar(dest, unzippath);
+                }
+                File[] files = new File(unzippath).listFiles();
+                for (File file1 : files) {
+                    if (file1.getAbsolutePath().substring(file1.getAbsolutePath().lastIndexOf(".") + 1).equals("shp")) {
+                        shpPath = file1.getAbsolutePath();
+                        shpPath = shpPath.replaceAll("\\\\", "/");
+                        break;
+                    }
+                }
+                if (!"".equals(shpPath)) {
+
+                } else {
+                    return RequestResult.error("未检索到shp文件");
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+                return RequestResult.error(e.getMessage());
+            }
+        }
+        String tablename = "";
+        String folderpath = "";
+        if (StringUtils.isEmpty(shpPath)) {
+            return RequestResult.error("未检索到shp文件!");
+        } else {
+            // 创建File对象
+            File currentfile = new File(shpPath);
+            // 获取文件名
+            String fileName = currentfile.getName();
+            folderpath = currentfile.getParentFile().getAbsolutePath();
+            String filetype = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
+            String filename = fileName.replace(filetype, "").replace(".", "");
+            tablename = prefix + filename + "_" + currentTime;
+            try {
+                Boolean bool = ShpToSpatiaLite.ImportShpToSpatialite(dbpath, shpPath, shpWkid, tablename);
+                if (!bool) {
+                    return RequestResult.error("shp数据入库失败!");
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            //注册数据到属性表
+            String insertSQL = "";
+            if ("base".equals(type)) {//管控数据
+                insertSQL = "insert into t_base_vector (layername , tablename) values ('" + name + "', '" + tablename + "')";
+            } else if ("analyse".equals(type)) {//分析图斑
+                insertSQL = "insert into t_analyse_vector (layername , tablename, path) values ('" + name + "', '" + tablename + "', '" + folderpath + "')";
+            }
+            statement.execute(insertSQL);
+            connection.close();
+        } catch (Exception w) {
+            w.printStackTrace();
+        }
+        return RequestResult.success("上传成功", tablename);
+    }
+
+    @Override
+    public RequestResult modellist() {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String querySQL = "select distinct(modelname) from t_model";
+            ResultSet resultSet = statement.executeQuery(querySQL);
+            List<String> res = new ArrayList<String>();
+            while (resultSet.next()) {
+                String name = resultSet.getString("modelname");
+                res.add(name);
+            }
+            connection.close();
+            return RequestResult.success("查询成功!", res);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("查询失败!", null);
+    }
+
+    /**
+     * 查询模型详情
+     *
+     * @param modelname
+     * @return
+     */
+    @Override
+    public RequestResult modeldetails(String modelname) {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String querySQL = "select layername,type,isvalid from t_model where modelname = '" + modelname + "'";
+            ResultSet resultSet = statement.executeQuery(querySQL);
+            List<Map> res = new ArrayList<Map>();
+            while (resultSet.next()) {
+                Map cur = new HashMap();
+                cur.put("layername", resultSet.getString("layername"));
+                cur.put("type", resultSet.getString("type"));
+                cur.put("isvalid", resultSet.getString("isvalid"));
+                res.add(cur);
+            }
+            connection.close();
+            return RequestResult.success("查询成功!", res);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("查询失败!", null);
+    }
+
+    /**
+     * 查询模型详情
+     *
+     * @param modelname
+     * @return
+     */
+    @Override
+    public RequestResult modeldelete(String modelname) {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String querySQL = "delete from t_model where modelname = '" + modelname + "'";
+            statement.execute(querySQL);
+            connection.close();
+            return RequestResult.success("删除成功!", 1);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("删除失败!", null);
+    }
+
+    @Override
+    public RequestResult modelupdate(HttpServletRequest request) {
+        try {
+            JSONObject parameters = (JSONObject) new JSONParser().parse(request.getReader());
+            String modelname = (String) parameters.get("modelname");
+            JSONArray details = (JSONArray) parameters.get("details");
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String deleteSQL = "delete from t_model where modelname = '" + modelname + "'";
+            statement.execute(deleteSQL);
+            for(int i = 0 ; i < details.size() ; i ++){
+                JSONObject curObj = (JSONObject) details.get(i);
+                String layername = (String) curObj.get("layername");
+                String isvalid = (String) curObj.get("isvalid");
+                String type = (String) curObj.get("type");
+                String insertSQL = "insert into t_model (layername , type, \"index\" , isvalid, modelname) values ('" + layername + "' , '" + type + "', " + i + " , '" + isvalid + "', '" + modelname + "')";
+                statement.execute(insertSQL);
+            }
+            connection.close();
+            return RequestResult.success("修改成功!", 1);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("失败!", null);
+    }
+
+    @Override
+    public RequestResult basevectordelete(String tablename) {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            //删除主表
+            String deleteSQL = "delete from t_base_vector where tablename = '" + tablename + "'";
+            statement.execute(deleteSQL);
+            //删除模型分析因子项
+            deleteSQL = "delete from t_model where layername = (select layername from t_base_vector where tablename = '" + tablename + "')";
+            statement.execute(deleteSQL);
+            //删除矢量表
+            deleteSQL = "drop table " + tablename + "";
+            statement.execute(deleteSQL);
+//            deleteSQL = "drop table idx_" + tablename + "_geom";
+//            statement.execute(deleteSQL);
+            deleteSQL = "delete from geometry_columns where f_table_name = '" + tablename + "'";
+            statement.execute(deleteSQL);
+            connection.close();
+            return RequestResult.success("删除成功!", 1);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("失败!", null);
+    }
+
+    @Override
+    public RequestResult basevector() {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String querySQL = "select * from t_base_vector";
+            ResultSet resultSet = statement.executeQuery(querySQL);
+            List<Map> res = new ArrayList<Map>();
+            while (resultSet.next()) {
+                Map cur = new HashMap();
+                cur.put("id", resultSet.getString("id"));
+                cur.put("layername", resultSet.getString("layername"));
+                cur.put("tablename", resultSet.getString("tablename"));
+                cur.put("serviceuri", resultSet.getString("serviceuri"));
+                cur.put("servicetype", resultSet.getString("servicetype"));
+                res.add(cur);
+            }
+            connection.close();
+            return RequestResult.success("查询成功!", res);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("查询失败!", null);
+    }
+
+    @Override
+    public RequestResult analysevector() {
+        try {
+            Connection connection = SpatialiteUtils.getSpatialiteConnection(dbpath);
+            Statement statement = connection.createStatement();
+            String querySQL = "select * from t_analyse_vector order by inserttime desc";
+            ResultSet resultSet = statement.executeQuery(querySQL);
+            List<Map> res = new ArrayList<Map>();
+            while (resultSet.next()) {
+                Map cur = new HashMap();
+                cur.put("id", resultSet.getString("id"));
+                cur.put("layername", resultSet.getString("layername"));
+                cur.put("tablename", resultSet.getString("tablename"));
+                cur.put("inserttime", resultSet.getString("inserttime"));
+                res.add(cur);
+            }
+            connection.close();
+            return RequestResult.success("查询成功!", res);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return RequestResult.error("查询失败!", null);
+    }
+
+
+}

+ 13 - 12
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/service/impl/SQLiteImp.java

@@ -53,22 +53,24 @@ public class SQLiteImp implements SQLiteService {
                 String layerName = resultSet.getString("图层名");
                 String type = resultSet.getString("合法方式");
                 String isValid = resultSet.getString("有效性");
-                if(isValid.equals("有效")){
-                    if(type.equals("外部")){
-                        String updateOutside = String.format("update 当前检查图斑 as c set 合法性说明 = case when 合法性说明 is null then '' else 合法性说明 || ';' end || '疑似%s内建设',面积 = case when 面积 is null then '' else 面积 end || ST_Area(ST_Intersection(c.geom,d.geom)) || ';' from %s d, idx_当前检查图斑_geom a, %s b where (a.xmax >= b.xmin  and a.xmin <= b.xmax and a.ymax >= b.ymin and a.ymin <= b.ymax) and (a.rowid = c.rowid  and b.rowid = d.rowid) and intersects(c.geom, d.geom) and st_intersection(c.geom,d.geom)  is not null;",layerName ,layerName,"idx_"+layerName+"_geom");
-                        //statement.addBatch(updateOutside);
-                        //Boolean resultUpdateOverlap = statement.execute(update);
+                if (isValid.equals("有效")) {
+                    if (type.equals("外部")) {
+                        String updateOutside = String.format("update 当前检查图斑 as c set " +
+                                "合法性说明 = case when 合法性说明 is null then '' else 合法性说明 || ';' end || '疑似%s内建设'," +
+                                "面积 = case when 面积 is null then '' else 面积 end || ST_Area(ST_Intersection(c.geom,d.geom)) || ';' " +
+                                "from %s d, idx_当前检查图斑_geom a, %s b " +
+                                "where intersects(c.geom, d.geom) and st_intersection(c.geom,d.geom)  is not null;", layerName, layerName, "idx_" + layerName + "_geom");
                         sqlOverlap.add(updateOutside);
-                    }
-                    if(type.equals("内部")){
-                        String updateInside = String.format("update 当前检查图斑 as c set 合法性说明 = case when 合法性说明 is null then '' else 合法性说明 || ';' end || '符合%s用地',面积 = case when 面积 is null then '' else 面积  end || ST_Area(ST_Intersection(c.geom,d.geom))|| ';' from %s d, idx_当前检查图斑_geom a, %s b where (a.xmax >= b.xmin  and a.xmin <= b.xmax and a.ymax >= b.ymin and a.ymin <= b.ymax) and (a.rowid = c.rowid  and b.rowid = d.rowid) and intersects(c.geom, d.geom) and st_within(c.geom, d.geom);",layerName ,layerName,"idx_"+layerName+"_geom");
-                        //statement.addBatch(updateInside);
-                        //Boolean resultUpdateOverlap = statement.execute(update);
+                    } else if (type.equals("内部")) {
+                        String updateInside = String.format("update 当前检查图斑 as c set " +
+                                "合法性说明 = case when 合法性说明 is null then '' else 合法性说明 || ';' end || '符合%s用地'," +
+                                "面积 = case when 面积 is null then '' else 面积  end || ST_Area(ST_Intersection(c.geom,d.geom))|| ';' " +
+                                "from %s d, idx_当前检查图斑_geom a, %s b where intersects(c.geom, d.geom) and st_within(c.geom, d.geom);", layerName, layerName, "idx_" + layerName + "_geom");
                         sqlOverlap.add(updateInside);
                     }
                 }
             }
-            for (String item : sqlOverlap){
+            for (String item : sqlOverlap) {
                 statement.addBatch(item);
             }
             String updateInlegal = "update 当前检查图斑  set 合法性判断 = '疑似违法'  where 合法性判断 is null and 合法性说明 like '%疑似%'";
@@ -100,6 +102,5 @@ public class SQLiteImp implements SQLiteService {
                 }
             }
         }
-
     }
 }

+ 12 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/CustomUtils.java

@@ -0,0 +1,12 @@
+package com.onemap.overlap.utils;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class CustomUtils {
+    public static String getCurrentTime() {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+        String currentTimeString = sdf.format(new Date());
+        return currentTimeString;
+    }
+}

+ 52 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/GeoServerSpatialiteJDBC.java

@@ -0,0 +1,52 @@
+//package com.onemap.overlap.utils;
+//
+//import java.sql.Connection;
+//import java.sql.DriverManager;
+//import java.sql.ResultSet;
+//import java.sql.Statement;
+//import java.sql.SQLException;
+//
+//public class GeoServerSpatialiteJDBC {
+//    public static void main(String[] args) {
+//        // 设置数据库路径(.sqlite 或 .spatialite)
+//        String jdbcUrl = "jdbc:sqlite:D:\\temp\\mappatchcheck.sqlite"; // SQLite 数据库路径
+//        String spatialiteJdbcUrl = jdbcUrl + "?load_extension=true";  // 启用 SpatiaLite 扩展
+//
+//        try {
+//            // 注册 SQLite JDBC 驱动
+//            Class.forName("org.sqlite.JDBC");/**/
+//
+//            // 创建数据库连接(启用 SpatiaLite 扩展)
+//            Connection conn = DriverManager.getConnection(jdbcUrl);
+//
+//            // 通过 SQL 语句加载 SpatiaLite 扩展
+//            Statement stmt = conn.createStatement();
+////            stmt.execute("SELECT load_extension('mod_spatialite')");
+//
+//            // 执行空间查询
+//            // 假设表名为 'my_table',字段 'geom' 是空间数据列
+//            String query = "SELECT id, name, AsText(geom) FROM wuchuan4525 WHERE ST_Within(geom, ST_GeomFromText('POLYGON((...))', 4326))";
+//            ResultSet rs = stmt.executeQuery(query);
+//
+//            // 处理查询结果
+//            while (rs.next()) {
+//                int id = rs.getInt("id");
+//                String name = rs.getString("name");
+//                String geom = rs.getString("AsText(geom)");
+//                System.out.println("ID: " + id + ", Name: " + name + ", Geometry: " + geom);
+//            }
+//
+//            // 关闭连接
+//            rs.close();
+//            stmt.close();
+//            conn.close();
+//
+//        } catch (ClassNotFoundException e) {
+//            System.out.println("SQLite JDBC Driver not found!");
+//            e.printStackTrace();
+//        } catch (SQLException e) {
+//            System.out.println("Database connection error!");
+//            e.printStackTrace();
+//        }
+//    }
+//}

+ 121 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/GeoToolsSpatialOverlay.java

@@ -0,0 +1,121 @@
+//package com.onemap.overlap.utils;
+//
+//import org.geotools.data.DataStore;
+//import org.geotools.data.DataStoreFinder;
+//import org.geotools.data.FeatureSource;
+//import org.geotools.data.Transaction;
+//import org.geotools.data.memory.MemoryDataStore;
+//import org.geotools.data.shapefile.ShapefileDataStore;
+//import org.geotools.data.shapefile.ShapefileDataStoreFactory;
+//import org.geotools.data.simple.SimpleFeatureCollection;
+//import org.geotools.data.simple.SimpleFeatureWriter;
+//import org.geotools.feature.FeatureCollection;
+//import org.geotools.feature.DefaultFeatureCollection;  // 引入 DefaultFeatureCollection
+//import org.geotools.feature.FeatureIterator;
+//import org.geotools.feature.simple.SimpleFeatureBuilder;
+//import org.geotools.feature.simple.SimpleFeatureTypeImpl;
+//import org.locationtech.jts.geom.Geometry;
+//import org.locationtech.jts.geom.GeometryFactory;
+//import org.opengis.feature.Feature;
+//import org.opengis.feature.simple.SimpleFeature;
+//import org.opengis.feature.simple.SimpleFeatureType;
+//
+//import java.io.File;
+//import java.util.HashMap;
+//import java.util.Iterator;
+//import java.util.Map;
+//
+//public class GeoToolsSpatialOverlay {
+//
+//    // 加载 Shapefile 文件并返回 FeatureCollection
+//    public static FeatureCollection loadShapefile(String shapefilePath) throws Exception {
+//        File file = new File(shapefilePath);
+//        ShapefileDataStore dataStore = new ShapefileDataStore(file.toURI().toURL());
+//        String typeName1 = dataStore.getTypeNames()[0];
+//        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource1 = dataStore.getFeatureSource(typeName1);
+//        FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = featureSource1.getFeatures();
+//
+//        // 将第一个 Shapefile 数据加载到内存
+//        MemoryDataStore memoryDataStore = new MemoryDataStore();
+//        memoryDataStore.addFeatures(featureCollection);
+////        memoryDataStore.setSpatialIndex(true);  // 启用空间索引(例如,R-tree)
+//
+//        return featureCollection;
+//    }
+//
+//    // 执行交集(Intersection)分析
+//    public static FeatureCollection performIntersection(FeatureCollection layer1, FeatureCollection layer2) throws Exception {
+//        // 使用 DefaultFeatureCollection 来存储交集结果
+//        FeatureCollection resultCollection = new DefaultFeatureCollection();
+//
+//        GeometryFactory geometryFactory = new GeometryFactory();
+//
+//        // 遍历第一个图层
+////        for (Feature feature : layer1) {
+////
+////        }
+//        FeatureIterator iterator1 = layer1.features();
+//        while (iterator1.hasNext()) {
+//            SimpleFeature feature1 = (SimpleFeature)iterator1.next();
+//            Geometry geom1 = (Geometry) feature1.getDefaultGeometry();
+//            // 遍历第二个图层
+//            FeatureIterator iterator2 = layer2.features();
+//            while (iterator2.hasNext()) {
+//                SimpleFeature simpleFeature2 = (SimpleFeature)iterator2.next();
+//                Geometry geom2 = (Geometry) simpleFeature2.getDefaultGeometry();
+//                // 如果两者有交集,计算交集
+//                if (geom1.intersects(geom2)) {
+//                    Geometry intersection = geom1.intersection(geom2);
+//                    // 将交集结果添加到新的 FeatureCollection
+//                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(feature1.getFeatureType());
+//                    SimpleFeature newFeature = featureBuilder.buildFeature(null);
+//                    newFeature.setAttribute("the_geom", intersection);
+//                    ((DefaultFeatureCollection) resultCollection).add(newFeature);
+//                }
+//            }
+//        }
+//
+//        return resultCollection;
+//    }
+//
+//    // 导出结果到新的 Shapefile 文件
+//    public static void exportToShapefile(FeatureCollection featureCollection, String outputShapefilePath) throws Exception {
+//        File outputFile = new File(outputShapefilePath);
+//        Map<String, Object> params = new HashMap<>();
+//        params.put(ShapefileDataStoreFactory.URLP.key, outputFile.toURI().toURL());
+//
+//        // 创建新的 Shapefile DataStore
+//        ShapefileDataStore dataStore = (ShapefileDataStore) DataStoreFinder.getDataStore(params);
+//
+//        // 获取 FeatureCollection 的 schema 并创建新的 Shapefile Schema
+//        SimpleFeatureTypeImpl featureType = (SimpleFeatureTypeImpl) featureCollection.getSchema();
+//        dataStore.createSchema(featureType);
+//
+//        // 写入新的 Shapefile
+//        try (SimpleFeatureWriter writer = (SimpleFeatureWriter) dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], Transaction.AUTO_COMMIT)) {
+//            for (int u = 0; u < featureCollection.size(); u++) {
+//                Feature feature = featureCollection.features().next();
+//                SimpleFeature simpleFeature = (SimpleFeature) feature;
+//                //for (SimpleFeature feature : featureCollection) {
+//                SimpleFeature newFeature = writer.next();
+//                newFeature.setAttributes(simpleFeature.getAttributes());
+//                writer.write();
+//            }
+//        }
+//    }
+//
+//    public static void main(String[] args) {
+//        try {
+//            // 加载两个输入的 Shapefile 文件
+//            FeatureCollection layer1 = loadShapefile("E:\\projects\\监测图斑审查上传\\图斑套合\\管控数据\\基本农田.shp");
+//            FeatureCollection layer2 = loadShapefile("D:\\temp\\wuchuan.shp");
+//            // 执行空间叠加分析,获取交集部分
+//            FeatureCollection result = performIntersection(layer1, layer2);
+//            // 导出交集结果到新的 Shapefile
+//            exportToShapefile(result, "D:\\temp\\temp.shp");
+//            System.out.println("空间叠加分析完成,结果已导出到新的 Shapefile。");
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//    }
+//}

+ 24 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/LoadShapefile.java

@@ -0,0 +1,24 @@
+//package com.onemap.overlap.utils;
+//
+//import org.geotools.data.DataStore;
+//import org.geotools.data.DataStoreFinder;
+//import org.geotools.data.shapefile.ShapefileDataStoreFactory;
+//import org.geotools.feature.FeatureCollection;
+//
+//import java.io.File;
+//import java.net.URL;
+//import java.util.HashMap;
+//import java.util.Map;
+//
+//public class LoadShapefile {
+//    public static FeatureCollection loadShapefile(String shapefilePath) throws Exception {
+//        File file = new File(shapefilePath);
+//        Map<String, Object> params = new HashMap<>();
+//        params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
+//
+//        DataStore dataStore = DataStoreFinder.getDataStore(params);
+//        String typeName = dataStore.getTypeNames()[0];  // 获取第一个图层
+//        FeatureCollection featureCollection = dataStore.getFeatureSource(typeName).getFeatures();
+//        return featureCollection;
+//    }
+//}

+ 35 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/OverlayAnalysis.java

@@ -0,0 +1,35 @@
+//package com.onemap.overlap.utils;
+//
+//import org.geotools.data.simple.SimpleFeatureCollection;
+//
+//import org.geotools.feature.FeatureCollection;
+//import org.locationtech.jts.geom.Geometry;
+//import org.opengis.feature.simple.SimpleFeature;
+//
+//public class OverlayAnalysis {
+//    public static FeatureCollection performIntersection(FeatureCollection layer1, FeatureCollection layer2) throws Exception {
+//        FeatureCollection resultCollection = new SimpleFeatureCollection(); // 用来存储结果的集合
+//
+//        // 遍历第一个图层中的每个要素
+//        for (SimpleFeature feature1 : (SimpleFeatureCollection) layer1) {
+//            Geometry geom1 = (Geometry) feature1.getDefaultGeometry();
+//
+//            // 遍历第二个图层中的每个要素
+//            for (SimpleFeature feature2 : (SimpleFeatureCollection) layer2) {
+//                Geometry geom2 = (Geometry) feature2.getDefaultGeometry();
+//
+//                // 求交集
+//                if (geom1.intersects(geom2)) {
+//                    Geometry intersection = geom1.intersection(geom2);
+//
+//                    // 创建新的要素并加入结果集合
+//                    SimpleFeature newFeature = feature1.clone();
+//                    newFeature.setAttribute("geometry", intersection);  // 设置新的几何属性
+//                    resultCollection.add(newFeature);
+//                }
+//            }
+//        }
+//
+//        return resultCollection;
+//    }
+//}

+ 150 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileOverlayAnalysis.java

@@ -0,0 +1,150 @@
+//package com.onemap.overlap.utils;
+//
+//import org.gdal.ogr.*;
+//import org.gdal.osr.SpatialReference;
+//import org.geotools.feature.FeatureCollection;
+//
+//import java.util.ArrayList;
+//import java.util.List;
+//
+//import static java.lang.Math.round;
+//
+//public class ShapefileOverlayAnalysis {
+//    public static void main(String[] args) {
+//        long startTime = System.currentTimeMillis();
+//        // 初始化 GDAL
+//        ogr.RegisterAll();
+//
+//        // 设置文件路径
+//        String shapefile1 = "D:\\temp\\wuchuan.shp";
+//        String shapefile2 = "E:\\projects\\监测图斑审查上传\\图斑套合\\管控数据\\基本农田.shp";
+//        String outputShapefile = "D:\\temp\\temp.shp";
+//
+//        // 读取 Shapefile 图层
+//        DataSource ds1 = ogr.Open(shapefile1);
+//        DataSource ds2 = ogr.Open(shapefile2);
+//
+//        if (ds1 == null || ds2 == null) {
+//            System.err.println("Failed to open one or both shapefiles.");
+//            return;
+//        }
+//
+//        // 获取第一个图层
+//        Layer layer1 = ds1.GetLayer(0);
+//        Layer layer2 = ds2.GetLayer(0);
+//
+//        Geometry mergedGeometry = null;
+//
+//        // 遍历输入图层中的所有要素,并合并它们的几何
+//        Feature inputFeature;
+//        layer1.ResetReading();
+//        while ((inputFeature = layer1.GetNextFeature()) != null) {
+//            Geometry featureGeometry = inputFeature.GetGeometryRef();
+//            if (mergedGeometry == null) {
+//                mergedGeometry = featureGeometry.Clone();  // 初始化合并几何
+//            } else {
+//                mergedGeometry = mergedGeometry.Union(featureGeometry);  // 合并几何
+//            }
+//        }
+//
+//
+//        layer2.SetSpatialFilter(mergedGeometry);  // 设置空间查询过滤条件
+//
+//        // 创建输出文件
+//        Driver driver = ogr.GetDriverByName("ESRI Shapefile");
+//        if (driver == null) {
+//            System.err.println("Shapefile driver not available.");
+//            return;
+//        }
+//
+//        // 创建输出图层
+//        DataSource outputDataSource = driver.CreateDataSource(outputShapefile, null);
+//        if (outputDataSource == null) {
+//            System.err.println("Failed to create output shapefile.");
+//            return;
+//        }
+//
+//        // 获取图层的空间参考
+//        SpatialReference spatialReference = layer1.GetSpatialRef();
+//
+//        // 创建输出图层的字段结构
+//        Layer outputLayer = outputDataSource.CreateLayer("intersection", spatialReference, ogr.wkbPolygon, null);
+//        // 复制输入图层的字段定义到输出图层
+//        for (int i = 0; i < layer1.GetLayerDefn().GetFieldCount(); i++) {
+//            FieldDefn fieldDefn = layer1.GetLayerDefn().GetFieldDefn(i);
+//            outputLayer.CreateField(fieldDefn);
+//        }
+////        outputLayer.CreateField(new FieldDefn("ID", ogr.OFTInteger));
+//
+//        // 执行叠加分析(交集)
+//        Layer intersectionLayer = getIntersectionLayer(layer1, layer2);
+//
+//        // 将交集结果保存到输出文件
+//        Feature feature;
+//        while ((feature = intersectionLayer.GetNextFeature()) != null) {
+//            outputLayer.CreateFeature(feature);
+//        }
+//
+//        // 关闭数据源
+//        ds1.delete();
+//        ds2.delete();
+//        outputDataSource.delete();
+//
+//        // 获取程序结束时的时间
+//        long endTime = System.currentTimeMillis();
+//
+//        // 计算并输出程序运行时间
+//        long duration = endTime - startTime;
+//        System.out.println("程序运行时间: " + round(duration / 1000) + " 秒");
+//    }
+//
+//    /**
+//     * 获取两个图层的交集
+//     *
+//     * @param layer1 第一个图层
+//     * @param layer2 第二个图层
+//     * @return 交集图层
+//     */
+//    private static Layer getIntersectionLayer(Layer layer1, Layer layer2) {
+//        List<Feature> intersectedFeatures = new ArrayList<>();
+//
+//        // 遍历第一个图层
+//        Feature feature1;
+//        layer1.ResetReading();
+//        while ((feature1 = layer1.GetNextFeature()) != null) {
+//            Geometry geom1 = feature1.GetGeometryRef();
+//
+//            // 遍历第二个图层,检查交集
+//            Feature feature2;
+//            layer2.ResetReading();
+//            while ((feature2 = layer2.GetNextFeature()) != null) {
+//                Geometry geom2 = feature2.GetGeometryRef();
+//
+//                // 计算交集
+//                if (geom1.Intersects(geom2)) {
+//                    Geometry intersection = geom1.Intersection(geom2);
+//
+//                    // 如果交集非空,保存交集
+//                    if (!intersection.IsEmpty()) {
+//                        Feature intersectedFeature = feature1.Clone();
+//                        intersectedFeature.SetGeometry(intersection);
+//                        intersectedFeatures.add(intersectedFeature);
+//                    }
+//                }
+//            }
+//        }
+//
+//        // 创建新的图层来保存交集结果
+//        Driver driver = ogr.GetDriverByName("Memory");
+//        DataSource memoryDataSource = driver.CreateDataSource("memory", null);
+//        Layer resultLayer = memoryDataSource.CreateLayer("intersection", layer1.GetSpatialRef(), ogr.wkbPolygon, null);
+//        resultLayer.CreateField(new FieldDefn("ID", ogr.OFTInteger));
+//
+//        // 将交集要素写入内存图层
+//        for (Feature feature : intersectedFeatures) {
+//            resultLayer.CreateFeature(feature);
+//        }
+//
+//        return resultLayer;
+//    }
+//}

+ 63 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileToGeoPackage.java

@@ -0,0 +1,63 @@
+//package com.onemap.overlap.utils;
+//
+//import org.gdal.ogr.*;
+//import org.gdal.osr.SpatialReference;
+//
+//public class ShapefileToGeoPackage {
+//    public static void main(String[] args) {
+//        // 注册 OGR 驱动
+//        ogr.RegisterAll();
+//
+//        // 输入和输出文件路径
+//        String inputShapefile = "E:\\projects\\监测图斑审查上传\\图斑套合\\管控数据\\基本农田.shp";
+//        String outputGeoPackage = "D:\\temp\\test.gpkg";
+//
+//        // 打开输入 Shapefile 数据源
+//        DataSource inputDataSource = ogr.Open(inputShapefile);
+//        if (inputDataSource == null) {
+//            System.err.println("无法打开 Shapefile: " + inputShapefile);
+//            return;
+//        }
+//
+//        // 获取 Shapefile 图层
+//        Layer inputLayer = inputDataSource.GetLayer(0);
+//
+//        // 获取 GPKG 驱动
+//        Driver gpkgDriver = ogr.GetDriverByName("GPKG");
+//        if (gpkgDriver == null) {
+//            System.err.println("GeoPackage 驱动不可用");
+//            return;
+//        }
+//
+//        // 创建输出 GeoPackage 数据源
+//        DataSource outputDataSource = gpkgDriver.CreateDataSource(outputGeoPackage, null);
+//        if (outputDataSource == null) {
+//            System.err.println("无法创建 GeoPackage: " + outputGeoPackage);
+//            return;
+//        }
+//
+//        // 创建输出图层,使用输入图层的空间参考
+//        SpatialReference spatialRef = inputLayer.GetSpatialRef();
+//        Layer outputLayer = outputDataSource.CreateLayer(inputLayer.GetName(), spatialRef, inputLayer.GetGeomType(), null);
+//
+//        // 复制输入图层的字段到输出图层
+//        for (int i = 0; i < inputLayer.GetLayerDefn().GetFieldCount(); i++) {
+//            FieldDefn fieldDefn = inputLayer.GetLayerDefn().GetFieldDefn(i);
+//            outputLayer.CreateField(fieldDefn);
+//        }
+//
+//        // 将输入图层的要素复制到输出图层
+//        Feature inputFeature;
+//        inputLayer.ResetReading();
+//        while ((inputFeature = inputLayer.GetNextFeature()) != null) {
+//            Feature outputFeature = inputFeature.Clone();
+//            outputLayer.CreateFeature(outputFeature);
+//        }
+//
+//        // 关闭数据源
+//        inputDataSource.delete();
+//        outputDataSource.delete();
+//
+//        System.out.println("Shapefile 导入到 GeoPackage 完成!");
+//    }
+//}

+ 96 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShapefileToSpatiaLiteWithProjection.java

@@ -0,0 +1,96 @@
+//package com.onemap.overlap.utils;
+//
+//import org.gdal.gdal.gdal;
+//import org.gdal.ogr.*;
+//import org.gdal.osr.*;
+//
+//public class ShapefileToSpatiaLiteWithProjection {
+//    public static void main(String[] args) {
+//        // 注册所有驱动
+//        ogr.RegisterAll();
+//        // 注册SpatiaLite驱动
+//        gdal.SetConfigOption("OGR_ENABLE_Spatialite", "ON");
+//        // 读取 Shapefile 文件
+//        String shapefilePath = "D:\\gisdata\\HaiNanXZQ\\XZQH3857.shp";
+//        String spatialiteDbPath = "D:\\temp\\mappatchcheck.sqlite";
+//        int srid = 4326;
+//
+//        // 创建 SpatiaLite 数据源(使用 SPATIALITE=YES 选项)
+//        Driver sqliteDriver = ogr.GetDriverByName("SQLite");
+//        if (sqliteDriver == null) {
+//            System.out.println("SQLite driver not available!");
+//            return;
+//        }
+//
+//        // 打开 Shapefile 数据源
+//        DataSource shapefile = ogr.Open(shapefilePath, 1); // 0 表示只读模式
+//        if (shapefile == null) {
+//            System.out.println("Failed to load Shapefile!");
+//            return;
+//        }
+//
+//        // 获取 Shapefile 图层
+//        Layer shapefileLayer = shapefile.GetLayer(0); // 假设我们只处理第一个图层
+//
+//        // 创建目标空间投影坐标系(例如:WGS 84,EPSG:4326)
+//        SpatialReference targetSpatialRef = new SpatialReference();
+//        targetSpatialRef.ImportFromEPSG(srid); // 设置为 EPSG:4326 坐标系(WGS84)
+//
+//        // 获取当前 Shapefile 图层的空间参考
+//        SpatialReference sourceSpatialRef = shapefileLayer.GetSpatialRef();
+//        if (sourceSpatialRef == null) {
+//            System.out.println("Shapefile does not have a defined coordinate system.");
+//            return;
+//        }
+//
+//        // 如果源空间参考与目标不同,则进行坐标转换
+//        if (sourceSpatialRef != null && sourceSpatialRef != targetSpatialRef) {
+//            // 创建坐标转换
+//            CoordinateTransformation transform = CoordinateTransformation.CreateCoordinateTransformation(sourceSpatialRef, targetSpatialRef);
+//
+//            // 遍历 Shapefile 中的每个要素并转换其坐标
+//            for (int i = 0; i < shapefileLayer.GetFeatureCount(); i++) {
+//                Feature feature = shapefileLayer.GetFeature(i);
+//                Geometry geometry = feature.GetGeometryRef();
+//
+//                // 将几何坐标从源坐标系转换到目标坐标系
+//                geometry.Transform(transform);
+//
+//                // 更新要素的几何数据
+//                feature.SetGeometry(geometry);
+//                shapefileLayer.SetFeature(feature);
+//            }
+//            System.out.println("Coordinate transformation applied.");
+//        }
+//
+//
+//
+//        String[] options = {"SPATIALITE=YES"};
+//        DataSource spatialiteDb = sqliteDriver.CreateDataSource(spatialiteDbPath, null);
+//        if (spatialiteDb == null) {
+//            System.out.println("Failed to create SpatiaLite database!");
+//            return;
+//        }
+//
+//        // 创建 SpatiaLite 图层(使用目标坐标系)
+//        String layerName = shapefileLayer.GetName();
+//        Layer spatialiteLayer = spatialiteDb.CreateLayer(layerName, targetSpatialRef, shapefileLayer.GetGeomType(), null);
+//        if (spatialiteLayer == null) {
+//            System.out.println("Failed to create layer in SpatiaLite.");
+//            return;
+//        }
+//
+//        // 将 Shapefile 图层复制到 SpatiaLite 图层
+//        spatialiteDb.CopyLayer(shapefileLayer, layerName, null);
+//
+//        // 创建空间索引
+//        String sql = "SELECT CreateSpatialIndex('" + layerName + "', 'geometry');";
+//        spatialiteDb.ExecuteSQL(sql);
+//
+//        // 关闭数据源
+//        shapefile.delete();
+//        spatialiteDb.delete();
+//
+//        System.out.println("Shapefile successfully imported to SpatiaLite with target projection.");
+//    }
+//}

+ 159 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/ShpToSpatiaLite.java

@@ -0,0 +1,159 @@
+package com.onemap.overlap.utils;
+
+import com.onemap.overlap.utils.SpatialiteUtils;
+import org.geotools.data.DataStore;
+import org.geotools.data.DataStoreFinder;
+import org.geotools.data.simple.SimpleFeatureCollection;
+import org.geotools.data.simple.SimpleFeatureIterator;
+import org.geotools.feature.simple.SimpleFeatureBuilder;
+import org.geotools.geometry.jts.JTS;
+import org.locationtech.jts.geom.MultiPolygon;
+import org.locationtech.jts.io.WKTWriter;
+import org.opengis.feature.simple.SimpleFeature;
+import org.opengis.feature.simple.SimpleFeatureType;
+import org.opengis.filter.Filter;
+import org.springframework.beans.factory.annotation.Value;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
+
+public class ShpToSpatiaLite {
+
+//    public static void main(String[] args) throws Exception {
+//        String shapefilePath = "D:\\temp\\ccs.shp";
+//        String spatialiteDbPath = "D:\\temp\\mappatchcheck.sqlite";
+//        // TODO 1. 连接到 Spatialite 数据库
+//        Connection conn = SpatialiteUtils.getSpatialiteConnection(spatialiteDbPath);
+//        // TODO 2. 解析 Shapefile 数据
+//        File shapefile = new File(shapefilePath);
+//        DataStore dataStore = DataStoreFinder.getDataStore(Collections.singletonMap("url", shapefile.toURI().toURL()));
+//        String typeName = dataStore.getTypeNames()[0];  // 获取第一个图层的名称
+//        SimpleFeatureCollection featureCollection = dataStore.getFeatureSource(typeName).getFeatures();
+//        //TODO  3. 创建表结构
+//        createSpatialTable(conn, typeName, featureCollection);
+//        // TODO 4. 遍历每个要素并插入数据
+//        insertFeaturesToSpatialite(conn, featureCollection, typeName);
+//        // TODO 5. 为几何字段创建空间索引
+//        createSpatialIndex(conn, typeName);
+//        // TODO 6. 关闭数据库连接
+//        conn.close();
+//    }
+
+    /**
+     * 导入shp到spatialite
+     *
+     * @param dbpath    sqlite文件位置
+     * @param shppath   shp文件路径
+     * @param wkid      坐标系
+     * @param tablename 入库表名
+     * @return
+     * @throws Exception
+     */
+    public static Boolean ImportShpToSpatialite(String dbpath, String shppath, Integer wkid, String tablename) {
+        Connection conn = null;
+        try {
+            String shapefilePath = shppath;
+            String spatialiteDbPath = dbpath;
+            // TODO 1. 连接到 Spatialite 数据库
+            conn = SpatialiteUtils.getSpatialiteConnection(spatialiteDbPath);
+            // TODO 2. 解析 Shapefile 数据
+            File shapefile = new File(shapefilePath);
+            DataStore dataStore = DataStoreFinder.getDataStore(Collections.singletonMap("url", shapefile.toURI().toURL()));
+            String typeName = dataStore.getTypeNames()[0];  // 获取第一个图层的名称
+            SimpleFeatureCollection featureCollection = dataStore.getFeatureSource(typeName).getFeatures();
+            //TODO  3. 创建表结构
+            createSpatialTable(conn, tablename, featureCollection);
+            // TODO 4. 遍历每个要素并插入数据
+            insertFeaturesToSpatialite(conn, featureCollection, tablename, wkid);
+            // TODO 5. 为几何字段创建空间索引
+            createSpatialIndex(conn, tablename);
+            // TODO 6. 关闭数据库连接
+            conn.close();
+            return true;
+        }catch (Exception e){
+            if (conn != null){
+                //conn.close();
+            }
+            e.printStackTrace();
+            return false;
+        }
+    }
+
+    // 3. 创建空间表结构
+    public static void createSpatialTable(Connection conn, String tableName, SimpleFeatureCollection featureCollection) throws SQLException {
+        SimpleFeatureType featureType = featureCollection.getSchema();
+        StringBuilder createTableSQL = new StringBuilder();
+        Statement stmt = conn.createStatement();
+        stmt.execute("drop table if exists '" + tableName + "';");
+        // 创建表结构,注意字段名称和类型要根据实际的 FeatureType 构建
+        createTableSQL.append("CREATE TABLE ").append(tableName).append(" (");
+        // 遍历属性字段,构建 SQL 表字段
+        for (int i = 0; i < featureType.getAttributeCount(); i++) {
+            String fieldName = featureType.getDescriptor(i).getName().getLocalPart();
+            if (fieldName.toLowerCase().contains("geom")) {
+                continue;
+            }
+            String fieldType = "TEXT";  // 默认字段类型,GeoTools 可以根据字段类型调整
+            // 根据字段类型调整
+            if (featureType.getDescriptor(i).getType().getBinding().equals(Integer.class)) {
+                fieldType = "INTEGER";
+            } else if (featureType.getDescriptor(i).getType().getBinding().equals(Double.class)) {
+                fieldType = "REAL";
+            } else if (featureType.getDescriptor(i).getType().getBinding().equals(String.class)) {
+                fieldType = "TEXT";
+            }
+            createTableSQL.append(fieldName).append(" ").append(fieldType).append(",");
+        }
+        // 添加几何列
+        createTableSQL.append("geom GEOMETRY");
+        createTableSQL.append(");");
+        stmt.execute(createTableSQL.toString());
+//        stmt.execute("SELECT CreateSpatialIndex('" + tableName + "', 'geom');");
+    }
+
+    // 4. 遍历要素并插入数据
+    public static void insertFeaturesToSpatialite(Connection conn, SimpleFeatureCollection featureCollection, String tableName, Integer wkid) throws SQLException {
+        StringBuilder fields = new StringBuilder();
+        Statement stmt = conn.createStatement();
+        SimpleFeatureType featureType = featureCollection.getSchema();
+        for (int i = 0; i < featureType.getAttributeCount(); i++) {
+            String fieldName = featureType.getDescriptor(i).getName().getLocalPart();
+            if (fieldName.toLowerCase().contains("geom")) {
+                continue;
+            }
+            fields.append(fieldName).append(",");
+        }
+        // 去除末尾的逗号
+        fields.append("geom");
+        // 遍历所有要素
+        SimpleFeatureIterator iterator = featureCollection.features();
+        while (iterator.hasNext()) {
+            SimpleFeature feature = iterator.next();
+            // 为每个字段设置值
+            StringBuilder current = new StringBuilder();
+            for (int i = 0; i < featureType.getAttributeCount(); i++) {
+                String fieldName = featureType.getDescriptor(i).getName().getLocalPart();
+                if (fieldName.toLowerCase().contains("geom")) {
+                    continue;
+                }
+                Object value = feature.getAttribute(i);
+                current.append("'" + value + "'").append(",");
+            }
+            Object geometry = feature.getDefaultGeometry();
+            String sql = "INSERT INTO " + tableName + " (" + fields.toString() + ") VALUES (" + current.toString() + "GeomFromText('" + geometry + "', " + wkid + "))";
+            stmt.executeUpdate(sql);
+        }
+        String sql = "select recovergeometrycolumn('" + tableName + "', 'geom', " + wkid + ", 'MULTIPOLYGON', 'XY')";
+        stmt.executeUpdate(sql);
+    }
+
+    // 5. 创建空间索引
+    public static void createSpatialIndex(Connection conn, String tableName) throws SQLException {
+        Statement stmt = conn.createStatement();
+        stmt.execute("SELECT CreateSpatialIndex('" + tableName + "', 'geom');");
+    }
+}

+ 56 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/SpatialiteSample.java

@@ -0,0 +1,56 @@
+//package com.onemap.overlap.utils;
+//
+//import java.sql.Connection;
+//import java.sql.ResultSet;
+//import java.sql.SQLException;
+//import java.sql.Statement;
+//
+//import org.sqlite.SQLiteConfig;
+//
+//public class SpatialiteSample {
+//
+//
+//    public static void main(String[] args) throws ClassNotFoundException, SQLException {
+//        // load the sqlite-JDBC driver using the current class loader
+//        Class.forName("org.sqlite.JDBC");
+//
+//        Connection conn = null;
+//        try {
+//            // enabling dynamic extension loading
+//            // absolutely required by SpatiaLite
+//            System.out.println(org.sqlite.SQLiteJDBCLoader.getVersion());
+////            System.setProperty("java.library.path", "E:\\google-download\\mod_spatialite-5.0.1-win-amd64\\mod_spatialite-5.0.1-win-amd64");
+//            SQLiteConfig config = new SQLiteConfig();
+//            config.enableLoadExtension(true);
+//            conn = config.createConnection("jdbc:sqlite:D:\\temp\\mappatchcheck.sqlite");
+//            // create a database connection
+////            conn = DriverManager.getConnection("jdbc:sqlite:spatialite-test.sqlite?enable_load_extension=1"
+////                    );
+////            conn.enableLoadExtension(true);
+//            Statement stmt = conn.createStatement();
+//            stmt.setQueryTimeout(30); // set timeout to 30 sec.
+//
+//            // loading SpatiaLite
+//            stmt.execute("SELECT load_extension('mod_spatialite')");
+//
+//            // checking SQLite and SpatiaLite version + target CPU
+//            String sql = "SELECT spatialite_version(), spatialite_target_cpu()";
+//            ResultSet rs = stmt.executeQuery(sql);
+//            while (rs.next()) {
+//                // read the result set
+//                String msg = "SQLite version: ";
+//                msg += rs.getString(1);
+//                System.out.println(msg);
+//                msg = "SpatiaLite version: ";
+//                msg += rs.getString(2);
+//                System.out.println(msg);
+//            }
+//            // enabling Spatial Metadata
+//            // this automatically initializes SPATIAL_REF_SYS and GEOMETRY_COLUMNS
+////            sql = "SELECT InitSpatialMetadata(1)";
+////            stmt.execute(sql);
+//        } catch (SQLException e) {
+//            throw new RuntimeException(e);
+//        }
+//    }
+//}

+ 22 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/SpatialiteUtils.java

@@ -0,0 +1,22 @@
+package com.onemap.overlap.utils;
+
+import org.sqlite.SQLiteConfig;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+
+public class SpatialiteUtils {
+    public static Connection getSpatialiteConnection(String dbFile) throws Exception {
+        Class.forName("org.sqlite.JDBC");
+        Connection conn = null;
+        System.out.println(org.sqlite.SQLiteJDBCLoader.getVersion());
+        SQLiteConfig config = new SQLiteConfig();
+        config.enableLoadExtension(true);
+        conn = config.createConnection("jdbc:sqlite:" + dbFile);
+        Statement stmt = conn.createStatement();
+        stmt.setQueryTimeout(30);
+        stmt.execute("SELECT load_extension('mod_spatialite')");
+        return conn;
+    }
+}

+ 81 - 0
onemap-modules/onemap-overlap/src/main/java/com/onemap/overlap/utils/UnPackageUtils.java

@@ -0,0 +1,81 @@
+package com.onemap.overlap.utils;
+
+import com.github.junrar.Archive;
+import com.github.junrar.rarfile.FileHeader;
+import net.lingala.zip4j.core.ZipFile;
+
+import java.io.File;
+import java.io.FileOutputStream;
+
+/**
+ * @author : wangping
+ * @createDate: 2021/7/12
+ * @description:解压缩工具
+ **/
+
+
+public class UnPackageUtils {
+
+    /**
+     * zip文件解压
+     *
+     * @param destPath 解压文件路径
+     * @param zipFile  压缩文件
+     *                 //* @param password 解压密码(如果有)
+     */
+    public static void unPackZip(File zipFile, String destPath) {
+
+        try {
+            ZipFile zip = new ZipFile(zipFile);
+            /*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
+            zip.setFileNameCharset("GBK");
+            zip.extractAll(destPath);
+
+            // 如果解压需要密码
+//            if (zip.isEncrypted()) {
+//                zip.setPassword(password);
+//            }
+        } catch (Exception e) {
+        }
+    }
+
+    /**
+     * rar文件解压(不支持有密码的压缩包)
+     *
+     * @param rarFile  rar压缩包
+     * @param destPath 解压保存路径
+     */
+    public static void unPackRar(File rarFile, String destPath) {
+        try (Archive archive = new Archive(rarFile)) {
+            if (null != archive) {
+                FileHeader fileHeader = archive.nextFileHeader();
+                File file = null;
+                while (null != fileHeader) {
+                    // 防止文件名中文乱码问题的处理
+                    String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
+                    if (fileHeader.isDirectory()) {
+                        //是文件夹
+                        file = new File(destPath + File.separator + fileName);
+                        file.mkdirs();
+                    } else {
+                        //不是文件夹
+                        file = new File(destPath + File.separator + fileName.trim());
+                        if (!file.exists()) {
+                            if (!file.getParentFile().exists()) {
+                                // 相对路径可能多级,可能需要创建父目录.
+                                file.getParentFile().mkdirs();
+                            }
+                            file.createNewFile();
+                        }
+                        FileOutputStream os = new FileOutputStream(file);
+                        archive.extractFile(fileHeader, os);
+                        os.close();
+                    }
+                    fileHeader = archive.nextFileHeader();
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 8 - 2
onemap-modules/onemap-overlap/src/main/resources/application.yml

@@ -4,6 +4,7 @@ spring:
     host: localhost
     port: 6379
     password:
+# tomcat配置
 server:
   port: 9206
 # swagger配置
@@ -11,6 +12,11 @@ swagger:
   title: 系统模块接口文档
   license: Powered By ruoyi
   licenseUrl: https://ruoyi.vip
-
+# Spatialite数据库配置
 spatialite:
-  filePath: D:\mapcheck.sqlite
+  filePath: D:\temp\mappatchcheck.sqlite
+# 文件路径配置
+file:
+  temp: D:\temp\
+  wkid: 4525
+  prefix: sw_