.NET|--杂类|--将Shp文件转为GeoJson-通过GDAL

前言


真实需求是将Shp转为pbf文件,
不过我现在已经实现了, 将GeoJson格式数据转换为pbf文件, 
所以需要实现将Shp文件转换为GeoJson格式即可.

1.下载GDAL的程序集

下载地址 → https://www.gisinternals.com/development.php

下载完成, 解压zip文件,可以看到这些dll文件(路径 : release-1930-x64-gdal-3-9-1-mapserver-8-2-0\bin\gdal\csharp)

2."依赖项-程序集"中添加4个程序集

依赖项→(右击)→添加项目引用→浏览 : 将这4个程序集选中.

3.Nuget包管理器,安装GDAL

Visual Studio菜单栏--工具--NuGet包管理器--管理解决方案的NuGet程序包

搜索"GDAL", 不出意外的, 第一个就是要安装的~

注意, Nuget中安装了GDAL后, 会自动生成一个类GdalConfiguration, 后面会用到

4.代码


 public static class ShpFileUtility
    {
        /// <summary>
        /// 将Shp文件转换为GeoJson格式文件
        /// </summary>
        /// <param name="shpFilePath"></param>
        /// <param name="geoJSONFilePath"></param>
        /// <returns></returns>
        public static bool Convert2GeoJSONFile(string shpFilePath, string geoJSONFilePath)
        {
            bool isOk = false;

            GdalConfiguration.ConfigureGdal();
            GdalConfiguration.ConfigureOgr();

            if (string.IsNullOrWhiteSpace(shpFilePath) || string.IsNullOrWhiteSpace(geoJSONFilePath))
            {
                throw new ArgumentException("输入参数路径不合法");
            }

            OSGeo.GDAL.Gdal.AllRegister();
            OSGeo.OGR.Ogr.RegisterAll();

            // 为了支持中文路径,请添加下面这句代码
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            // 为了使属性表字段支持中文,请添加下面这句
            OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");

            //Gdal.SetConfigOption("DXF_ENCODING", "UTF-8");

            //打开数据
            DataSource ds = Ogr.Open(shpFilePath, 0);
            if (ds == null)
            {
                throw new Exception($"打开文件失败{shpFilePath}");
            }
            using OSGeo.OGR.Driver dv = Ogr.GetDriverByName("GeoJSON");
            if (dv == null)
            {
                throw new Exception($"打开驱动失败:GeoJSON");
            }

            using var ret = dv.CopyDataSource(ds, geoJSONFilePath, null);
            // 手动释放, 否则生成的geoJSONFilePath一直被占用, 并且反序列化JSON的时候会报错 : Newtonsoft.Json Unexpected character encountered while parsing value: .Path...
            ret.FlushCache();
            ret.Dispose();


            isOk = true;
            return isOk;
        }

    }

摘抄文档

posted @   zh89233  阅读(107)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示