欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA 用geotools 同时导入多个 KML到 postgreSQL数据库

程序员文章站 2022-07-05 16:54:20
KML 导入postgreSQL 数据库依赖导入org.geotoolsgt-geojson24.1

KML 导入postgreSQL 数据库

依赖导入

<!--geotools 工具类-->
<dependency>
		<groupId>org.geotools</groupId>
		<artifactId>gt-geojson</artifactId>
		<version>24.1</version>
</dependency>

<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-shapefile</artifactId>
  <version>24.1</version>
</dependency>

<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-swing</artifactId>
  <version>24.1</version>
</dependency>

<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-epsg-hsql</artifactId>
  <version>24.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/de.micromata.jak/JavaAPIforKml -->
<dependency>
  <groupId>de.micromata.jak</groupId>
  <artifactId>JavaAPIforKml</artifactId>
  <version>2.2.1</version>
</dependency>
<!--postdreSQL依赖-->
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-generator</artifactId>
  <version>3.3.2</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.3.2</version>
</dependency>

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
  <version>3.2.0</version>
</dependency>

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
</dependency>

<dependency>
  <groupId>net.postgis</groupId>
  <artifactId>postgis-jdbc</artifactId>
  <version>2.5.0</version>
</dependency>

<dependency>
  <groupId>com.eyougo</groupId>
  <artifactId>mybatis-typehandlers-postgis</artifactId>
  <version>1.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
    </exclusion>
    <exclusion>
      <groupId>net.postgis</groupId>
      <artifactId>postgis-jdbc</artifactId>
    </exclusion>
  </exclusions>
</dependency>

存入数据库实体类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.paramland.geo.component.FeatureSerializer;
import com.paramland.geo.component.GeometrySerializer;
import com.paramland.geo.enumn.DataSourceTypeEnum;
import com.paramland.geo.enumn.GeomCategory;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;

/**
 * 标注请求参数
 */
@Data
@ApiModel(value = "标注请求参数", description = "标注请求参数")
public class MarkVo extends BaseVo {

    /**
     * 标注图形类型
     * 1: POINT 点
     * 2: LINESTRING 线串
     * 3: POLYGON 多边形
     * 4: MULTIPOINT 多个点
     * 5: MULTILINESTRING 多个线串
     * 6: MULTIPOLYGON 多个多边形
     * 7: GEOMETRYCOLLECTION 几何集合
     * 8: 包围盒,Polygon加上高度值
     * 9: 体
     */
    @ApiModelProperty(value = "标注图形类型 1: POINT 点,2: LINESTRING 线串,3: POLYGON 多边形,4: MULTIPOINT 多个点," +
            "5: MULTILINESTRING 多个线串,6: MULTIPOLYGON 多个多边形,7: GEOMETRYCOLLECTION 几何集合," +
            "8: 包围盒,Polygon加上高度值,9: 体", example = "1")
    private Integer tagType;
    /**
     * 标注业务类型
     * 1: 点标绘
     * 2: 测量
     * 3:压平
     * 4:模型标绘
     * 5: 面标绘
     * 6:圆标绘
     * 7:体标绘
     * 8:多段线标绘
     * 9:抛物线标绘
     * 10:曲线标绘
     */
    @ApiModelProperty(value = "业务类型,1: 点标绘,2: 测量,3:压平,4:模型标绘,5: 面标绘,6:圆标绘,7:体标绘,8:多段线标绘," +
            "9:抛物线标绘,10:曲线标绘,11:包围盒,13:直角线标绘,14:墙标绘,15:矩形标绘,16:线标绘,17:条带标绘,18:球体标绘", example = "1")
    private Integer bizType;

    /**
     * poi的GeoJson对应的Feature
     */
    @ApiModelProperty(value = "poi的GeoJson对应的Feature", dataType = "com.alibaba.fastjson.JSONObject", example = "{ \"type\": \"Feature\", \"properties\": {}, \"geometry\": { \"type\": \"Point\", \"coordinates\": [106.551808137304,29.687846285011,306.984456211726] } }")
    @JSONField(deserializeUsing = FeatureSerializer.class, serializeUsing = FeatureSerializer.class)
    private SimpleFeature feature;

