查找Shapefile中是否存在纬度/经度的Java解决方案

标签 java geocoding latitude-longitude geotools

我的任务是尝试查找给定的纬度/经度(以度为单位,例如 -50.55555、78.232222)是否存在于给定的 Shapefile 中。

我从这里下载的 Shapefile:https://www.census.gov/geo/maps-data/data/cbf/cbf_nation.html (它包含美国及其所有领土的形状文件)。

我正在寻找一种基于 Java 的解决方案,在给定随机生成的纬度/经度的情况下,确定该点是否位于美国境内。我发现有用(但我是新手)的一种工具是 GeoTools。

那么几个问题:

  • 是否可以使用 GeoTools 来完成此要求(确定某些纬度/经度是否位于美国)?

  • 如果 GeoTools(或单独的 GeoTools)无法做到这一点,是否有另一种方法可以为此找到 Java 解决方案(无需求助于 Google map 等网络服务)。

另请注意:我下载了 QGIS 并使用 mmqgis 插件能够导出我上面提到的 Shapefile 的所有形状文件内容(shape_id、lat、long)。也许我可以使用另一个 Java 库来读取这些形状并测试随机纬度/经度是否落在这些形状内?

我是这一切的新手,任何/所有问题请提问!非常感谢。

最佳答案

你可以通过多种方式做到这一点,但我会这样做:

   private SimpleFeatureCollection features;
   private ReferencedEnvelope env;
   private boolean isInShape(Point p) {
        if (!env.contains(p.getCoordinate())) {
            return false;
        }
        Expression propertyName = filterFactory.property(features.getSchema()
                .getGeometryDescriptor().getName());
        Filter filter = filterFactory.contains(propertyName,
                filterFactory.literal(p));
        SimpleFeatureCollection sub = features.subCollection(filter);
        if (sub.size() > 0) {
            return true;
        }
        return false;
    }

然后读入您的 shapefile 并提取特征并向其 throw 点:

public static void main(String[] args) throws IOException {
    File file = null;
    if (args.length == 0) {
        // display a data store file chooser dialog for shapefiles
        file = JFileDataStoreChooser.showOpenFile("shp", null);
        if (file == null) {
            return;
        }
    } else {
        file = new File(args[0]);
        if (!file.exists()) {
            System.err.println(file + " doesn't exist");
            return;
        }
    }
    PointInPolygon tester = new PointInPolygon();
    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource featureSource = store.getFeatureSource();
    tester.setFeatures(featureSource.getFeatures());
    GeometryFactory fac = new GeometryFactory();
    for (int i = 0; i < 1000; i++) {

        double lat = (Math.random() * 180.0) - 90.0;
        double lon = (Math.random() * 360.0) - 180.0;
        Point p = fac.createPoint(new Coordinate(lat, lon));
        boolean flag = tester.isInShape(p);
        if (flag) {
            System.out.println(p + " is in States ");
        }
    }
}

完整的例子是here .

关于查找Shapefile中是否存在纬度/经度的Java解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27452596/

相关文章:

latitude-longitude - 确定纬度/经度是否在地球表面的多边形内

java - 无法发送 48681 字节的消息来保护来自 java 的 wcf 服务

r - 在 R 中用 ggplot 绘制谷歌地图

python - 为什么这两个 API(twitter geo/search API)返回不同的结果集?

java - 如何在 geoTools 中使用 GeometricShapeFactory 在 map 上创建一个圆

google-maps - 如何计算10米的当前位置变化?

java - 上传文件并将其存储到文件夹中?

java - 在java中处理windows-1252和unicode

java - EntityManager 持久化和合并在 @Transactional 方法中不起作用