Java shp 转 GeoJson

1. 依赖安装

1.1 配置软件源

在项目 pom.xml 添加,
maven 的 settings.xml 配置的源,mirrorOf 不能是 *,不然安装不上

<project>
	...
    <repositories>
        <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>
        <repository>
            <id>osgeo-snapshot</id>
            <name>OSGeo Snapshot Repository</name>
            <url>https://repo.osgeo.org/repository/snapshot/</url>
            <snapshots><enabled>true</enabled></snapshots>
            <releases><enabled>false</enabled></releases>
        </repository>
    </repositories>
</project>

1.2 引入依赖

geotools 29及以上的版本需要 jdk 11

<project>
...
	
    <properties>
	    ...
        <geotools.version>28.5</geotools.version>
    </properties>

	<dependencies>
		...
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>${geotools.version}</version>
        </dependency>
    </dependencies>
</project>

2. 功能实现

// 新版本 FeatureSource 的包路径有变化,根据IDE提示导入即可
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.geojson.feature.FeatureJSON;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;

public class GeoTools {

    /**
     *
     * @param shpFile .shp 文件路径
     * @return
     * @throws IOException
     */
    public static String shpToJsonString(String shpFile) throws IOException {
        ShapefileDataStore dataStore = new ShapefileDataStore(new File(shpFile).toURI().toURL());
		
		// 处理中文乱码
        dataStore.setCharset(Charset.forName("GBK"));
        
        FeatureSource featureSource = dataStore.getFeatureSource();

        FeatureJSON featureJSON = new FeatureJSON();
        String result = null;
        try (StringWriter writer = new StringWriter()) {
            featureJSON.writeFeatureCollection(featureSource.getFeatures(), writer);
            result = writer.toString();
        }

        return result;
    }
}

3. 参考链接

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
非常抱歉,作为AI语言模型,我没有直接的能力进行Java程序设计和运行。但是,您可以使用Java库来实现dxf到shp换。以下是一些可能会对您有帮助的Java库和示例: 1. GeoTools - 一个用于处理地理空间数据的开源Java库,可以处理dxf和shp格式。它提供了很多示例代码和文档。 2. JTS Topology Suite - 一个用于处理地理空间数据的Java库,也可以处理dxf和shp格式。它提供了许多示例代码和文档。 3. GDAL - 一个用于处理各种地理空间数据格式的C++/Java库,支持dxf和shp格式。它还提供了Java接口和示例代码。 使用这些库,您可以编写Java代码来实现dxf到shp换。以下是一个基本的示例代码使用GeoTools库: ``` import org.geotools.data.*; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geometry.jts.JTSFactoryFinder; import org.locationtech.jts.geom.*; import org.locationtech.jts.io.WKTReader; import org.locationtech.jts.io.WKTWriter; import org.opengis.feature.simple.*; import org.opengis.feature.type.*; import java.io.*; import java.util.*; import java.util.zip.*; import org.w3c.dom.*; import javax.xml.parsers.*; import java.nio.charset.Charset; public class DxfToShpConverter { private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); public static void main(String[] args) { String dxfFileName = "input.dxf"; String shpFileName = "output.shp"; try { SimpleFeatureCollection features = getFeaturesFromDxf(dxfFileName); writeFeaturesToShp(features, shpFileName); System.out.println("Conversion completed successfully!"); } catch (Exception e) { System.out.println("Error during conversion: " + e.getMessage()); } } private static SimpleFeatureCollection getFeaturesFromDxf(String dxfFileName) throws Exception { SimpleFeatureType featureType = createFeatureType(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); FileInputStream fis = new FileInputStream(dxfFileName); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis); ZipEntry entry = zis.getNextEntry(); while (entry != null) { String fileName = entry.getName(); if (fileName.endsWith(".xml") && entry.getSize() > 0) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(zis); Node node = doc.getElementsByTagName("Entities").item(0); NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) childNode; if (element.getNodeName().equals("Line")) { LineString lineString = createLineStringFromElement(element); featureBuilder.add(lineString); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } else if (element.getNodeName().equals("Circle")) { Polygon polygon = createPolygonFromCircleElement(element); featureBuilder.add(polygon); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } // add more cases for other entities } } } entry = zis.getNextEntry(); } zis.close(); SimpleFeatureCollection featureCollection = DataUtilities.collection(features); return featureCollection; } private static LineString createLineStringFromElement(Element element) { Coordinate[] coordinates = new Coordinate[2]; String startX = element.getAttribute("StartX"); String startY = element.getAttribute("StartY"); String endX = element.getAttribute("EndX"); String endY = element.getAttribute("EndY"); coordinates[0] = new Coordinate(Double.parseDouble(startX), Double.parseDouble(startY)); coordinates[1] = new Coordinate(Double.parseDouble(endX), Double.parseDouble(endY)); LineString lineString = geometryFactory.createLineString(coordinates); return lineString; } private static Polygon createPolygonFromCircleElement(Element element) { String centerX = element.getAttribute("CenterX"); String centerY = element.getAttribute("CenterY"); String radius = element.getAttribute("Radius"); Coordinate centerCoordinate = new Coordinate(Double.parseDouble(centerX), Double.parseDouble(centerY)); double radiusValue = Double.parseDouble(radius); Polygon circlePolygon = createCirclePolygon(centerCoordinate, radiusValue); return circlePolygon; } private static Polygon createCirclePolygon(Coordinate center, double radius) { int numPoints = 32; Coordinate[] coordinates = new Coordinate[numPoints + 1]; for (int i = 0; i < numPoints; i++) { double angle = ((double) i / (double) numPoints) * Math.PI * 2.0; double x = radius * Math.cos(angle) + center.x; double y = radius * Math.sin(angle) + center.y; coordinates[i] = new Coordinate(x, y); } coordinates[numPoints] = coordinates[0]; LinearRing ring = geometryFactory.createLinearRing(coordinates); Polygon polygon = geometryFactory.createPolygon(ring, null); return polygon; } private static SimpleFeatureType createFeatureType() { SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName("Feature"); builder.add("geometry", Geometry.class); SimpleFeatureType featureType = builder.buildFeatureType(); return featureType; } private static void writeFeaturesToShp(SimpleFeatureCollection features, String shpFileName) throws IOException { File shapefile = new File(shpFileName); Map<String, Serializable> connectParams = new HashMap<String, Serializable>(); connectParams.put("url", shapefile.toURI().toURL()); connectParams.put("create spatial index", Boolean.TRUE); DataStoreFactorySpi factory = new ShapefileDataStoreFactory(); DataStore dataStore = factory.createNewDataStore(connectParams); SimpleFeatureType featureType = createFeatureType(); dataStore.createSchema(featureType); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.addFeatures(features); } dataStore.dispose(); } } ``` 请根据您的具体需求进行修改和裁剪,特别是在创建地理空间对象时使用不同的代码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

du青松

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值