C# NetTopologySuite+ProjNet 任意图形类型坐标转换

添加引用:NetTopologySuite、ProjNet、ProjNet.SRID

C# NetTopologySuite+ProjNet 任意图形类型坐标转换_第1张图片

Program.cs文件:

using ProjNet.CoordinateSystems;
using ProjNet.CoordinateSystems.Transformations;
using ProjNet.SRID;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Xsl;
using NetTopologySuite.IO;
using NetTopologySuite.Geometries;

namespace Reproject2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            CoordinateSystem projCs = SRIDReader.GetCSbyID(4527);
            CoordinateSystem geoCs = SRIDReader.GetCSbyID(4490);

            CoordinateTransformationFactory ctFactory = new CoordinateTransformationFactory();
            ICoordinateTransformation transformation = ctFactory.CreateFromCoordinateSystems(projCs, geoCs);

            Polygon original = new Polygon(
                new LinearRing(
                    new Coordinate[] {
                        new Coordinate(39498340.1151, 4807100.9600),
                        new Coordinate(39499340.1151, 4809100.9600),
                        new Coordinate(39497340.1151, 4806100.9600),
                        new Coordinate(39498340.1151, 4807100.9600)
            }));

            foreach (var coor in original.Coordinates)
            {
                Console.WriteLine("原始坐标: " + coor.X + " ; " + coor.Y);
            }

            Geometry after = Transform(original, transformation.MathTransform);

            foreach (var coor in after.Coordinates)
            {
                Console.WriteLine("转换后坐标: " + coor.X + " ; " + coor.Y);
            }
            Console.ReadKey();
        }

        public static Geometry Transform(Geometry geometry, MathTransform mathTransform)
        {
            geometry = geometry.Copy();
            geometry.Apply(new MathTransformFilter(mathTransform));
            return geometry;
        }
    }
}

新增文件:MathTransformFilter.cs,用于完成任意geometry的序列化转坐标。

using NetTopologySuite.Geometries;
using ProjNet.CoordinateSystems.Transformations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Reproject2
{
    public class MathTransformFilter : ICoordinateSequenceFilter
    {
        private readonly MathTransform _mathTransform;

        public MathTransformFilter(MathTransform mathTransform)
            => _mathTransform = mathTransform;

        public bool Done => false;
        public bool GeometryChanged => true;

        public void Filter(CoordinateSequence seq, int i)
        {
            var (x, y, z) = _mathTransform.Transform(seq.GetX(i), seq.GetY(i), seq.GetZ(i));
            seq.SetX(i, x);
            seq.SetY(i, y);
            seq.SetZ(i, z);
        }
    }
}

C# NetTopologySuite+ProjNet 任意图形类型坐标转换_第2张图片

 

你可能感兴趣的:(c#)