    /**
     * 图形集合时
     * poi的GeoJson对应的GeometryCollection
     */
    @ApiModelProperty(value = "图形集合时,poi的GeoJson对应的GeometryCollection", dataType = "com.alibaba.fastjson.JSONObject", example = "{ \"type\": \"GeometryCollection\", \"geometries\": [{ \"type\": \"Point\", \"coordinates\": [108.62,31.02819,301.44] }, { \"type\": \"LineString\", \"coordinates\": [ [108.896484375, 30.1071178870, 301.22], ] }] }")
    @JSONField(deserializeUsing = GeometrySerializer.class, serializeUsing = GeometrySerializer.class)
    private Geometry geometry;

    /**
     * 数据来源
     */
    private DataSourceTypeEnum dataSource = DataSourceTypeEnum.MARK;

    /**
     * 是否永久显示,1:是,0:否
     */
    @ApiModelProperty(value = "是否永久显示,1:是,0:否", example = "0")
    private Integer isPermanent;

    /**
     * 是否永久显示,1:是,0:否
     */
    @ApiModelProperty(value = "文件bid", example = "0")
    private String fileBid;

    /**
     * POI图形偏移量
     */
    @ApiModelProperty(value = "POI图形偏移量", example = "{\"x\":-100,\"y\":100,\"z\":100}")
    private JSON geomOffset;

    /**
     * 来源哪一张shp表
     */
    @ApiModelProperty(value = "来源哪一张shp表 导入shp专用")
    private String fromShpResource;

    /**
     * 来源哪一张shp表
     */
    @ApiModelProperty(value = "高层值")
    private Double height;
    /**
     * 图形分类 1:标绘,2:空间分析
     */
    @ApiModelProperty(value = "图形分类 1:标绘,2:空间分析")
    private GeomCategory geomCategory;

}

参数实体类

KmlLine(线)

import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @program: ParseKMLForJava
 * @description:
 * @Date 2021/1/11 下午4:50
 * @Version 1.0
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class KmlLine {
    private List<Coordinate> points;
    private String name;
    private String description;
    private Integer type = 2 ;
}

KmlPoint(点)

import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 *
 * @program: ParseKMLForJava
 * @description:
 * @Date 2021/1/11 下午4:50
 * @Version 1.0
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class KmlPoint {
    private List<Coordinate> points;
    private String name;
    private String description;
    private Integer type = 1;
}

KmlPolygon(面)

import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
 *
 * @program: ParseKMLForJava
 * @description:
 * @Date 2021/1/11 下午4:50
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class KmlPolygon {
    private List<Coordinate> points;
    private String name;
    private String description;
    private Integer type = 3;

}

KmlProperties(用来存储描述 文本信息)

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 *
 * @program: ParseKMLForJava
 * @description:
 * @Date 2021/1/11 下午4:50
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class KmlProperties {
   private String name;
   private String description;
}

KmlProperty(用来存储解析的集合信息)

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;


/**
 *
 * @program: ParseKMLForJava
 * @description:
 * @Author Mc QiLing
 * @Date 2021/1/11 下午4:50
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class KmlProperty {
    private List<KmlPoint> kmlPoints;
    private List<KmlLine> kmlLines;
    private List<KmlPolygon> kmlPolygons;
}

ParsingKmlUtil(用来解析KML信息)

import de.micromata.opengis.kml.v_2_2_0.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: my_project
 * @description: KML文件解析:先获取kml文件的根节点,依次遍历当前节点的子节点的信息,
 * 如果遇到节点属于Folder、Document则继续解析其子节点;反之则解析PlaceMark节点(主要解析LineString、Point、Polygon)。
 * @create: 2021-01-11 12:39
 **/
public class ParsingKmlUtil {

    private List<KmlPoint> kmlPointList = new ArrayList<>();
    private List<KmlLine> kmlLineList = new ArrayList<>();
    private List<KmlPolygon> kmlPolygonList = new ArrayList<>();
    private KmlProperty kmlProperty = new KmlProperty();
 
