zrj
2024-11-04 24387f2317d499409697b83a21cdb4995c467278
集成 shp 文件导入
3 files modified
3 files added
387 ■■■■■ changed files
pom.xml 17 ●●●●● patch | view | raw | blame | history
src/main/java/org/springblade/common/utils/CoordinateSystemUtil.java 101 ●●●●● patch | view | raw | blame | history
src/main/java/org/springblade/common/utils/ShapeFileUtil.java 129 ●●●●● patch | view | raw | blame | history
src/main/java/org/springblade/common/utils/ZipUtil.java 132 ●●●●● patch | view | raw | blame | history
src/main/java/org/springblade/modules/yw/mapper/RiskSourceMapper.xml 2 ●●● patch | view | raw | blame | history
src/main/java/org/springblade/modules/yw/vo/RiskSourceVO.java 6 ●●●●● patch | view | raw | blame | history
pom.xml
@@ -232,6 +232,16 @@
            <scope>system</scope>
            <systemPath>${pom.basedir}/lib/aspose-cad-24.3.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>28.0</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>28.0</version>
        </dependency>
    </dependencies>
    <build>
@@ -324,6 +334,13 @@
            <name>BladeX Release Repository</name>
            <url>https://center.javablade.com/api/packages/blade/maven</url>
        </repository>
        <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>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
src/main/java/org/springblade/common/utils/CoordinateSystemUtil.java
New file
@@ -0,0 +1,101 @@
package org.springblade.common.utils;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
/**
 * 空间坐标工具类
 */
