2

您好我想在 C# 中使用 Gdal 库将 shapefile (shp) 转换为 kml。我写了一个代码,但输出不是 kml 格式。

这是我的代码:

using OSGeo.OGR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.OSR;
using OSGeo.GDAL;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            GdalConfiguration.ConfigureGdal();
            GdalConfiguration.ConfigureOgr();
            convert();
        }
        public static void convert() {
            string shapeFilePath = @ "C:\riv1.shp";

            Ogr.RegisterAll();
            var drv = Ogr.GetDriverByName("ESRI Shapefile");

            var ds = drv.Open(shapeFilePath, 0);


            OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0);

            OSGeo.OGR.Feature f;
            layer.ResetReading();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();


            while ((f = layer.GetNextFeature()) != null) {
                var geom = f.GetGeometryRef();
                if (geom != null) {
                    var geometryKml = geom.ExportToKML("");
                    sb.AppendLine(geometryKml);
                }
            }

            var kmlStr = sb.ToString();
            System.IO.File.WriteAllText("c:/riv1.kml", kmlStr);

        }

    }
}

FWTools Shell 的这种转换工作正常,但我需要在我的代码中进行。如果你知道我想念什么,请帮助我。

4

2 回答 2

1

您可以使用 CopyLayer() 方法将 shapefile 图层复制到新的 Kml 数据源。

        // load the shapefile in a datasoure
        Driver shpDriver = Ogr.GetDriverByName("ESRI Shapefile");
        DataSource shpDatasource = Ogr.Open(shapefilePath, 0);
        if (shpDatasource == null)
            return false;

        // load the shapefile layer
        Layer shpLayer = shpDatasource.GetLayerByIndex(0);

        // create the KML datasource layer
        Driver kmlDriver = Ogr.GetDriverByName("KML");
        DataSource KmlDatasource = Ogr.Open(KmlPath, 0);            
        KmlDatasource = kmlDriver.CreateDataSource(KmlPath, new string[] {});

        // copy the shapefile layer
        Layer newLayer = KmlDatasource.CopyLayer(shpLayer, shpLayer.GetName(), new string[] { });
于 2018-07-04T07:08:00.307 回答
0

非常感谢 Maxwell77。我只是运行它并添加微小的修改以使其正常工作。

GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
OSGeo.OGR.Ogr.RegisterAll();
Driver drv = Ogr.GetDriverByName("ESRI Shapefile");
DataSource shpDatasource = Ogr.Open(shapefilePath, 0);
if (shpDatasource == null)
  return false;

// load the shapefile layer
Layer shpLayer = shpDatasource.GetLayerByIndex(0);

// create the KML datasource layer
using (Driver kmlDriver = Ogr.GetDriverByName("KML"))
{
  // DataSource KmlDatasource = Ogr.Open(KmlPath, 0);
  using (DataSource KmlDatasource = kmlDriver.CreateDataSource(KmlPath, new string[] { }))
  {
    // copy the shapefile layer
    Layer newLayer = KmlDatasource.CopyLayer(shpLayer, shpLayer.GetName(), new string[] {  });
    newLayer.Dispose();
  }

}
}
于 2021-01-04T07:59:34.110 回答