使用NetTopologySuite将shp文件转为GeoJson格式

艾泰
2023-12-01

使用NetTopologySuite将shp文件转为GeoJson格式

需要引入的库(NetTopologySuite可从Nuget中下载):

using NetTopologySuite.Features;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using NetTopologySuite.IO.Converters;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;

首先读取shp,将shp读取为Geometry
我这里是单个图形的,这里可以用遍历拓展出多图形的

private static Geometry ReadShape(string shapepath)
     {
         if (!File.Exists(shapepath))
             throw new ArgumentException("File " + shapepath + " not found!");

         var reader = new ShapefileReader(shapepath);
         var geometries = reader.ReadAll();
         Geometry geometry = geometries[0];//这块可以遍历,用于多个图形转换
         return geometry;
     }
     

接下来转GeoJson,这里可以添加属性,具体可以NTS参考源码中的例子

public static string ShpToGeoJSON(string shpPath)
        {
            Geometry boundary = ReadShape(shpPath);
            var target = new FeatureConverter();
            var sb = new StringBuilder();
            var writer = new JsonTextWriter(new StringWriter(sb));
            IFeature value = new Feature(boundary, null);
            var serializer = GeoJsonSerializer.Create(
                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore },
                GeometryFactory.Default);
            target.WriteJson(writer, value, serializer);
            writer.Flush();
            return sb.ToString();
        }

最后在Main方法中调用就行了

static void Main(string[] args)
        {
            string path = @"E:\GIS工作区\21县\库车县.shp";
            string GeoJson= Shp2GeoJSON.ShpToGeoJSON(path);
            Console.WriteLine(GeoJson);
        }

这只是NetTopologySuite一个小小的例子,以后会更新更多关于NetTopologySuite和GDAL的各种应用例子。

 类似资料: