Java 判断坐标是否存在于geojson中
时间: 2023-08-05 09:04:12 浏览: 92
可以使用 GeoTools 库来实现 Java 判断坐标是否存在于 GeoJSON 中。
首先,需要将 GeoJSON 转换为 FeatureCollection,然后遍历其中的 Feature 对象,判断目标坐标是否在 Feature 中。
示例代码如下:
```java
import org.geotools.data.geojson.GeoJSONDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.geojson.feature.FeatureJSON;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class GeoJSONUtil {
public static boolean containsCoordinate(File geojsonFile, Coordinate coordinate) throws IOException {
GeoJSONDataStore dataStore = new GeoJSONDataStore(geojsonFile.toURI().toURL());
SimpleFeatureType featureType = dataStore.getSchema();
SimpleFeatureCollection featureCollection = dataStore.getFeatureSource(featureType.getTypeName()).getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
boolean contains = false;
try {
while (featureIterator.hasNext()) {
SimpleFeature feature = featureIterator.next();
Geometry geometry = (Geometry) feature.getDefaultGeometry();
if (geometry.contains(geometry.getFactory().createPoint(coordinate))) {
contains = true;
break;
}
}
} finally {
featureIterator.close();
}
return contains;
}
}
```
其中,参数 `geojsonFile` 是 GeoJSON 文件,`coordinate` 是目标坐标。该方法返回一个布尔值,表示目标坐标是否存在于 GeoJSON 中。
使用示例:
```java
File geojsonFile = new File("path/to/geojson/file");
Coordinate coordinate = new Coordinate(x, y);
boolean contains = GeoJSONUtil.containsCoordinate(geojsonFile, coordinate);
if (contains) {
System.out.println("目标坐标存在于 GeoJSON 中");
} else {
System.out.println("目标坐标不存在于 GeoJSON 中");
}
```
阅读全文