public class CoordinateSystemUtil {
    public static void main(String[] args) {
        String wtk= "MULTIPOLYGON(((3.94836025714E7 3176072.7897, 3.94835938931E7 3176063.7288, 3.94835894481E7 3176067.1154, 3.94835981264E7 3176075.7938, 3.94836026103E7 3176085.7288, 3.94836089215E7 3176099.7123, 3.94836159065E7 3176121.5139, 3.94836178114E7 3176140.9873, 3.94836181917E7 3176148.7199, 3.94836214775E7 3176146.8663, 3.94836254582E7 3176144.37, 3.94836237382E7 3176137.8123, 3.94836165415E7 3176107.3321, 3.9483608468E7 3176087.3696, 3.94836025714E7 3176072.7897)))";
        String se=wtk.replaceAll(",\\["," ").replaceAll("]","").replaceAll("\\[","");
        System.out.println(se);
        System.out.println(poylonCGCStoWGS(se));
    }
    public static Geometry pointCGCStoWGS(Double lot, Double lat) {
        String wkt = "POINT (" + lot + " " + lat + ")";
        Geometry source = createGeometry(wkt, 4527);
        return coordinateTransform(source, 4326);
    }
    public static Geometry pointWGStoCGCS(Double lot, Double lat) {
        String wkt = "POINT (" + lot + " " + lat + ")";
        Geometry source = createGeometry(wkt, 4326);
        return coordinateTransform(source, 4527);
    }
    public static String poylonWGStoCGCS(String poylon) {
        Geometry source = createGeometry(poylon, 4326);
        Geometry transformedGeometry = coordinateTransform(source, 4527);
        return transformedGeometry.toText();
    }
    public static String poylonCGCStoWGS(String poylon) {
        Geometry source = createGeometry(poylon, 4527);
        Geometry transformedGeometry = coordinateTransform(source, 4326);
        return transformedGeometry.toText();
    }
    public static double[] extractCoordinates(Geometry geometry) {
        // 如果是点类型的几何对象,则直接提取坐标
        if (geometry instanceof Point) {
            Coordinate coordinate = geometry.getCoordinate();
            return new double[]{coordinate.getX(), coordinate.getY()};
        } else {
            // 如果不是点类型,则返回 null 或者根据需要处理其他几何对象类型
            return null;
        }
    }
    // 格式化坐标值,保留指定小数位数
    public static String formatCoordinate(double coordinate) {
        return String.format("%.15f", coordinate).replaceAll("\\.?0*$", "");
    }
    public static Geometry createGeometry(String wkt, int srid) {
        try {
            WKTReader reader = new WKTReader();
            Geometry geometry = reader.read(wkt);
            geometry.setSRID(srid);
            return geometry;
        } catch (ParseException e) {
            System.out.println("WKT解析错误: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Geometry coordinateTransform(Geometry sourceGeometry, int targetSrid) {
        if (sourceGeometry == null || sourceGeometry.getSRID() == 0 || targetSrid == 0) {
            return null;
        }
        try {
            CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);
            CoordinateReferenceSystem source = factory.createCoordinateReferenceSystem("EPSG:" + sourceGeometry.getSRID());
            CoordinateReferenceSystem target = factory.createCoordinateReferenceSystem("EPSG:" + targetSrid);
            MathTransform transform = CRS.findMathTransform(source, target, true);
            Geometry res = JTS.transform(sourceGeometry, transform);
            if (res != null) {
                res.setSRID(targetSrid);
            }
            return res;
        } catch (FactoryException | TransformException e) {
            e.printStackTrace();
        }
        return null;
    }
}
src/main/java/org/springblade/common/utils/ShapeFileUtil.java
New file
@@ -0,0 +1,129 @@
package org.springblade.common.utils;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geojson.feature.FeatureJSON;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
public class ShapeFileUtil {
    /**
     * 将文件解压
     * @param zipFile
     * @return
     * @throws IOException
     */
    public static FeatureCollection getFeatureCollectionByShpFile(File zipFile) throws IOException {
        try {
            String tempDir = FileUtil.getTmpDirPath();
            File shapeDir = new File(tempDir + File.separator + new Date().getTime());
            shapeDir.mkdir();
            List<String> files = ZipUtil.unZipFiles(zipFile, shapeDir.getPath() + File.separator);
            String shapFileName = "";
            for (String fileName : files) {
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                if ("shp".equals(suffix)) {
                    shapFileName = fileName;
                }
            }
            File shapeFile = new File(shapFileName);
            Map<String, Object> shapeFileParams = new HashMap();
            shapeFileParams.put("url", shapeFile.toURI().toURL());
            // 设置编码
            shapeFileParams.put("charset", "utf-8");
            DataStore dataStore = DataStoreFinder.getDataStore(shapeFileParams);
            if (dataStore == null) {
                throw new RuntimeException("couldn't load the damn data store: " + shapeFileParams);
            }
            String typeName = dataStore.getTypeNames()[0];
            FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);
            Filter filter = Filter.INCLUDE;
            FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(filter);
            return collection;
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     * 解析shp文件返回数据
     * @param zipFile:
     * @return JSONObject
     * @description 通过shp压缩文件,将其转换为GeoJson格式
     */
    //将解压后的文件转换成GeoJson格式
    public static List<Map<String,Object>> shpToGeoJson(File zipFile) throws IOException{
        List<Map<String,Object>> dtoList = new ArrayList<>();
        try {
            FeatureJSON featureJSON = new FeatureJSON();
            JSONObject geoJsonObject = new JSONObject();
            geoJsonObject.put("type", "FeatureCollection");
            // 解压zip文件,获取FeatureCollection
            FeatureCollection collection = getFeatureCollectionByShpFile(zipFile);
            // 获取迭代对象
            FeatureIterator iterator = collection.features();
            // 遍历feature转为json对象
            while (iterator.hasNext()) {
                Map<String,Object> shpDTO = new HashMap<>();
                SimpleFeature feature = (SimpleFeature) iterator.next();
                StringWriter writer = new StringWriter();
                featureJSON.writeFeature(feature, writer);
                String temp = writer.toString();
                JSONObject json = JSONObject.parseObject(temp);
                try {
                    // 空间坐标
                    shpDTO.put("geometry",json.getJSONObject("geometry").getString("coordinates"));
                    // 空间类型
                    if (json.getJSONObject("geometry").get("type") != null) {
                        shpDTO.put("geoType",json.getJSONObject("geometry").getString("type"));
                    }
                    dtoList.add(shpDTO);
                } catch (NumberFormatException e) {
                    System.err.println("处理单个特征时发生错误:" + e.getMessage());
                } catch (Exception e) {
                    System.err.println("处理单个特征时发生错误:" + e.getMessage());
                }
            }
            iterator.close();
        } catch (IOException e) {
            System.err.println("读取或解析文件时发生错误:" + e.getMessage());
            throw e;
        }
        return dtoList;
    }
    public static void main(String[] args) throws IOException, ParseException {
        File file = new File("F:\\test4jdata\\shp\\zrq.zip");
        List<Map<String, Object>> list = shpToGeoJson(file);
        System.out.println("list = " + list);
    }
    public static double[] getLongitudeLatitude(Geometry wktPoint) throws ParseException {
        Geometry geometry = wktPoint;
        if (geometry instanceof Point) {
            Point point = (Point) geometry;
            double longitude = point.getX();
            double latitude = point.getY();
            return new double[]{longitude, latitude};
        } else {
            throw new IllegalArgumentException("The geometry is not a point.");
        }
    }
}
src/main/java/org/springblade/common/utils/ZipUtil.java
New file
@@ -0,0 +1,132 @@
package org.springblade.common.utils;
import org.springframework.context.annotation.Configuration;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@Configuration
public class ZipUtil {
    /**
     * zip解压
     *
     * @param srcFile     zip源文件
     * @param destDirPath 解压后的目标文件夹
     * @return list 解压文件的路径合集
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static List<String> unZipFiles(File srcFile, String destDirPath) throws RuntimeException {
        List<String> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + File.separator + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + File.separator + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    File parentFile = targetFile.getParentFile();
                    if (!parentFile.exists()) {
                        parentFile.mkdirs();
                    }
                    list.add(destDirPath + entry.getName());
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
    // 定义一个公共的静态方法zipFolder,用于压缩文件夹
    public static boolean zipFolder(String sourceFolderPath, String zipFilePath) {
        File sourceFile = new File(sourceFolderPath);
        try (
                FileOutputStream fos = new FileOutputStream(zipFilePath);
                ZipOutputStream zos = new ZipOutputStream(fos)
        ) {
            zipFile(sourceFile, sourceFile.getName(), zos);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    // 将文件夹整体压缩
    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zos) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zos.putNextEntry(new ZipEntry(fileName));
                zos.closeEntry();
            } else {
                zos.putNextEntry(new ZipEntry(fileName + "/"));
                zos.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + "/" + childFile.getName(), zos);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        fis.close();
    }
    public static void main(String[] args) {
        // 调用方法进行测试
    }
}
src/main/java/org/springblade/modules/yw/mapper/RiskSourceMapper.xml
@@ -20,7 +20,7 @@
    <select id="selectRiskSourcePage" resultType="org.springblade.modules.yw.vo.RiskSourceVO">
        select
        yrs.*,
        yfi.name as firmName,yfi.category,yfi.main_product,
        yfi.name as firmName,yfi.category,yfi.main_product,yfi.lng,yfi.lat,
        bdb.dict_value as riskLevelName
        from
        yw_risk_source yrs
src/main/java/org/springblade/modules/yw/vo/RiskSourceVO.java
@@ -27,4 +27,10 @@
    @ApiModelProperty(value = "主要产品")
    private String mainProduct;
    @ApiModelProperty(value = "经度")
    private String lng;
    @ApiModelProperty(value = "纬度")
    private String lat;
}