    /**
     * 保存kml数据到临时表
     *
     * @param file 上传的文件实体
     * @return 自定义的KML文件实体
     */
    public KmlProperty parseKmlForJAK(File file) {
        Kml kml = Kml.unmarshal(file);
        Feature feature = kml.getFeature();
        parseFeature(feature);
        kmlProperty.setKmlPoints(kmlPointList);
        kmlProperty.setKmlLines(kmlLineList);
        kmlProperty.setKmlPolygons(kmlPolygonList);
        return kmlProperty;
    }
 
    /**
     * 解析kml节点信息
     *
     * @param feature 需要解析到要素信息
     * @return
     */
    private void parseFeature(Feature feature) {
        if (feature != null) {
            //判断根节点是否为Document
            if (feature instanceof Document) {
                List<Feature> featureList = ((Document) feature).getFeature();
                //遍历已获取的节点信息(节点信息为List),将list使用forEach进行遍历(同for、while)
                featureList.forEach(documentFeature -> {
                            //判断遍历节点是否为PlaceMark,否则迭代解析
                            if (documentFeature instanceof Placemark) {
                                getPlaceMark((Placemark) documentFeature);
                            } else {
                                parseFeature(documentFeature);
                            }
                        }
                );
            } else if (feature instanceof Folder) {
                //原理同上
                List<Feature> featureList = ((Folder) feature).getFeature();
                featureList.forEach(documentFeature -> {
                            if (documentFeature instanceof Placemark) {
                                getPlaceMark((Placemark) documentFeature);
                            }
                            {
                                parseFeature(documentFeature);
                            }
                        }
                );
            }
        }
    }
 
    /**
     * 解析PlaceMark节点下的信息
     *
     * @return
     */
    private void getPlaceMark(Placemark placemark) {
        String description = placemark.getDescription();
        String name = placemark.getName();
        Geometry geometry = placemark.getGeometry();
        parseGeometry(name,description,geometry);
    }

    /**
     * 解析PlaceMark节点下的信息
     *
     * @return
     */
    private void parseGeometry(String name,String description, Geometry geometry) {
        if (geometry != null) {
            if (geometry instanceof Polygon) {
                Polygon polygon = (Polygon) geometry;
                Boundary outerBoundaryIs = polygon.getOuterBoundaryIs();
                if (outerBoundaryIs != null) {
                    LinearRing linearRing = outerBoundaryIs.getLinearRing();
                    if (linearRing != null) {
                        List<Coordinate> coordinates = linearRing.getCoordinates();
                        if (coordinates != null) {
                            outerBoundaryIs = ((Polygon) geometry).getOuterBoundaryIs();
                            addPolygonToList(kmlPolygonList, name, outerBoundaryIs,description);
                        }
                    }
                }
            } else if (geometry instanceof LineString) {
                LineString lineString = (LineString) geometry;
                List<Coordinate> coordinates = lineString.getCoordinates();
                if (coordinates != null) {
                    coordinates = ((LineString) geometry).getCoordinates();
                    addLineStringToList(kmlLineList, coordinates, name,description);
                }
            } else if (geometry instanceof Point) {
                Point point = (Point) geometry;
                List<Coordinate> coordinates = point.getCoordinates();
                if (coordinates != null) {
                    coordinates = ((Point) geometry).getCoordinates();
                    addPointToList(kmlPointList, coordinates, name ,description);
                }
            } else if (geometry instanceof MultiGeometry) {
                List<Geometry> geometries = ((MultiGeometry) geometry).getGeometry();
                for (Geometry geometryToMult : geometries) {
                    Boundary outerBoundaryIs;
                    List<Coordinate> coordinates;
                    if (geometryToMult instanceof Point) {
                        coordinates = ((Point) geometryToMult).getCoordinates();
                        addPointToList(kmlPointList, coordinates, name, description);
                    } else if (geometryToMult instanceof LineString) {
                        coordinates = ((LineString) geometryToMult).getCoordinates();
                        addLineStringToList(kmlLineList, coordinates, name, description);
                    } else if (geometryToMult instanceof Polygon) {
                        outerBoundaryIs = ((Polygon) geometryToMult).getOuterBoundaryIs();
                        addPolygonToList(kmlPolygonList, name, outerBoundaryIs, description);
                    }
                }
            }
        }
    }
 
