arcgis解析CAD (dwg) 转为geojson

利用Arcgis解析dwg格式的CAD返回geojson,现在只解析了CAD中的点、线、面、圆、标注,其他类型因项目暂时未使用就没有兼容,并且样式颜色都是写死的(可根据feature中的参数属性配置颜色,但参数属性中显示的大部分是CAD色谱中的颜色),可根据实际情况自己修改,这边只是提供一个思路。

feature中的参数属性说明,Arcgis 为 AutoCAD DWG/DXF 格式保留的 CAD 字段说明

安装arcgis

本地安装的是10.5版本 32位的
jdk 32位

项目配置

依赖

        <dependency>
            <groupId>com.esri.arcgisgroupId>
            <artifactId>arcobjectsartifactId>
            <version>1.0.0version>
        dependency>

下载jar包 :arcobjects-1.0.0 提取码:moqp

接口


    @Value("${sys.prj.url}")
    private String prjUrl;

    @ValidMethod
    @ApiOperation(value = "cad转换", response = JsonResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "文件类型 CAD/SHP", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "epsg", value = "投影坐标代码(4490_4527: CGCS 2000 39  4490_4509: CGCS 2000 117)", dataType = "string", paramType = "query")
    })
    @PostMapping(value = "/cadShpToJson", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JsonResponse cadShpToJson(@RequestParam(name = "file") MultipartFile files, String type, String epsg, HttpServletRequest request) {
        List list = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        String uploadpath = "";
        try {
            if ("CAD".equals(type)) {
                /** 构建文件保存的目录* */
                uploadpath = request.getSession().getServletContext().getRealPath("").concat("leping\\CAD\\" + new Date().getTime() + "\\");
                String fileName = files.getOriginalFilename();//获取原始文件名
                File targetFile = new File(uploadpath, fileName);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdirs();
                    targetFile.createNewFile();
                }
                files.transferTo(targetFile);
                // 解析epsg
                String prjPath = null;
                String epsgPath = prjUrl + "4490.prj";
                if (fileName.endsWith("zip")) {
                    CompressFileUits.unZipFiles(targetFile, uploadpath);
                } else if (fileName.endsWith("rar")) {
                    CompressFileUits.unRarFile(uploadpath + fileName, uploadpath);
                } else {
                    if (StringUtils.isEmpty(epsg)){
                        return JsonResponse.error(Code.CAD_NO_PRJ_ERROR);
                    }
                    String[] split = epsg.split("_");
                    prjPath = prjUrl + split[1] + ".prj";
                    epsgPath = prjUrl + split[0] + ".prj";
                    String copyPrjPath = uploadpath + fileName.substring(0, fileName.lastIndexOf(".") )+".prj";
                    // 如果是单个dwg文件,就复制一份相同名字且以prj结尾的投影文件到相同目录下
                    FileUtils.appendFile(new FileInputStream(new File(prjPath)),new File(copyPrjPath));
                }
                //  CompressFileUits.doDeleteEmptyDir(uploadpath + fileName);
                List<File> fileList = CompressFileUits.getFileList(uploadpath, "dwg");
                if (fileList.size() > 1) {
                    uploadpath = uploadpath + fileName.substring(0, fileName.lastIndexOf("."));
                }
                for (File file : fileList) {
                    jsonObject = FileUtils.cadToJson(uploadpath, file.getName(),epsgPath);
                    list.add(jsonObject);
                }

            } else if ("SHP".equals(type)) {
                /** 构建文件保存的目录* */
                uploadpath = request.getSession().getServletContext().getRealPath("").concat("leping\\SHP\\" + new Date().getTime() + "\\");
                String fileName = files.getOriginalFilename();//获取原始文件名
                File targetFile = new File(uploadpath, fileName);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdirs();
                    targetFile.createNewFile();
                }
                files.transferTo(targetFile);
                if (fileName.endsWith("zip")) {
                    CompressFileUits.unZipFiles(targetFile, uploadpath);
                } else if (fileName.endsWith("rar")) {
                    CompressFileUits.unRarFile(uploadpath + fileName, uploadpath);
                }
                List<File> fileList = CompressFileUits.getFileList(uploadpath, "shp");
                if (!CollectionUtils.isEmpty(fileList)) {
                    String filename = fileList.get(0).getName();
                    String path = fileList.get(0).getParentFile().getAbsolutePath() + "\\";
                    jsonObject = FileUtils.shpToGeojson(path, filename);
                    list.add(jsonObject);
                }
            }
            CompressFileUits.delFolder(uploadpath);
            return JsonResponse.success(list);
        } catch (ServiceException e) {
            LogUtils.error(e.getMessage(), e);
            return JsonResponse.error(e.getCode(),e.getMessage());
        } catch (IOException e) {
            LogUtils.error(e.getMessage(), e);
            return JsonResponse.error(Code.CAD_TO_GEOJSON_ERROR);
        } catch (Exception e) {
            LogUtils.error(e.getMessage(), e);
            return JsonResponse.error(Code.CAD_TO_GEOJSON_ERROR);
        }
    }

