【问题标题】:GeoTools: insert custom Polygons into existiong .shp fileGeoTools:将自定义多边形插入现有的 .shapefile
【发布时间】:2020-11-25 09:42:19
【问题描述】:

我是 Geotools 的新手。现在我想在奥地利的 Shapefile 中插入一个自定义区域(多边形)。 我的代码:

 public static void main(String[] args) throws IOException {
        File file = new File("src/main/java/org/geotools/austria.shp");
        Map<String, Object> map = new HashMap<>();
        map.put("url", file.toURI().toURL());

        DataStore dataStore = DataStoreFinder.getDataStore(map);
        String typeName = dataStore.getTypeNames()[0];
        FeatureSource<SimpleFeatureType, SimpleFeature> source =
                dataStore.getFeatureSource(typeName);

        MapContent showmap = new MapContent();
        showmap.setTitle("Austria");

        Style style = SLD.createSimpleStyle(source.getSchema());
        Layer layer = new FeatureLayer(source, style);
        showmap.addLayer(layer);

        // display the map
        JMapFrame.showMap(showmap);
    }

我目前的结果:

这张图片显示了我当前的输出。我画了一个红色的六边形来展示我将来想要的东西。 如何将此多边形插入并显示到 Shapefile 中?

【问题讨论】:

    标签: java shapefile geo geotools


    【解决方案1】:

    首先,您需要创建一个新的 Shapefile(您可以覆盖旧的,但这样很容易丢失数据)。

    SimpleFeatureType TYPE = dataStore.getSchema(typeName);
    File newFile = new File("output.shp");
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("url", URLs.fileToURL(newFile));
    params.put("create spatial index", Boolean.TRUE);
    
    ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
    newDataStore.createSchema(TYPE);
    

    然后您需要将现有多边形复制到新文件中(我假设它们位于名为 collectionSimpleFeatureCollection 中),然后是新功能:

    Transaction transaction = new DefaultTransaction("create");
    
    String typeName = newDataStore.getTypeNames()[0];
    SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
    
    if (featureSource instanceof SimpleFeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    
        featureStore.setTransaction(transaction);
        try {
            featureStore.addFeatures(collection);
            
            // Now add the hexagon
            featureStore.addFeatures(DataUtilities.collection(hexagon));
            transaction.commit();
         } catch (Exception problem) {
            problem.printStackTrace();
            transaction.rollback();
            System.exit(-1);
         } finally {
            transaction.close();
         }
    } else {
        System.out.println(typeName + " does not support read/write access");
        System.exit(1);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2018-03-18
      • 1970-01-01
      • 2016-12-01
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2015-08-29
      相关资源
      最近更新 更多