    /**
     * 将kml中所有面添加到一个list
     *
     * @return
     */
    private void addPolygonToList(List<KmlPolygon> kmlPolygonList, String name, Boundary outerBoundaryIs,String description) {
        LinearRing linearRing;
        List<Coordinate> coordinates;
        linearRing = outerBoundaryIs.getLinearRing();//面
        coordinates = linearRing.getCoordinates();
        KmlPolygon kmlPolygon = new KmlPolygon();
        kmlPolygon.setPoints(coordinates);
        kmlPolygon.setName(name);
        kmlPolygon.setDescription(description);
        kmlPolygonList.add(kmlPolygon);
    }
 
    /**
     * 将kml中所有线添加到一个list
     *
     * @return
     */
    private void addLineStringToList(List<KmlLine> kmlLineList, List<Coordinate> coordinates, String name,String description) {
        KmlLine kmlLine = new KmlLine();
        kmlLine.setPoints(coordinates);
        kmlLine.setName(name);
        kmlLine.setDescription(description);
        kmlLineList.add(kmlLine);

    }
 
    /**
     * 将kml中所有点添加到一个list
     *
     * @return
     */
    private void addPointToList(List<KmlPoint> kmlPointList, List<Coordinate> coordinates, String name,String description) {
        KmlPoint kmlPoint = new KmlPoint();
        kmlPoint.setName(name);
        kmlPoint.setPoints(coordinates);
        kmlPoint.setDescription(description);
        kmlPointList.add(kmlPoint);
    }
}

CreateFeatureJson(创建GeoJSON–这里可能有更简单方法 我这里是自己手写处理)

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Mc QiLing
 * @Date 2021/1/13 下午5:20
 * @Version 1.0
 */
public class CreateFeatureJson {

    public static String coverString(String jsonString){
        JSONObject parseObject = JSONObject.parseObject(jsonString);
        JSONObject geometry = parseObject.getObject("geometry", JSONObject.class);
        JSONArray coordinates = geometry.getJSONArray("coordinates");
        List<JSONObject> jsonObjectList = JSONObject.parseArray(coordinates.toJSONString(), JSONObject.class);
        List<List<Double>> coordinatesNew = new ArrayList<>();
        for (JSONObject jsonObject : jsonObjectList) {
            ArrayList<Double> doubles = new ArrayList<>();
            Double longitude = jsonObject.getDouble("longitude");
            if (longitude!=null) {
                doubles.add(longitude);
            }
            Double latitude = jsonObject.getDouble("latitude");
            if (latitude!=null) {
                doubles.add(latitude);
            }
            Double altitude = jsonObject.getDouble("altitude");
            if (altitude!=null) {
                doubles.add(altitude);
            }
            coordinatesNew.add(doubles);
        }
        JSONObject geometryNew = new JSONObject();
        geometryNew.put("type",geometry.get("type"));
        geometryNew.put("coordinates",coordinatesNew);

        JSONObject feature = new JSONObject();
        feature.put("type",parseObject.get("type"));
        feature.put("properties",parseObject.get("properties"));
        feature.put("geometry",geometryNew);
        return feature.toJSONString();
    }
}

UploadUtils(文件上传工具)

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Date 2021/1/14 下午3:14
 * @Version 1.0
 */
public class UploadUtils {

    public static List<String> uploadKml(List<MultipartFile> files,String folder) throws Exception {

        ArrayList<String> urlList = new ArrayList<>();

        // 绝对路径
          String projectPath = System.getProperty("user.dir");
          File fileNow = new File(projectPath);
          String strParentDirectory = fileNow.getParent() + folder;

          String fileName = null;
          // 参数为空
          File directory = new File(strParentDirectory);
          if (!directory.isDirectory()) {
            directory.mkdirs();
          }
          String s = UUID.randomUUID().toString();
          String uuid = s.substring(0, s.indexOf("-"));
          String fileUrl = null;
          for (MultipartFile file : files) {
            fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            // 创建文件夹
            // 参数为空
            String dirName = split[0];
            File fileDirectory = new File(strParentDirectory + "/" + dirName + "-" + uuid);
            if (!fileDirectory.isDirectory()) {
              fileDirectory.mkdirs();
            }
            // 获取文件后缀名
            String suffixName = split[1];
            // 重新生成文件名
            String fName = dirName + "-" + uuid + "." + suffixName;
            fileUrl = "/" + dirName + "-" + uuid + "/" + dirName + "-" + uuid;
            File dest = new File(fileDirectory, fName);
            try {
              file.transferTo(dest);
              System.out.println(fName + "上传成功!");
            } catch (IOException e) {
              System.out.println(fName + "上传异常!" + e);
            }
              String saveUrl=strParentDirectory + fileUrl + ".kml";
              urlList.add(saveUrl);
          }
          return urlList;
    }
}

