java如何读取shp文件,取出点、线坐标点

本文介绍了在工作中如何使用GeoTools和JTS库处理GIS数据,通过pom.xml依赖管理,详细展示了如何通过API调用查询和解析Shapefile数据,并将其转换为MapDataLineVO对象以渲染到地图上。
摘要由CSDN通过智能技术生成

工作中处理gis数据的时候,需要用到

首先pom.xml

        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>24.1</version>
        </dependency>
        <dependency>
            <groupId>org.locationtech.jts</groupId>
            <artifactId>jts-core</artifactId>
            <version>1.18.1</version>
        </dependency>

然后上代码

@GetMapping("/queryShpForMapDataLine")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "查询所需要的shp数据从而渲染到地图上-线数据", notes = "传入dataType和time")
	@Cacheable(value = "mapDataLineCache", key = "'queryShpForMapDataLine_'+#region+ '_' + #dataType + '_' + #time")
	public R<List<MapDataLineVO>> queryShpForMapDataLine(@RequestParam(value = "dataType", required = true) String dataType,
														 @RequestParam(value = "time", required = true) String time,
														 @RequestParam(value = "region",required = true) String region
	) {


		String dateString = "2024-01-08";//因為數據庫只有這一天的數據
		String dateTimeString = dateString + " " + time + ":00";
		//將時間字符串轉換成LocalDataTime
		LocalDateTime parseTime = LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

		//构建最终需要返回的对象
		ArrayList<MapDataLineVO> mapDataLineVOS = new ArrayList<>();

		//将id和线的shp坐标存入map,以便后续匹配
		HashMap<String, Geometry> geometryHashMap = new HashMap<>();

		try {
			// 获取资源文件路径
			// 获取资源文件路径
			String path = IndexDataController.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			File file ;
			if (path.contains("file:")&&!path.contains("D:")&&!path.contains("E:")) {
				String[] parts = path.split("file:");
				path = parts[0]; // 获取前面的路径部分
				file = new File(path+"temp/line/line_Project.shp"); // 构建shp文件路径(生产环境的路径)
				log.info("得到的path为="+path+"得到的path[1]为"+parts[1]);
				if (StringUtil.isBlank(path)){
					log.info("path为空,进入虚拟机环境,找到与外界映射的虚拟机的文件夹");
					//docker run -d \
					//--name watermodelService \
					//-p 9084:9084 \
					//-m 512M \
					//--privileged=true \
					//--restart=always \
					//-v /home/watermodel/service/logs:/xh/logs \
					//-v /home/watermodel/service/temp:/xh/data \    启动脚本应该加上文件夹映射
					//-e JAVA_OPTS="-Xmx128m -Xss512k" \
					//-e "spring.profiles.active=dev" \
					//xhsoft/watermodel-service
					file=new File("/xh/data/line/line_Project.shp");//构建shp文件路径(生产环境的路径)
				}
				log.info("实际文件路径="+file.getAbsolutePath());
			} else if (path.contains("file:")) {
				String[] parts = path.split("file:");
				path = parts[0]; // 获取前面的路径部分
				file = new File(path+"temp/line/line_Project.shp"); // 构建shp文件路径(生产环境的路径)
				log.info("得到的path为="+path+"得到的path[1]为"+parts[1]);
			} else{
				String decodedPath = URLDecoder.decode(path, "UTF-8");
				File jarFile = new File(decodedPath);
				File jarParentDir = jarFile.getParentFile(); // 获取JAR包所在的目录

				File tempDir = new File(jarParentDir, "temp"); // 构建temp目录的路径
				file = new File(tempDir, "line/line_Project.shp"); // 构建shp文件路径
//			log.info("jar包文件路径jarParentDir="+jarParentDir.getAbsolutePath());
				log.info("实际文件路径="+file.getAbsolutePath());
			}

			// 读取SHP文件
			FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);

			// 获取FeatureSource
			SimpleFeatureSource featureSource = dataStore.getFeatureSource();

			// 获取FeatureType
//			SimpleFeatureType featureType = featureSource.getSchema();


			// 获取FeatureIterator遍历Feature
			try (SimpleFeatureIterator iterator = featureSource.getFeatures().features()) {
				while (iterator.hasNext()) {
					SimpleFeature feature = iterator.next();

					// 获取几何对象
					Geometry geometry = (Geometry) feature.getDefaultGeometry();

					// 获取起点坐标
					Coordinate startCoordinate = geometry.getCoordinates()[0];

					// 获取终点坐标
					Coordinate endCoordinate = geometry.getCoordinates()[geometry.getCoordinates().length - 1];

					// 获取Name字段值
					String name = (String) feature.getAttribute("Name");

					// 获取FeatID字段值
					String featID = (String) feature.getAttribute("FACILITYID");


					// 获取length字段值
					Double length = (Double) feature.getAttribute("length");

					//直接存入geometry
					geometryHashMap.put(featID, geometry);

					// 输出起点坐标、终点坐标、Name字段值、FeatID字段值和length字段值到控制台
//					System.out.println("FeatID: " + featID);
//					System.out.println("起点坐标:(" + startCoordinate.x + ", " + startCoordinate.y + ")");
//					System.out.println("终点坐标:(" + endCoordinate.x + ", " + endCoordinate.y + ")");
//					System.out.println("Name: " + name);
//					System.out.println("length: " + length);
//					System.out.println("------------------------------");
				}
			}
			//上面的代码主要是读取shp构建map为了取出坐标


		} catch (IOException e) {
			throw new RuntimeException("IO异常");
		}
//后面业务代码省略

注意,在linux一定要改shp文件为英文

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用一些库来读取和处理SHP文件,其中最常用的是开源库GeoTools。以下是一个简单的示例代码,展示了如何使用GeoTools读取SHP文件: ```java import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.opengis.feature.simple.SimpleFeature; public class SHPReader { public static void main(String[] args) { try { // 打开SHP文件 FileDataStore dataStore = FileDataStoreFinder.getDataStore(new File("path/to/your/file.shp")); // 获取SHP文件中的要素集合 SimpleFeatureCollection features = dataStore.getFeatureSource().getFeatures(); // 遍历要素集合 try (SimpleFeatureIterator iterator = features.features()) { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); // 处理每个要素的属性和几何信息 System.out.println("属性信息: " + feature.getAttribute("attributeName")); System.out.println("几何信息: " + feature.getDefaultGeometry()); } } // 关闭数据存储 dataStore.dispose(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在代码中,你需要将`"path/to/your/file.shp"`替换为你实际的SHP文件路径。然后,你可以通过`feature.getAttribute("attributeName")`来获取每个要素的属性信息,`feature.getDefaultGeometry()`来获取几何信息。 请注意,这只是一个基本的示例,你可以根据自己的需求进一步扩展和处理SHP文件中的数据。同时,确保你已经将GeoTools库添加到你的项目中,并正确引入所需的依赖项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值