在GDAL(C#)中向shapefile添加点几何

时间:2018-05-29 19:01:08

标签: c# shapefile gdal qgis

我正在尝试使用GDAL制作带点几何的shapefile。我按照here给出的例子。我使用的是Microsoft Visual Studio,编程语言是C#。现在,我只是在原点制作一个点,并且我在QGIS中查看生成的shapefile。出于某种原因,我无法看到我所提出的观点。我也试过制作一个多边形,但我遇到了同样的问题。以下是我写的代码:

        public void testSF(Dataset ds)
        {
        Console.WriteLine("Writing ERSI shapefile");
        // Registering drivers
        OSGeo.OGR.Ogr.RegisterAll();
        OSGeo.OGR.Driver driverSH = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");

        if (driverSH == null)
        {
            Console.WriteLine("Cannot get drivers. Exiting");
            System.Environment.Exit(-1);
        }
        Console.WriteLine("Drivers fetched");

        // Creating a shapefile
        OSGeo.OGR.DataSource dataSourceSH = driverSH.CreateDataSource("ERSI_TEST_ShapeFile.shp", new string[] { });
        if (dataSourceSH == null)
        {
            Console.WriteLine("Cannot create datasource");
            System.Environment.Exit(-1);
        }
        Console.WriteLine("Shapefile created");

        // Creating a point layer
        OSGeo.OGR.Layer layerSH;
        layerSH = dataSourceSH.CreateLayer("PolygonLayer", null, OSGeo.OGR.wkbGeometryType.wkbPoint, new string[] { });
        if (layerSH == null)
        {
            Console.WriteLine("Layer creation failed, exiting...");
            System.Environment.Exit(-1);
        }
        Console.WriteLine("Polygon Layer created");

        // Creating and adding attribute fields to layer
        OSGeo.OGR.FieldDefn fdefnName = new OSGeo.OGR.FieldDefn("Name", OSGeo.OGR.FieldType.OFTString);
        fdefnName.SetWidth(32);

        OSGeo.OGR.FieldDefn fdefnGPS = new OSGeo.OGR.FieldDefn("GPS", OSGeo.OGR.FieldType.OFTString);
        fdefnGPS.SetWidth(32);

        if (layerSH.CreateField(fdefnName, 1) != 0)
        {
            Console.WriteLine("Creating Name field failed");
            System.Environment.Exit(-1);
        }

        if (layerSH.CreateField(fdefnGPS, 1) != 0)
        {
            Console.WriteLine("Creating GPS field failed");
            System.Environment.Exit(-1);
        }

        Console.WriteLine("Fields created and added to layer");
        OSGeo.OGR.Feature featureSH = new OSGeo.OGR.Feature(layerSH.GetLayerDefn());
        featureSH.SetField("Name", "This is a NAME");
        featureSH.SetField("GPS", "Test GPS point");

        // Outer Ring 
        // Methodology: Create a linear ring geometry, add it to a polygon geometry. Add polygon geometry to feature. Add feature to layer

        OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature( layerSH.GetLayerDefn() );
        OSGeo.OGR.Geometry geom = OSGeo.OGR.Geometry.CreateFromWkt("POINT(0.0 0.0)");

        feature.SetGeometry(geom);
        layerSH.CreateFeature(feature);
}

此代码在0.0和0.0处为多边形图层添加一个点。但是,当我在QGIS中打开生成的图层时,我看不到/找到该点。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我已经使用上一个GDAL版本测试了您的代码并且它可以正常运行。

您必须关闭数据源(调用Dispose方法)以使用创建的几何更新文件,否则您将只查看空文件。

答案 1 :(得分:0)

我认为您缺少定义空间参考