CoverCoordinate(可以自定义高层值–不使用 可以不调)

import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;

/**
 * @Author Mc QiLing
 * @Date 2021/1/14 上午10:24
 * @Version 1.0
 */
public class CoverCoordinate {
    public static SimpleFeature coverCoordinateSystemAndSetHeight(Double height, SimpleFeature feature) throws TransformException, FactoryException {
        Geometry defaultGeometry = (Geometry) feature.getDefaultGeometry();
        for (Coordinate coordinate : defaultGeometry.getCoordinates()) {
            coordinate.setZ(height);
        }
        feature.setDefaultGeometry(defaultGeometry);
        return feature;
    }
}

生成MarkVO类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.paramland.geo.entity.vo.MarkVo;
import com.paramland.geo.enumn.DataSourceTypeEnum;
import com.paramland.geo.enumn.GeomCategory;
import com.paramland.geo.utils.GeoJsonUtils;
import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import org.geotools.geojson.feature.FeatureJSON;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Date 2021/1/12 上午9:51
 * @Version 1.0
 */
public class CreateMvo {

    public static  <T> List<MarkVo> createMvo(List<T> mvo, Integer type,Double height,String fromShpResource,String bid) throws IOException, TransformException, FactoryException {
        List<MarkVo> markVos = new ArrayList<>();
        for (T t : mvo) {
            MarkVo markVo = new MarkVo();
            markVo.setHeight(height);
            markVo.setFromShpResource(fromShpResource);
            markVo.setFileBid(bid);
            String name = null;
            String description = null;
            HashMap<String, Object> geometry = new HashMap<>(16);
            if(1==type){
                KmlPoint k = (KmlPoint)t;
                List<Coordinate> points = k.getPoints();
                name = k.getName();
                description = k.getDescription();
                geometry.put("type","Point");
                geometry.put("coordinates",points);
                markVo.setTagType(1);
                markVo.setBizType(1);
            }else if(2==type){
                KmlLine k = (KmlLine)t;
                name = k.getName();
                description = k.getDescription();
                List<Coordinate> points = k.getPoints();
                markVo.setTagType(2);
                geometry.put("type","LineString");
                geometry.put("coordinates",points);
                markVo.setBizType(16);
            }else if(3==type){
                KmlPolygon k = (KmlPolygon)t;
                name = k.getName();
                description = k.getDescription();
                markVo.setTagType(3);
                List<Coordinate> points = k.getPoints();
                geometry.put("type","Polygon");
                geometry.put("coordinates",points);
                markVo.setBizType(5);
            }

            JSONObject properties = new JSONObject();
            properties.put("name",name);
            properties.put("description",description);
            HashMap<String, Object> featureMap = new HashMap<>(16);
            featureMap.put("type","Feature");
            featureMap.put("geometry",geometry);
            featureMap.put("properties",properties);
            String jsonString = JSON.toJSONString(featureMap);
            if (!StringUtils.isEmpty(jsonString)) {
                String featureMapNew = CreateFeatureJson.coverString(jsonString);
                if (!StringUtils.isEmpty(featureMapNew)) {
                    FeatureJSON featureJSON = GeoJsonUtils.getFjson();
                    SimpleFeature featureNew = featureJSON.readFeature(featureMapNew);;
                    //-1000 用默认高层值
                  if (height!=-1000) {
                        SimpleFeature feature = CoverCoordinate.coverCoordinateSystemAndSetHeight(height, featureNew);
                        markVo.setFeature(feature);
                    }else{
                        Geometry defaultGeometry = (Geometry) featureNew.getDefaultGeometry();
                        double z = defaultGeometry.getCoordinate().getZ();
                        markVo.setFeature(featureNew);
                        markVo.setHeight(z);
                    }
                    markVo.setDataSource(DataSourceTypeEnum.IMPORTKML);
                    markVo.setGeomCategory(GeomCategory.PLOTTING);
                    markVos.add(markVo);
                }
            }
        }
        return markVos;
    }
}