FileUtils

package com.tuxin.data.util;


import com.alibaba.fastjson.JSONObject;
import com.esri.arcgis.datasourcesfile.CadWorkspaceFactory;
import com.esri.arcgis.geodatabase.*;
import com.esri.arcgis.geometry.*;
import com.esri.arcgis.system.EngineInitializer;
import com.tuxin.common.common.constants.Code;
import com.tuxin.common.common.exception.ServiceException;
import com.tuxin.common.common.response.JsonResponse;
import com.tuxin.common.util.LogUtils;
import com.tuxin.common.util.StringUtils;
import org.springframework.util.CollectionUtils;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.*;


/**
 * Created by Administrator on 2018/9/13.
 */
public class FileUtils {

    private static final int BUFFER_SIZE = 100 * 1024;

    // private ExecutorService compressConvertExecutor = Executors.newFixedThreadPool(10);

    /**
     * cad转geojson
     *
     * @param workSpacePath :
     * @param dwgFileName   :
     * @param epsgPath      :
     * @return : com.alibaba.fastjson.JSONObject
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:37
     */
    public static JSONObject cadToJson(String workSpacePath, String dwgFileName, String epsgPath) throws IOException, ServiceException {
        // 判断是否有投影文件
        String prjPath = workSpacePath + dwgFileName.substring(0, dwgFileName.lastIndexOf(".")) + ".prj";
        File prjFile = new File(prjPath);
        if (!prjFile.exists()) {
            throw new ServiceException(Code.CAD_NO_PRJ_FILE_ERROR);
        }
        // 初始化arcgis
        EngineInitializer.initializeEngine();
        // 打开cad
        CadWorkspaceFactory pWorkspaceFactory = new CadWorkspaceFactory();
        IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace) pWorkspaceFactory.openFromFile(workSpacePath, 0);
        pFeatureWorkspace.openFeatureDataset(dwgFileName);
        // 获取
        IFeatureClass polygon = pFeatureWorkspace.openFeatureClass(dwgFileName + ":Polygon");
        IFeatureClass polyline = pFeatureWorkspace.openFeatureClass(dwgFileName + ":Polyline");
        IFeatureClass point = pFeatureWorkspace.openFeatureClass(dwgFileName + ":Point");
        IFeatureClass annotation = pFeatureWorkspace.openFeatureClass(dwgFileName + ":Annotation");
        // 实体唯一标识集合(去除重复的数据)
        List<String> handleList = new ArrayList<>();
        // 获取坐标系
        ISpatialReferenceFactory ispReferenceFactory = new SpatialReferenceEnvironment();
        ISpatialReference spatialReference = ispReferenceFactory.createESRISpatialReferenceFromPRJFile(epsgPath);
        // 获取标注信息
        Map<Point, Map<String, Object>> annoPointList = loadingAnnotation(annotation, handleList, spatialReference);
        // 获取点线面
        List<Map> featuresList = new ArrayList();
        featuresList.addAll(loadingPolygon(polygon, annoPointList, handleList, spatialReference));
        featuresList.addAll(loadingPolyline(polyline, annoPointList, handleList, spatialReference));
        featuresList.addAll(loadingPoint(point, handleList, spatialReference));
        // 构建geojson
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        jsonObject.put("features", featuresList);
        return jsonObject;
    }


    /**
     * 构建properties
     *
     * @return : java.util.Map
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:52
     */
    private static Map<String, Object> makeBaseProperties() {
        Map<String, Object> properties = new HashMap();
        properties.put("polygonType", "polygon");
        properties.put("fill", "#ffffff");
        properties.put("fill-opacity", 0.5);
        properties.put("stroke-width", 2);
        properties.put("stroke-opacity", 1);
        properties.put("stroke", "#408080");
        properties.put("name", "");
        return properties;
    }

    /**
     * 获取feature的参数属性
     *
     * @param feature :
     * @return : java.util.Map
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:59
     */
    private static Map<String, String> getFieldsByFeature(IFeature feature) throws IOException {
        IFields fields = feature.getFields();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < fields.getFieldCount(); i++) {
            IField field = fields.getField(i);
            map.put(field.getName(),feature.getValue(i).toString());
            LogUtils.info(field.getName() + ":" + feature.getValue(i).toString());
            /*if ("Handle".equals(field.getName())) {
                map.put("Handle", feature.getValue(i).toString());
            }
            if ("Entity".equals(field.getName())) {
                map.put("Entity", feature.getValue(i).toString());
            }*/
        }
        return map;
    }

    /**
     * 解析标注信息
     *
     * @param layer      :
     * @param handleList :
     * @return : java.util.Map>
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:42
     */
    public static Map<Point, Map<String, Object>> loadingAnnotation(IFeatureClass layer, List<String> handleList,
                                                                    ISpatialReference spatialReference) throws IOException {
        Map<Point, Map<String, Object>> map = new HashMap<>();
        for (int m = 1; m <= layer.featureCount(null); ++m) {
            IFeature feature = layer.getFeature(m);
            if (null == feature) {
                continue;
            }
            Point point = (Point) feature.getShape();
            point.project(spatialReference);
            Fields fields = (Fields) feature.getFields();
            Map<String, Object> properties = new HashMap();
            String handle = null;
            for (int i = 0; i < fields.getFieldCount(); i++) {
                IField field = fields.getField(i);
                String name = field.getName();
                if ("Handle".equals(name)) {
                    handle = feature.getValue(i).toString();
                }
                if ("Text".equals(name) || "Entity".equals(name) || "Handle".equals(name)
                        || "Layer".equals(name) || "RefName".equals(name)) {
                    properties.put(name, feature.getValue(i));
                }
            }
            if (handleList.contains(handle)) {
                continue;
            }
            handleList.add(handle);
            map.put(point, properties);
        }
        return map;
    }

    /**
     * 解析面
     *
     * @param layer            :
     * @param annoPointMap     :
     * @param handleList       :
     * @param spatialReference :
     * @return : java.util.List
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:52
     */
    public static List<Map> loadingPolygon(IFeatureClass layer, Map<Point, Map<String, Object>> annoPointMap,
                                           List<String> handleList, ISpatialReference spatialReference) throws IOException {
        List<Map> featuresList = new ArrayList();
        for (int m = 1; m <= layer.featureCount(null); ++m) {
            IFeature feature = layer.getFeature(m);
            if (feature == null) {
                continue;
            }
            Map<String, String> fieldsMap = getFieldsByFeature(feature);
            String handle = fieldsMap.get("Handle");
            String entity = fieldsMap.get("Entity");
            // 判断实体唯一标识是否存在,如果该对象存在则跳过此次添加
            if (handleList.contains(handle)) {
                continue;
            }
            handleList.add(handle);
            // 构建geojson
            Map<String, Object> featuremap = new HashMap();
            featuremap.put("type", "Feature");
            Map<String, Object> properties = makeBaseProperties();
            featuremap.put("properties", properties);
            Map<String, Object> geometry = new HashMap();
            geometry.put("type", "Polygon");
            List coordinates = new ArrayList();
            // 转换为面
            Polygon polygon = (Polygon) feature.getShape();
            polygon.project(spatialReference);
            if (polygon.getPointCount() == 0) {
                continue;
            }
            // 判断是否为圆
            if (StringUtils.isNotEmpty(entity) && "Circle".equals(entity)) {
                coordinates = HandleFeatureUtils.handleCircle(polygon);
                properties.put("isCircle", true);
            } else {
                coordinates = HandleFeatureUtils.handlePolygonOrPolyline(polygon);
            }
            // 如果坐标集合为空,则跳过该条数据
            if (CollectionUtils.isEmpty(coordinates)) {
                continue;
            }
            geometry.put("coordinates", coordinates);
            featuremap.put("geometry", geometry);
            featuresList.add(featuremap);

            // 判断标注点信息是否在该面中
            if (CollectionUtils.isEmpty(annoPointMap)) {
                continue;
            }
            Set<Map.Entry<Point, Map<String, Object>>> entries = annoPointMap.entrySet();
            for (Map.Entry<Point, Map<String, Object>> entry : entries) {
                Point point = entry.getKey();
                if (polygon.contains(point)) {
                    properties.putAll(entry.getValue());
                    featuremap.put("properties", properties);
                    break;
                }
            }
        }
        return featuresList;
    }

    /**
     * 解析线
     *
     * @param layer            :
     * @param annoPointMap     :
     * @param handleList       :
     * @param spatialReference :
     * @return : java.util.List
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:51
     */
    public static List<Map> loadingPolyline(IFeatureClass layer, Map<Point, Map<String, Object>> annoPointMap,
                                            List<String> handleList, ISpatialReference spatialReference) throws IOException {
        List<Map> featuresList = new ArrayList();
        for (int m = 1; m <= layer.featureCount(null); ++m) {
            IFeature feature = layer.getFeature(m);
            if (null == feature) {
                continue;
            }

            Map<String, Object> featuremap = new HashMap();
            Map<String, Object> properties = makeBaseProperties();
            featuremap.put("type", "Feature");
            properties.put("polygonType", "Polyline");
            featuremap.put("properties", properties);
            Map<String, Object> geometry = new HashMap();
            geometry.put("type", "MultiLineString");

            Map<String, String> fieldsMap = getFieldsByFeature(feature);
            String handle = fieldsMap.get("Handle");
            String entity = fieldsMap.get("Entity");
            if (handleList.contains(handle)) {
                continue;
            }
            handleList.add(handle);

            List coordinates = new ArrayList();
            Polyline polyline = (Polyline) feature.getShape();
            polyline.project(spatialReference);
            if (polyline.getPointCount() == 0) {
                continue;
            }

            if (StringUtils.isNotEmpty(entity) && "Circle".equals(entity)) {
                coordinates = HandleFeatureUtils.handleCircle(polyline);
            } else {
                coordinates = HandleFeatureUtils.handlePolygonOrPolyline(polyline);
            }
            if (CollectionUtils.isEmpty(coordinates)) {
                continue;
            }
            geometry.put("coordinates", coordinates);
            featuremap.put("geometry", geometry);
            featuresList.add(featuremap);
            // 判断标注点信息是否在该面中
            if (CollectionUtils.isEmpty(annoPointMap)) {
                continue;
            }
            Set<Map.Entry<Point, Map<String, Object>>> entries = annoPointMap.entrySet();
            for (Map.Entry<Point, Map<String, Object>> entry : entries) {
                Point point = entry.getKey();
                if (polyline.contains(point)) {
                    properties.putAll(entry.getValue());
                    featuremap.put("properties", properties);
                    break;
                }
            }
        }
        return featuresList;
    }

    /**
     * 解析点
     *
     * @param layer            :
     * @param handleList       :
     * @param spatialReference :
     * @return : java.util.List
     * @author zfxiang [[email protected]]
     * @date 2020/6/9 10:51
     */
    public static List<Map> loadingPoint(IFeatureClass layer, List<String> handleList, ISpatialReference spatialReference) throws IOException {
        List<Map> featuresList = new ArrayList();
        for (int m = 1; m <= layer.featureCount(null); ++m) {
            IFeature feature = layer.getFeature(m);
            if (feature == null) {
                continue;
            }
            Map<String, String> fieldsMap = getFieldsByFeature(feature);
            String handle = fieldsMap.get("Handle");
            if (handleList.contains(handle)) {
                continue;
            }
            handleList.add(handle);
            Map<String, Object> featuremap = new HashMap();
            featuremap.put("type", "Feature");
            Map<String, Object> properties = makeBaseProperties();
            properties.put("polygonType", "point");
            featuremap.put("properties", properties);
            Map<String, Object> geometry = new HashMap();
            IGeometry shape = feature.getShape();
            shape.project(spatialReference);
            List coordinates = HandleFeatureUtils.handlePoint(shape);
            if (CollectionUtils.isEmpty(coordinates)) {
                continue;
            }
            geometry.put("type", "Point");
            geometry.put("coordinates", coordinates);
            featuremap.put("geometry", geometry);
            featuresList.add(featuremap);
        }
        return featuresList;
    }

    public static void appendFile(InputStream in, File destFile) throws IOException {
        OutputStream out = null;
        try {
            // plupload 配置了chunk的时候新上传的文件append到文件末尾
            if (destFile.exists()) {
                out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE);
            } else {
                out = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE);
            }
            in = new BufferedInputStream(in, BUFFER_SIZE);

            int len = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                LogUtils.error(e.getMessage(), e);
            }
        }
    }

    public static InputStream base64ToInputStream(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new ByteArrayInputStream(b);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static JsonResponse geojsonToShp(String shpFilePath, String uuid, String geojsonStr) throws IOException, InterruptedException {

        String geojsonPath = shpFilePath + "\\" + uuid + ".geojson";
        File file = new File(geojsonPath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(geojsonStr);
        out.close();

        Runtime rt = Runtime.getRuntime();
        String cmd = "ogr2ogr -f \"ESRI Shapefile\" " + shpFilePath + " " + geojsonPath;
        Process p = rt.exec(cmd);
        Thread.sleep(1000);

        if (!shpFilePath.endsWith("\\")) {
            shpFilePath = shpFilePath + "\\";
        }
        String zipPath = shpFilePath + uuid + ".zip";
        FileOutputStream fos1 = new FileOutputStream(new File(zipPath));
        List<File> pathList = new ArrayList<>();

        pathList.add(new File(shpFilePath + uuid + ".dbf"));
        pathList.add(new File(shpFilePath + uuid + ".prj"));
        pathList.add(new File(shpFilePath + uuid + ".shp"));
        pathList.add(new File(shpFilePath + uuid + ".shx"));
        CompressFileUits.toZip(pathList, fos1);
        JSONObject data = new JSONObject();
        data.put("zipPath", zipPath);
        file.delete();

        return JsonResponse.success(data);
    }


    private static void geo2shp(String shpFilePath,
                                String geojsonPath) {
        String picCommend = "ogr2ogr -f \"ESRI Shapefile\" " + shpFilePath
                + " " + geojsonPath;
        runCmd(picCommend);
    }

    private static void runCmd(String command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("");
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("");
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            System.out.println(t);
            t.printStackTrace();
        }

    }

    public static JSONObject shpToGeojson(String workSpacePath, String shpFileName) throws IOException {
        String filename = shpFileName.substring(0, shpFileName.lastIndexOf("."));
        //使用gdal的工具,执行cmd命令
        Runtime rt = Runtime.getRuntime();
        String cmd = "ogr2ogr -t_srs EPSG:4326 -f GeoJson " + workSpacePath + filename + ".geojson" + " " + workSpacePath + shpFileName;
        Process p = rt.exec(cmd);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        File file = new File(workSpacePath + filename + ".geojson");
        String text = org.apache.commons.io.FileUtils.readFileToString(file, "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(text);
        return jsonObject;
    }

//    public static void main(String[] args) throws IOException, InterruptedException {
//
////        String geojsonStr = "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[10.781662469505527,58.99727341375908,0],[10.782110957068376,58.99717187847401,0],[10.782174283542597,58.99681031168689,1.3222238854040097e-9],[10.78180984509706,58.99681275056772,9.313225746154785e-10],[10.781519467071563,58.996839782937315,9.313225746154785e-10],[10.781436643701255,58.99701867044865,9.313225746154785e-10],[10.781341118892644,58.99714725688093,9.313225746154785e-10]]]}}]}";
////        String shpFilePath = "e:\\test";
////        String uuid = UUID.randomUUID().toString();
////        geojsonToShp(shpFilePath, uuid, geojsonStr);
//        String workSpacePath = "C:\\Users\\admin\\Desktop\\";
//        String filename = "33ff8780-8c8c-45b1-a933-685e1284e9f4";
//        JSONObject jsonObject = shpToGeojson(workSpacePath, filename);
//        System.out.println("转换成功!" );
//    }
}

HandleFeatureUtils

package com.tuxin.data.util;

import com.esri.arcgis.geometry.*;
import org.springframework.util.CollectionUtils;

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

/**
 * @author zfxiang 
 * @version v1.0
 * @className HandleFeatureUtils
 * @description 处理feature工具类
 * @date 2020/6/8 9:56
 */
public class HandleFeatureUtils {

    /**
     * 解析圆:通过中心点获取圆弧上的36个点
     * @author zfxiang [[email protected]]
     * @date 2020/6/8 10:47
     * @param circularArc :
     * @return : java.util.List>
     */
    public static List<List<Double[]>> handleCircle(IGeometry geometry) throws IOException {
        List<Double[]> coordinatesList = new ArrayList();
        List<List<Double[]>> coordinates = new ArrayList();
        ISegmentCollection iSegmentCollection = (ISegmentCollection)geometry;
        int segmentCount = iSegmentCollection.getSegmentCount();
        for(int a = 0; a < segmentCount; ++a) {
            CircularArc circularArc = (CircularArc)iSegmentCollection.getSegment(a);
            for(int i = 0; i < 36; ++i) {
                Double x = circularArc.getCenterPoint().getX() + circularArc.getRadius() * Math.sin(0.017453292519943295D * (double)i * 10.0D);
                Double y = circularArc.getCenterPoint().getY() + circularArc.getRadius() * Math.cos(0.017453292519943295D * (double)i * 10.0D);
                Double[] strArr = new Double[]{x, y, 0.0D};
                coordinatesList.add(strArr);
            }
            Double x = circularArc.getCenterPoint().getX() + circularArc.getRadius() * Math.sin(0.0D);
            Double y = circularArc.getCenterPoint().getY() + circularArc.getRadius() * Math.cos(0.0D);
            Double[] strArr = new Double[]{x, y, 0.0D};
            coordinatesList.add(strArr);
        }

        if (!CollectionUtils.isEmpty(coordinatesList)) {
            coordinates.add(coordinatesList);
        }
        return coordinates;
    }

    /**
     * 解析面或线
     * @author zfxiang [[email protected]]
     * @date 2020/6/8 10:48
     * @param geometry :
     * @return : java.util.List>
     */
    public static List<List<Double[]>> handlePolygonOrPolyline(IGeometry geometry) throws IOException{
        IGeometryCollection geometryCollection = null;
        if (geometry instanceof  Polygon){
            geometryCollection = (Polygon)geometry;
        } else if (geometry instanceof Polyline){
            geometryCollection = (Polyline)geometry;
        }
       // IGeometryCollection geometryCollection = feature;
        List<List<Double[]>> coordinates = new ArrayList();
        for(int a = 0; a < geometryCollection.getGeometryCount(); ++a) {
            IPointCollection pointCollection = (IPointCollection)geometryCollection.getGeometry(a);
            List<Double[]> pointCoordinatesList = new ArrayList();
            for(int b = 0; b < pointCollection.getPointCount(); ++b) {
                IPoint point = pointCollection.getPoint(b);
                Double x = point.getX();
                Double y = point.getY();
                Double[] strArr = new Double[]{x, y, 0.0D};
                pointCoordinatesList.add(strArr);
            }
            if (CollectionUtils.isEmpty(pointCoordinatesList)){
                return coordinates;
            }
            coordinates.add(pointCoordinatesList);
        }
        return coordinates;
    }

    /**
     * 解析点
     * @author zfxiang [[email protected]]
     * @date 2020/6/8 10:48
     * @param geometry :
     * @return : java.util.List>
     */
    public static  List<List<Double[]>> handlePoint(IGeometry geometry) throws IOException{
        List<Double[]> coordinatesList = new ArrayList();
        List<List<Double[]>> coordinates = new ArrayList();
        if (geometry instanceof Point) {
            Point point = (Point)geometry;
            if (null != point && !point.isEmpty()) {
                Double X = point.getX();
                Double Y = point.getY();
                Double[] strArr = new Double[]{X, Y, 0.0D};
                coordinatesList.add(strArr);
                coordinates.add(coordinatesList);
            }
        } else {
            Multipoint polygon = (Multipoint)geometry;
            if (polygon.getPointCount() != 0) {
                for(int n = 0; n < polygon.getPointCount(); ++n) {
                    IPoint point = polygon.getPoint(n);
                    Double x = point.getX();
                    Double y = point.getY();
                    Double[] strArr = new Double[]{x, y, 0.0D};
                    coordinatesList.add(strArr);
                }

                if (CollectionUtils.isEmpty(coordinatesList)) {
                    coordinates.add(coordinatesList);
                }
            }
        }
        return coordinates;
    }

}

下载 投影文件 提取码:r6zx

说明:如果上传CAD数据为压缩包,则压缩包中必须包含prj投影文件,如果上传的是单个DWG文件,则调用接口是必需选择投’影坐标代码’

注:如果dwg太大不建议使用Java解析,很占内存,可以使用c#

你可能感兴趣的:(CAD,dwg)