преобразовать шейп-файл в kml, используя библиотеку Gdal в C # - PullRequest
0 голосов
/ 14 мая 2018

Привет, я хочу преобразовать шейп-файл (shp) в kml, используя библиотеку Gdal в C #.Я пишу код, но вывод не в формате 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, но мне нужно сделать это в моем коде.Пожалуйста, помогите мне, если вы знаете, что я скучаю.

1 Ответ

0 голосов
/ 04 июля 2018

Вы можете использовать метод CopyLayer (), чтобы просто скопировать слой шейп-файла в новый источник данных 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[] { });
...