测试

Controller 上传多个KML

@PostMapping("/uploadKml")
    public ApiResponse uploadKml(@RequestParam("files") List<MultipartFile> files ,@RequestParam("height")Double height) throws Exception {
        if (files.isEmpty()) {
            return new ApiResponse();
        }
        List<String> strings = UploadUtils.uploadKml(files, "/kml");
      	//service处理
        ApiResponse apiResponse = iImportShapefile.importKmlFile(strings,height);
        int errorCode = apiResponse.getErrorCode();
        if(errorCode==200){
            for (String str : strings) {
                File file = new File(str);
                deleteDir(file);
            }
        }
        apiResponse.setData(strings);
        return apiResponse;
    }

服务类(service)

@Override
public ApiResponse importKmlFile(List<String> strings, double height) {
  ArrayList<MarkVo> markVos = new ArrayList<>();
  try {
    for (String string : strings) {
      String substring = string.substring(string.lastIndexOf("/") + 1);
      String[] split = substring.split("\\.");
      ImportFile importFile = new ImportFile();
      importFile.setFileType(split[1]);
      importFile.setFileName(split[0]);
      importFile.setFileUrl(string);
      importFile.setIsDelete(1);
      importFile.setIsResolved(1);
      importFileService.save(importFile);
      String bid = importFile.getBid();
      List<MarkVo> markVo = getMarkVo(string,split[0],height,bid);
      markVos.addAll(markVo);
    }
    //保存到数据库
    mapGeometryService.transformAndSave(markVos, height);
    return ApiResponse.success();
  } catch (TransformException | FactoryException | IOException e) {
    e.printStackTrace();
    return ApiResponse.error(e.toString());
  }

}
private List<MarkVo> getMarkVo(String url,String fromShpResource,double height,String bid) throws TransformException, FactoryException, IOException {
      KmlProperty kmlProperty;
      ParsingKmlUtil parsingKmlUtil =new ParsingKmlUtil();
      File file = new File(url);
      kmlProperty = parsingKmlUtil.parseKmlForJAK(file);
      List<KmlPoint> kmlPoints = kmlProperty.getKmlPoints();
      List<KmlLine> kmlLines = kmlProperty.getKmlLines();
      List<KmlPolygon> kmlPolygons = kmlProperty.getKmlPolygons();
      ArrayList<MarkVo> allMarkVos = new ArrayList<>();
      if(kmlPoints!=null && !kmlPoints.isEmpty()){
        List<MarkVo> mvo = CreateMvo.createMvo(kmlPoints, 1,height,fromShpResource,bid);
        allMarkVos.addAll(mvo);
      }
      if(kmlLines!=null && !kmlLines.isEmpty()){
        List<MarkVo> mvo = CreateMvo.createMvo(kmlLines, 2,height,fromShpResource,bid);
        allMarkVos.addAll(mvo);
      }
      if(kmlPolygons!=null && !kmlPolygons.isEmpty()){
        List<MarkVo> mvo = CreateMvo.createMvo(kmlPolygons, 3,height,fromShpResource,bid);
        allMarkVos.addAll(mvo);
      }
      return allMarkVos;
    }

数据库表设计

