为什么此 GeoTool 片段不生成可查看的 shapefile?

2024-03-30

我正在创建一个简单的程序,它从 csv 文件读取值并根据这些值创建 shp 文件。这是一个轻微的修改这个例子 http://docs.geotools.org/latest/tutorials/feature/csv2shp.html

形状文件似乎已创建,但是当我查看形状文件时与另一个片段 http://docs.geotools.org/latest/userguide/tutorial/quickstart/eclipse.html我什么也没看到。我可以用这个程序查看其他示例形状文件。

我的代码中缺少什么?

My data:

LAT1, LON1, LAT2, LON2, LAT3, LON3, LAT3, LON3, CITY, NUMBER
10, 10, 20, 20, 30, 30, 10, 10, Trento, 140

我的代码:

public class ShapeReaderWriter {

    public static void main(String[] args) throws Exception {

        //read the xml file
        File file = FileUtils.getFile("D:\\workspaces\\Routeguard\\Xml2Shape\\src\\com\\meteogroup\\conversion\\locations.csv");

        List<String> lines = FileUtils.readLines(file, "utf-8");

        final SimpleFeatureType TYPE = createFeatureType();

        List<SimpleFeature> features = new ArrayList<SimpleFeature>();        

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

        int i = 0;
        for(String line : lines){
            if (i > 0 && line.trim().length() > 0) { // skip blank lines + header
                String tokens[] = line.split("\\,");

                Coordinate[] coordinates = createPolygonDescription(tokens, 8); //the number of values the polygon has

                String name = tokens[8].trim();
                int number = Integer.parseInt(tokens[9].trim());

                /* Longitude (= x coord) first ! */
                Polygon polygon = geometryFactory.createPolygon(coordinates);
                featureBuilder.add(polygon);
                featureBuilder.add(name);
                featureBuilder.add(number);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                features.add(feature);
            }
            i++;
        }

        /*
         * Get an output file name and create the new shapefile
         */
        File newFile = getNewShapeFile(file);

        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", newFile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);

        ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        newDataStore.createSchema(TYPE);

        /*
         * You can comment out this line if you are using the createFeatureType method (at end of
         * class file) rather than DataUtilities.createType
         */
        //newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);

        /*
         * Write the features to the shapefile
         */
        Transaction transaction = new DefaultTransaction("create");

        String typeName = newDataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);

        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

            /*
             * SimpleFeatureStore has a method to add features from a
             * SimpleFeatureCollection object, so we use the ListFeatureCollection
             * class to wrap our list of features.
             */
            SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();

            } catch (Exception problem) {
                problem.printStackTrace();
                transaction.rollback();

            } finally {
                transaction.close();
            }
            System.exit(0); // success!
        } else {
            System.out.println(typeName + " does not support read/write access");
            System.exit(1);
        }

    }

    private static Coordinate[] createPolygonDescription(String[] tokens, int max) {
        Coordinate[] coords = new Coordinate[max / 2];
        int j = 0;
        for(int i = 0 ; i < max; i = i+2){
            Coordinate c = new Coordinate(Double.parseDouble(tokens[i + 1]), Double.parseDouble(tokens[i])); // seems weird but isn't  -> lon is the x value, lat is the y
            coords[j] = c;
            j++;
        }
        return coords;
    }

    private static SimpleFeatureType createFeatureType() {

        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("Location");
        builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system

        // add attributes in order
        builder.add("Polygon", Polygon.class);
        builder.length(15).add("Name", String.class); // <- 15 chars width for name field
        builder.add("Number", Integer.class);

        // build the type
        final SimpleFeatureType LOCATION = builder.buildFeatureType();

        return LOCATION;
    }

    private static File getNewShapeFile(File csvFile) {
        String path = csvFile.getAbsolutePath();
        String newPath = path.substring(0, path.length() - 4) + ".shp";

        JFileChooser chooser = new JFileChooser("shp");
        chooser.setDialogTitle("Save shapefile");
        chooser.setSelectedFile(new File(newPath));

        int returnVal = chooser.showSaveDialog(null);

        if (returnVal != JFileChooser.APPROVE_OPTION) {
            // the user cancelled the dialog
            System.exit(0);
        }

        File newFile = chooser.getSelectedFile();
        if (newFile.equals(csvFile)) {
            System.out.println("Error: cannot replace " + csvFile);
            System.exit(0);
        }

        return newFile;
    }

}

还有我的观众:

公开课快速入门 {

/**
 * GeoTools Quickstart demo application. Prompts the user for a shapefile and displays its
 * contents on the screen in a map frame
 */
public static void main(String[] args) throws Exception {
    // display a data store file chooser dialog for shapefiles
    File file = JFileDataStoreChooser.showOpenFile("shp", null);
    if (file == null) {
        return;
    }

    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource featureSource = store.getFeatureSource();

    // Create a map content and add our shapefile to it
    MapContent map = new MapContent();
    map.setTitle("Quickstart");

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

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

}

谢谢你,很抱歉这个长片段!


看起来 geotools 在内部将几何名称硬编码为“the_geom”。

我遇到了同样的错误,通过替换此行即可修复:

builder.add("Polygon", Polygon.class);

与这个:

builder.add("the_geom", Polygon.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么此 GeoTool 片段不生成可查看的 shapefile? 的相关文章

随机推荐

  • Google 地图 React Wrapper - 标记集群创建 @googlemaps/react-wrapper

    我正在使用 Google ReactJS 库将地图添加到我的 React Web 应用程序中 并使用 googlemaps react wrapper 库来集群标记 但我无法在包装器上进行标记聚类 如果有人有任何想法 请帮助解决问题 组件代
  • .htaccess - 301 重定向所有不带扩展名的文件以具有 .html 扩展名

    我需要将请求重定向到没有扩展名的文件 并附加 html 扩展名 http www mydomain com this to http www mydomain com this html 以下内容不会被重定向 http www mydoma
  • 在 KeyChainItemWrapper 中保存密码时崩溃

    Apple 在他们的中提供了 KeyChainItemWrapper 类GenericKeyChain 示例代码 http developer apple com library ios samplecode GenericKeychain
  • C# 3.5 DLR 表达式.动态问题

    我继承了一种小型脚本语言 并尝试将其移植到 DLR 以便更容易管理 到目前为止 一切都相当简单 我在尝试动态调用变量的成员时遇到了问题 当前的语言在 NET 上运行 并使用解析循环和反射来执行此操作 但我希望摆脱这种情况 这是脚本语言的示例
  • 在PE的导入表中添加一个条目

    我正在寻找一个命令行程序来向 PE 文件的导入表添加条目 我的目标是将一个新的导入函数从外部 DLL 添加到我的 EXE 然后使用 ollydbg 使用代码洞穴插入新代码 新代码将使用新导入的函数 实际上我已经实现了我的目标 但是要向我使用
  • 使用 LINQWhere 查询仅获取部分 ConfigurationManager.ConnectionStrings

    我的目标是使用 LINQWhere查询于ConfigurationManager ConnectionStrings控制台应用程序中的集合 假设一个新的 NET 4 5 控制台应用程序添加了 System Configuration 引用
  • 一个构造函数 - 多个参数

    我在一些 Java 编程竞赛中找到了一个任务 必须创建仅包含一个参数 文本 和一个构造函数的类 Sentence 这是示例测试代码 Sentence s1 new Sentence only CAT s2 new Sentence and
  • 用户“”登录失败

    我有一个 ASP Net MVC 网站 在本地测试时工作正常 我已将该网站放入您的 Windows Server 2008 计算机上的 IIS 7 中 该网站使用 net 会员提供商 当我尝试登录时收到以下错误 Login failed f
  • 使用python限制类实例的数量

    我的主类创建了一个简单的QmainWindows像这样 class mcManageUiC QtGui QMainWindow def init self super mcManageUiC self init self initUI de
  • 使用 perl 格式化字符串和日期

    我想转换 使用perl 05 26 2013 06 09 47 to 26 05 2013 06 09 47 另外我怎样才能将上面的日期和时间更改为 GMT 日期和时间 use DateTime Format Strptime qw my
  • 用户查找加密数据库字段

    本质上 我有一个保存用户数据的表 所有这些数据都是 AES 加密的 在 BLOB 字段中 这意味着这些字段都不能被索引 这将减慢该表上的任何查询 特别是因为在进行任何匹配之前整个表需要解密 WHERE AES DECRYPT user em
  • 从树视图 tkinter 复制项目

    我的一个 tkinter 应用程序中有一个树视图 我想知道是否真的可以通过用户右键单击来复制选定的字段 如果没有 是否有任何其他小部件允许用户复制 GUI 窗口中显示的选定字段 Code log Toplevel root log titl
  • javascript向函数添加属性

    假设我们有一个函数 function Rabbit console log shiv 现在 无需创建该函数的对象 我就可以分配该对象的属性 Rabbit bark function line console log name is line
  • 使用 Iso_Fortran_Env 设置函数的 Kind 值

    如何使用 ISO Fortran Env 的内在函数以 Fortran 2008 惯用的方式设置函数的返回 KIND 值 通常在主程序中 我可以使用 ISO Fortran 内在函数 如下所示 program name here use i
  • jQuery 事件适用于 Firefox,不适用于 Chrome

    我在代码中注册了一些点击事件 它们在 Firefox Windows 和 Mac 中正常运行 但在 Chrome 中无法执行 尝试过 Windows 和 Mac beta JavaScript 的目的是根据 select 元素的值显示正确的
  • 检查一个 Int 值是否大于或等于另一个 Int 值?价值? [复制]

    这个问题在这里已经有答案了 如何比较两个 Int 值 所以 我有这个 let limit Int let current Int Int self stringValue 但是当我尝试比较它们 大于或等于 时 if current gt s
  • 如何使 JAWS 等屏幕阅读器可以访问“正在加载”图标?

    所以 HTML 代码是这样的 div style display none img src PT LOADING gif alt Processing please wait title div 即使提供了 ALT 文本 在更改样式以显示图
  • 函数 while 循环中的 return 是如何处理的?

    我有一个函数 该函数内部有一个 while 循环 当我尝试使用 IF 语句在 while 循环内设置非局部变量 然后退出整个函数时 突然该变量不再设置 function EXAMPLE cat test txt while read LIN
  • insertRow 与appendChild

    向表中添加行时首选哪种方法 var tr tbl insertRow 1 or var tr document createElement tr tbl appendChild tr insertRow会好得多 这是支持的 http www
  • 为什么此 GeoTool 片段不生成可查看的 shapefile?

    我正在创建一个简单的程序 它从 csv 文件读取值并根据这些值创建 shp 文件 这是一个轻微的修改这个例子 http docs geotools org latest tutorials feature csv2shp html 形状文件