CREATE TABLE "public"."tagging_info" (
  "id" int4 NOT NULL DEFAULT nextval('seq_tagging_info'::regclass),
  "create_time" timestamp(6) NOT NULL,
  "update_time" timestamp(6) NOT NULL,
  "version" int4 NOT NULL,
  "bid" varchar(64) COLLATE "pg_catalog"."default" NOT NULL,
  "company_id" int4,
  "project_id" int4,
  "application_id" int4,
  "tag_type" int4,
  "geom" "public"."geometry",
  "centroid" "public"."geometry",
  "central_point" varchar(255) COLLATE "pg_catalog"."default",
  "height" float8,
  "area" float8,
  "volume" float8,
  "line_length" float8,
  "correlated" int2,
  "correlated_cnt" int4,
  "data_source" int4 DEFAULT 1,
  "biz_type" int4 DEFAULT 1,
  "is_permanent" int2 DEFAULT 0,
  "geom_offset" json,
  "from_shp_resource" varchar(255) COLLATE "pg_catalog"."default",
  "dbf_property" text COLLATE "pg_catalog"."default",
  "file_bid" varchar(64) COLLATE "pg_catalog"."default",
  "categories" int4,
  "properties" json,
  CONSTRAINT "tagging_info_pkey" PRIMARY KEY ("id"),
  CONSTRAINT "tagging_info_u_bid" UNIQUE ("bid")
)
;

ALTER TABLE "public"."tagging_info" 
  OWNER TO "postgres";
COMMENT ON COLUMN "public"."tagging_info"."id" IS '主键';
COMMENT ON COLUMN "public"."tagging_info"."create_time" IS '创建时间';
COMMENT ON COLUMN "public"."tagging_info"."update_time" IS '更新时间';
COMMENT ON COLUMN "public"."tagging_info"."version" IS '乐观锁';
COMMENT ON COLUMN "public"."tagging_info"."bid" IS '业务主键';
COMMENT ON COLUMN "public"."tagging_info"."company_id" IS '公司id';
COMMENT ON COLUMN "public"."tagging_info"."project_id" IS '项目id';
COMMENT ON COLUMN "public"."tagging_info"."application_id" IS '应用id';
COMMENT ON COLUMN "public"."tagging_info"."tag_type" IS '标注图形类型,1:POINT点,2:LINESTRING线串,3:POLYGON多边形,4:MULTIPOINT多个点,5:MULTILINESTRING多个线串,6:MULTIPOLYGON多个多边形,7:GEOMETRYCOLLECTION几何集合,8:包围盒,9:体';
COMMENT ON COLUMN "public"."tagging_info"."geom" IS '标注POI几何信息';
COMMENT ON COLUMN "public"."tagging_info"."centroid" IS '形心';
COMMENT ON COLUMN "public"."tagging_info"."central_point" IS '中心点';
COMMENT ON COLUMN "public"."tagging_info"."height" IS '高度,类型为包围盒有高度';
COMMENT ON COLUMN "public"."tagging_info"."area" IS '面积';
COMMENT ON COLUMN "public"."tagging_info"."volume" IS '体积';
COMMENT ON COLUMN "public"."tagging_info"."line_length" IS '长度';
COMMENT ON COLUMN "public"."tagging_info"."correlated" IS '是否已经关联1是0否';
COMMENT ON COLUMN "public"."tagging_info"."correlated_cnt" IS '关联次数';
COMMENT ON COLUMN "public"."tagging_info"."data_source" IS '数据来源 1:标绘 2:shape文件导入';
COMMENT ON COLUMN "public"."tagging_info"."biz_type" IS '业务类型,1:标绘,2:测量,3:压平,4:模型';
COMMENT ON COLUMN "public"."tagging_info"."is_permanent" IS '是否永久显示,1是0否';
COMMENT ON COLUMN "public"."tagging_info"."geom_offset" IS 'POI图形偏移量';
COMMENT ON COLUMN "public"."tagging_info"."from_shp_resource" IS '来源哪一张shp表';
COMMENT ON COLUMN "public"."tagging_info"."dbf_property" IS '对应的属性及其属性值';
COMMENT ON COLUMN "public"."tagging_info"."file_bid" IS '关联文件bid';
COMMENT ON COLUMN "public"."tagging_info"."categories" IS '分类:1:标绘,2:空间分析';
COMMENT ON COLUMN "public"."tagging_info"."properties" IS '画图属性参数,JSON格式';
COMMENT ON TABLE "public"."tagging_info" IS '标注POI信息表';

总结:

这个是第一个版本 写个个人感觉 太复杂 也许还有更好的方法 批量处理KML 将多类型存入数据库 希望提出和交流

本文地址:https://blog.csdn.net/Mclaughling/article/details/112860974

相关标签: KML GeoTools java