Пример #1
0
 public static ISpatialReference ReadSR(string pPrjFilePath)
 {
     if (File.Exists(pPrjFilePath))
     {
         StreamReader aReader = new StreamReader(pPrjFilePath);
         string       aLine   = aReader.ReadToEnd();
         aReader.Close();
         int byteCount = 0;
         if (aLine.StartsWith("GEOGCS"))
         {
             GeographicCoordinateSystem sr = new GeographicCoordinateSystem();
             (sr as IESRISpatialReference).ImportFromESRISpatialReference(aLine, out byteCount);
             return(sr as ISpatialReference);
         }
         else
         {
             ProjectedCoordinateSystem sr = new ProjectedCoordinateSystem();
             (sr as IESRISpatialReference).ImportFromESRISpatialReference(aLine, out byteCount);
             return(sr as ISpatialReference);
         }
     }
     else
     {
         return(null);
     }
 }
Пример #2
0
        public static string ToESRIGeotransWKT(ISpatialReference sRef)
        {
            if (sRef == null || sRef.Datum == null)
            {
                return("");
            }

            object obj = Proj4CoordinateSystemReader.Create(ToProj4(sRef));

            if (obj == null)
            {
                return("");
            }

            if (obj is AbstractInformation)
            {
                ((AbstractInformation)obj).Name = (sRef.Description != String.Empty) ? sRef.Description : sRef.Name;
            }

            if (obj is ProjectedCoordinateSystem)
            {
                ProjectedCoordinateSystem sys = obj as ProjectedCoordinateSystem;
                if (sys.HorizontalDatum != null && sRef.Datum != null)
                {
                    sys.HorizontalDatum.Name = sRef.Datum.Name;
                }
                if (sys.GeographicCoordinateSystem != null && sRef.Datum != null)
                {
                    sys.GeographicCoordinateSystem.Name = GeogrNameFromDatumName(sRef.Datum.Name);
                }
            }

            return(ESRIGeotransWktCoordinateWriter.Write(obj));
        }
Пример #3
0
        public HIL.Vector3 getOffsetFromLeader(MAVLink leader, MAVLink mav)
        {
            //convert Wgs84ConversionInfo to utm
            CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

            GeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

            int utmzone = (int)((leader.MAV.cs.lng - -183.0) / 6.0);

            IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone, leader.MAV.cs.lat < 0 ? false : true);

            ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

            double[] masterpll = { leader.MAV.cs.lng, leader.MAV.cs.lat };

            // get leader utm coords
            double[] masterutm = trans.MathTransform.Transform(masterpll);

            double[] mavpll = { mav.MAV.cs.lng, mav.MAV.cs.lat };

            //getLeader follower utm coords
            double[] mavutm = trans.MathTransform.Transform(mavpll);

            return(new HIL.Vector3(masterutm[1] - mavutm[1], masterutm[0] - mavutm[0], 0));
        }
        public Vector3 getOffsetFromLeader(MAVState leader, MAVState mav)
        {
            //convert Wgs84ConversionInfo to utm
            CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

            IGeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

            int utmzone = (int)((leader.cs.lng - -186.0) / 6.0);

            IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone,
                                                                                 leader.cs.lat < 0 ? false : true);

            ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

            double[] masterpll = { leader.cs.lng, leader.cs.lat };

            // get leader utm coords
            double[] masterutm = trans.MathTransform.Transform(masterpll);

            double[] mavpll = { mav.cs.lng, mav.cs.lat };

            //getLeader follower utm coords
            double[] mavutm = trans.MathTransform.Transform(mavpll);

            var heading = -leader.cs.yaw;

            var norotation = new Vector3(masterutm[1] - mavutm[1], masterutm[0] - mavutm[0], 0);

            norotation.x *= -1;
            norotation.y *= -1;

            return(new Vector3(norotation.x * Math.Cos(heading * MathHelper.deg2rad) - norotation.y * Math.Sin(heading * MathHelper.deg2rad), norotation.x * Math.Sin(heading * MathHelper.deg2rad) + norotation.y * Math.Cos(heading * MathHelper.deg2rad), 0));
        }
Пример #5
0
        private void BtnCoord_Click(object sender, RoutedEventArgs e)
        {
            var ctfac  = new CoordinateTransformationFactory();
            var toCS   = GeographicCoordinateSystem.WGS84;
            var fromCS = ProjectedCoordinateSystem.WGS84_UTM(32, true);
            var trans  = ctfac.CreateFromCoordinateSystems(fromCS, toCS);

            double[] fromPoint = new double[] { 344354, 5676502 };
            double[] toPoint   = trans.MathTransform.Transform(fromPoint);

            var utmX = Convert.ToInt32(fromPoint[0]);
            var utmY = Convert.ToInt32(fromPoint[1]);

            var latDecimal = toPoint[1].ToString(new CultureInfo("en-US"));
            var lonDecimal = toPoint[0].ToString(new CultureInfo("en-US"));
            var url1       = $@"https://www.openstreetmap.de/karte.html?lat={latDecimal}&lon={lonDecimal}&zoom=17&layers=B000";
            var url2       = $@"https://maps.duesseldorf.de/stk/index.html?Zoom=6&UTM32={utmX},{utmY}";

            Log($"Coords: {toPoint[0]}, {toPoint[1]}");
            Log($"Url: {url2}");

            //webBrowser.Navigate(url2);

            Process.Start(url2);
        }
        private static bool TryGetTransformation(Coordinate c1, Coordinate c2, out ICoordinateTransformation transformation)
        {
            var result = false;

            transformation = null;

            int utmZone1 = GetUtmZone(c1.Longitude);
            int utmZone2 = GetUtmZone(c2.Longitude);

            bool isSouth1 = c1.Latitude < 0;
            bool isSouth2 = c2.Latitude < 0;

            result = (Math.Abs((utmZone1 - utmZone2))) < 2 && (isSouth1 == isSouth2);

            if (!result)
            {
                return(false);
            }

            var wgs = GeographicCoordinateSystem.WGS84;
            var utm = ProjectedCoordinateSystem.WGS84_UTM(utmZone1, !isSouth1);

            transformation = new CoordinateTransformationFactory().CreateFromCoordinateSystems(wgs, utm);

            return(result);
        }
Пример #7
0
        private static IProjectedCoordinateSystem ReadProjectedCoordinateSystem(XmlTextReader reader)
        {
            if (!(reader.NodeType == XmlNodeType.Element && reader.Name == "CS_ProjectedCoordinateSystem"))
            {
                throw new ParseException(String.Format("Expected a IProjectedCoordinateSystem but got a {0} at line {1} col {2}", reader.Name, reader.LineNumber, reader.LinePosition));
            }
            string authority = "", authorityCode = "", abbreviation = "", name = "";

            reader.Read();
            ReadInfo(reader, ref authority, ref authorityCode, ref abbreviation, ref name);
            ArrayList list = new ArrayList();

            while (reader.NodeType == XmlNodeType.Element && reader.Name == "CS_AxisInfo")
            {
                IAxisInfo axis = ReadAxisInfo(reader);
                list.Add(axis);
                reader.Read();
            }
            IAxisInfo[] axisInfos = new IAxisInfo[list.Count];
            axisInfos = (IAxisInfo[])list.ToArray(typeof(IAxisInfo));
            IGeographicCoordinateSystem geographicCoordinateSystem = ReadGeographicCoordinateSystem(reader);
            ILinearUnit linearUnit = ReadLinearUnit(reader);
            IProjection projection = ReadProjection(reader);

            reader.Read();
            //IPrimeMeridian primeMeridian = null;
            IHorizontalDatum          horizontalDatum = null;
            ProjectedCoordinateSystem projectedCS     = new ProjectedCoordinateSystem(horizontalDatum,
                                                                                      axisInfos, geographicCoordinateSystem, linearUnit, projection, "", authority, authorityCode,
                                                                                      name, "", abbreviation);

            return(projectedCS);
        }
Пример #8
0
        public void MetersDistanceTest()
        {
            var brasiliaUtmZone        = 23;
            var originCoordinateSystem = GeographicCoordinateSystem.WGS84;
            var targetCoordinateSystem = ProjectedCoordinateSystem.WGS84_UTM(brasiliaUtmZone, false);

            var transform = new CoordinateTransformationFactory().CreateFromCoordinateSystems(
                originCoordinateSystem, targetCoordinateSystem);

            var southCampus = new GeoAPI.Geometries.Coordinate(-15.8136081, -47.8442208);
            var northCampus = new GeoAPI.Geometries.Coordinate(-15.7632746, -47.8779637);
            var epnbCampus  = new GeoAPI.Geometries.Coordinate(-15.87567632, -47.9929947);

            var southCoordinate = new GeoAPI.Geometries.Coordinate(southCampus.X, southCampus.Y);
            var northCoordinate = new GeoAPI.Geometries.Coordinate(northCampus.X, northCampus.Y);
            var epnbCoordinate  = new GeoAPI.Geometries.Coordinate(epnbCampus.X, epnbCampus.Y);

            var newSouthCampusPoint = transform.MathTransform.Transform(southCoordinate);
            var newNorthCampusPoint = transform.MathTransform.Transform(northCoordinate);
            var newEnpbCampusPoint  = transform.MathTransform.Transform(epnbCoordinate);

            var distanceSouthCampus = newEnpbCampusPoint.Distance(newSouthCampusPoint);
            var distanceNorthCampus = newEnpbCampusPoint.Distance(newNorthCampusPoint);

            distanceSouthCampus.ShouldBeGreaterThan(distanceNorthCampus);

            //result makes no sense for me, on google says other way
        }
Пример #9
0
        /// <summary>
        /// Creates a coordinats transfomation from ITM to WGS84.
        /// </summary>
        /// <returns></returns>
        public static IMathTransform Create()
        {
            var coordinateTransformFactory = new CoordinateTransformationFactory();
            var coordinateSystemFactory    = new CoordinateSystemFactory();
            var itmParameters = new List <ProjectionParameter>
            {
                new ProjectionParameter("latitude_of_origin", 31.734393611111109123611111111111),
                new ProjectionParameter("central_meridian", 35.204516944444442572222222222222),
                new ProjectionParameter("false_northing", 626907.390),
                new ProjectionParameter("false_easting", 219529.584),
                new ProjectionParameter("scale_factor", 1.0000067)
            };

            var itmDatum = coordinateSystemFactory.CreateHorizontalDatum("Isreal 1993", DatumType.HD_Geocentric,
                                                                         Ellipsoid.GRS80, new Wgs84ConversionInfo(-24.0024, -17.1032, -17.8444, -0.33077, -1.85269, 1.66969, 5.4248));

            var itmGeo = coordinateSystemFactory.CreateGeographicCoordinateSystem("ITM", AngularUnit.Degrees, itmDatum,
                                                                                  PrimeMeridian.Greenwich, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North));

            var itmProjection = coordinateSystemFactory.CreateProjection("Transverse_Mercator", "Transverse_Mercator", itmParameters);
            var itm           = coordinateSystemFactory.CreateProjectedCoordinateSystem("ITM", itmGeo, itmProjection, LinearUnit.Metre,
                                                                                        new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North));

            var wgs84 = ProjectedCoordinateSystem.WGS84_UTM(36, true).GeographicCoordinateSystem;

            return(coordinateTransformFactory.CreateFromCoordinateSystems(itm, wgs84).MathTransform);
        }
Пример #10
0
        public ActionResult <IEnumerable <string> > Get()
        {
            try
            {
                CoordinateSystemFactory         csFact = new CoordinateSystemFactory();
                CoordinateTransformationFactory ctFact = new CoordinateTransformationFactory();

                ICoordinateSystem utm35ETRS = csFact.CreateFromWkt(
                    "PROJCS[\"ETRS89 / ETRS-TM35\",GEOGCS[\"ETRS89\",DATUM[\"D_ETRS_1989\",SPHEROID[\"GRS_1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",27],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]");

                IProjectedCoordinateSystem utm33 = ProjectedCoordinateSystem.WGS84_UTM(33, true);

                ICoordinateTransformation trans = ctFact.CreateFromCoordinateSystems(utm35ETRS, utm33);

                Coordinate[] points = new Coordinate[]
                {
                    new Coordinate(290586.087, 6714000), new Coordinate(290586.392, 6713996.224),
                    new Coordinate(290590.133, 6713973.772), new Coordinate(290594.111, 6713957.416),
                    new Coordinate(290596.615, 6713943.567), new Coordinate(290596.701, 6713939.485)
                };

                Coordinate[] tpoints = trans.MathTransform.TransformList(points).ToArray();
            }
            catch (Exception)
            {
                throw;
            }



            return(new string[] { "value1", "value2" });
        }
Пример #11
0
        public void MetersDistanceTaguaTest()
        {
            var brasiliaUtmZone        = 23;
            var originCoordinateSystem = GeographicCoordinateSystem.WGS84;
            var targetCoordinateSystem = ProjectedCoordinateSystem.WGS84_UTM(brasiliaUtmZone, false);

            var transform = new CoordinateTransformationFactory().CreateFromCoordinateSystems(
                originCoordinateSystem, targetCoordinateSystem);

            var catolica         = new GeoAPI.Geometries.Coordinate(-15.8674807, -48.0310518);
            var taguatingaCentro = new GeoAPI.Geometries.Coordinate(-15.8326894, -48.0547287);
            var taguaCenter      = new GeoAPI.Geometries.Coordinate(-15.8026851, -48.0685222);

            var catolicaCoordinate         = new GeoAPI.Geometries.Coordinate(catolica.X, catolica.Y);
            var taguatingaCentroCoordinate = new GeoAPI.Geometries.Coordinate(taguatingaCentro.X, taguatingaCentro.Y);
            var taguaCenterCoordinate      = new GeoAPI.Geometries.Coordinate(taguaCenter.X, taguaCenter.Y);

            var newcatolicaPoint         = transform.MathTransform.Transform(catolicaCoordinate);
            var newTaguatingaCentroPoint = transform.MathTransform.Transform(taguatingaCentroCoordinate);
            var newTaguaCenterPoint      = transform.MathTransform.Transform(taguaCenterCoordinate);

            var distanceTaguatingaCentro = newcatolicaPoint.Distance(newTaguatingaCentroPoint);
            var distanceTaguaCenter      = newcatolicaPoint.Distance(newTaguaCenterPoint);

            distanceTaguaCenter.ShouldBeGreaterThan(distanceTaguatingaCentro);

            //try in strait line, at least this works
        }
Пример #12
0
        public static SpatialReference SpRefFromWKT(ref string wkt)
        {
            SpatialReference result;

            try
            {
                if (wkt.StartsWith("PROJCS", StringComparison.CurrentCultureIgnoreCase))
                {
                    result = new ProjectedCoordinateSystem
                    {
                        WKT = wkt
                    };
                }
                else if (wkt.StartsWith("GEOGCS", StringComparison.CurrentCultureIgnoreCase))
                {
                    result = new GeographicCoordinateSystem
                    {
                        WKT = wkt
                    };
                }
                else
                {
                    result = null;
                }
            }
            catch
            {
                result = null;
            }
            return(result);
        }
Пример #13
0
        public void TestTransformSequence()
        {
            var csFact = new CoordinateSystemFactory();
            var ctFact = new CoordinateTransformationFactory();

            var utm35ETRS = csFact.CreateFromWkt(
                "PROJCS[\"ETRS89 / ETRS-TM35\",GEOGCS[\"ETRS89\",DATUM[\"D_ETRS_1989\",SPHEROID[\"GRS_1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",27],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]");

            var utm33 = ProjectedCoordinateSystem.WGS84_UTM(33, true);

            var trans = ctFact.CreateFromCoordinateSystems(utm35ETRS, utm33);

            var points = new NetTopologySuite.Geometries.Implementation.CoordinateArraySequence(
                new []
            {
                new Coordinate(290586.087, 6714000), new Coordinate(290586.392, 6713996.224),
                new Coordinate(290590.133, 6713973.772), new Coordinate(290594.111, 6713957.416),
                new Coordinate(290596.615, 6713943.567), new Coordinate(290596.701, 6713939.485)
            });

            var tpoints = trans.MathTransform.Transform(points);

            for (var i = 0; i < points.Count; i++)
            {
                Assert.AreEqual(trans.MathTransform.Transform(points.GetCoordinate(i)), tpoints.GetCoordinate(i));
            }
        }
Пример #14
0
        public static SpatialReference SpRefFromWKID(ref int wkid)
        {
            SpatialReference result;

            try
            {
                if (!MapServiceFidTests.IsGeographicWKID(wkid))
                {
                    result = new ProjectedCoordinateSystem
                    {
                        WKID          = wkid,
                        WKIDSpecified = true
                    };
                }
                else
                {
                    result = new GeographicCoordinateSystem
                    {
                        WKID          = wkid,
                        WKIDSpecified = true
                    };
                }
            }
            catch
            {
                result = null;
            }
            return(result);
        }
Пример #15
0
        public void TestTransformListOfDoubleArray()
        {
            var csFact = new CoordinateSystemFactory();
            var ctFact = new CoordinateTransformationFactory();

            var utm35ETRS = csFact.CreateFromWkt(
                "PROJCS[\"ETRS89 / ETRS-TM35\",GEOGCS[\"ETRS89\",DATUM[\"D_ETRS_1989\",SPHEROID[\"GRS_1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",27],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]");

            var utm33 = ProjectedCoordinateSystem.WGS84_UTM(33, true);

            var trans = ctFact.CreateFromCoordinateSystems(utm35ETRS, utm33);

            var points = new List <double[]>
            {
                new[] { 290586.087, 6714000 }, new[] { 90586.392, 6713996.224 },
                new[] { 290590.133, 6713973.772 }, new[] { 290594.111, 6713957.416 },
                new[] { 290596.615, 6713943.567 }, new[] { 290596.701, 6713939.485 }
            };

            var tpoints = trans.MathTransform.TransformList(points).ToArray();

            for (var i = 0; i < points.Count; i++)
            {
                Assert.IsTrue(Equal(tpoints[i], trans.MathTransform.Transform(points[i])));
            }
        }
Пример #16
0
 public void TestConversion()
 {
     var point     = GeometryFactory.Default.CreatePoint(new Coordinate(492155.73, 6303867.82));
     var transform = new CoordinateTransformationFactory().CreateFromCoordinateSystems(
         ProjectedCoordinateSystem.WGS84_UTM(32, true), GeographicCoordinateSystem.WGS84);
     var transformedPoint = GeometryTransform.TransformGeometry(GeometryFactory.Default, point, transform.MathTransform);
 }
        public static string CoordinatesConvertor(double InputX,double InputY, int InputWKID, int OutputWKID)
        {
            Geometry_GeometryServer geometryService = new Geometry_GeometryServer();

            SpatialReference inputSpatialReference = new GeographicCoordinateSystem();

            inputSpatialReference.WKID = InputWKID;

            inputSpatialReference.WKIDSpecified = true;

            SpatialReference outputSpatialReference = new ProjectedCoordinateSystem();

            outputSpatialReference.WKID = OutputWKID;

            outputSpatialReference.WKIDSpecified = true;

            PointN pt = new PointN();
            pt.X = InputX;
            pt.Y = InputY;

            Geometry[] inGeo = new Geometry[] { pt };

            Geometry[] geo = geometryService.Project(inputSpatialReference, outputSpatialReference, false, null, null, inGeo);
            PointN nPt = (PointN)geo[0];

            return (nPt.X.ToString() + ',' + nPt.Y.ToString());
        }
Пример #18
0
        public void TestMathTransformBug()
        {
            var coordinateTransformFactory = new CoordinateTransformationFactory();
            var coordinateSystemFactory    = new CoordinateSystemFactory();
            var itmParameters = new List <ProjectionParameter>
            {
                new ProjectionParameter("latitude_of_origin", 31.734393611111109123611111111111),
                new ProjectionParameter("central_meridian", 35.204516944444442572222222222222),
                new ProjectionParameter("false_northing", 626907.390),
                new ProjectionParameter("false_easting", 219529.584),
                new ProjectionParameter("scale_factor", 1.0000067)
            };

            var itmDatum = coordinateSystemFactory.CreateHorizontalDatum("Isreal 1993", DatumType.HD_Geocentric,
                                                                         Ellipsoid.GRS80, new Wgs84ConversionInfo(-24.0024, -17.1032, -17.8444, -0.33077, -1.85269, 1.66969, 5.4248));

            var itmGeo = coordinateSystemFactory.CreateGeographicCoordinateSystem("ITM", AngularUnit.Degrees, itmDatum,
                                                                                  PrimeMeridian.Greenwich, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North));

            var itmProjection = coordinateSystemFactory.CreateProjection("Transverse_Mercator", "Transverse_Mercator", itmParameters);
            var itm           = coordinateSystemFactory.CreateProjectedCoordinateSystem("ITM", itmGeo, itmProjection, LinearUnit.Metre,
                                                                                        new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North));

            var wgs84 = ProjectedCoordinateSystem.WGS84_UTM(36, true).GeographicCoordinateSystem;

            var ctFwd = _css.CreateTransformation(itm, wgs84).MathTransform;
            var pt1a  = (x : 200000.0, y : 600000.0);
            var pt2a  = ctFwd.Transform(pt1a.x, pt1a.y);
            var pt1b  = ctFwd.Inverse().Transform(pt2a.x, pt2a.y);
            var pt2b  = ctFwd.Transform(pt1a.x, pt1a.y);

            Assert.That(pt1a.x, Is.EqualTo(pt1b.x).Within(0.01));
            Assert.That(pt1a.y, Is.EqualTo(pt1b.y).Within(0.01));
            Assert.That(pt2a, Is.EqualTo(pt2b));
        }
Пример #19
0
        public static void Main(string[] args)
        {
            var ctFact = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();

            _trans = ctFact.CreateFromCoordinateSystems(ProjectedCoordinateSystem.WGS84_UTM(33, true), GeographicCoordinateSystem.WGS84);

            var naturområdeTyper           = ReadAll <NaturområdeType>("NaturområdeType");
            var beskrivelsesVariabler      = ReadAll <Beskrivelsesvariabel>("Beskrivelsesvariabel");
            var rødlistekategori           = ReadAll <Rødlistekategori>("Rødlistekategori");
            var kategoriSet                = ReadAll <KategoriSet>("KategoriSet");
            var rødlisteVurderingsenhetSet = ReadAll <RødlisteVurderingsenhetSet>("RødlisteVurderingsenhetSet");

            var geometries = ReadGeometries();

            var root = new root();

            var i = 0;

            Parallel.ForEach(geometries, naturområde =>
            {
                Interlocked.Increment(ref i);

                if (naturområdeTyper.All(n => n.Naturområde_id != naturområde.Id) &&
                    beskrivelsesVariabler.All(b => b.Naturområde_id != naturområde.Id))
                {
                    return;
                }

                try
                {
                    var flexible = GenerateFlexible(naturområde);

                    AddBeskrivelsesVariabler(beskrivelsesVariabler, flexible);

                    AddNaturområdeTyper(naturområdeTyper, flexible);

                    AddRødlistekategori(rødlisteVurderingsenhetSet, rødlistekategori, kategoriSet, flexible);

                    root.features.Add(flexible);
                }
                catch (Exception e)
                {
                    Console.Write("ERROR: Id " + naturområde.Id + ". " + e.Message);
                    Console.WriteLine();
                    return;
                }


                if (i % 100 == 0 && i != 0)
                {
                    Console.Write("\r{0}%   ", (int)(1.0 * i / geometries.Count * 100));
                }
            });

            var json = JsonConvert.SerializeObject(root);

            File.WriteAllText(@"c:\tmp\naturomrader9.json", json);
        }
Пример #20
0
        public UtmPosition TransformFromWGS(int pToZone)
        {
            var vDestinationUTM = ProjectedCoordinateSystem.WGS84_UTM(pToZone, true);
            CoordinateTransformationFactory vTransformerFactory = new CoordinateTransformationFactory();
            var vTransformer = vTransformerFactory.CreateFromCoordinateSystems(GeographicCoordinateSystem.WGS84, vDestinationUTM);

            double[] vTransformed = vTransformer.MathTransform.Transform(new double[] { this.Easting, this.Northing });
            return(new UtmPosition(pToZone, vTransformed[0], vTransformed[1]));
        }
        public Wgs84UtmProjection(int zone, bool north)
        {
            if (zone < 1 || zone > 60)
            {
                throw new ArgumentException($"Invalid UTM zone {zone}.", nameof(zone));
            }

            CoordinateSystem = ProjectedCoordinateSystem.WGS84_UTM(zone, north);
        }
Пример #22
0
        public UtmPosition TransformToWGS()
        {
            var vSourceUTM = ProjectedCoordinateSystem.WGS84_UTM(this.Zone, true);
            CoordinateTransformationFactory vTransformerFactory = new CoordinateTransformationFactory();
            var vTransformer = vTransformerFactory.CreateFromCoordinateSystems(vSourceUTM, GeographicCoordinateSystem.WGS84);

            double[] vTransformed = vTransformer.MathTransform.Transform(new double[] { this.Easting, this.Northing });
            return(new UtmPosition(0, vTransformed[0], vTransformed[1]));
        }
Пример #23
0
        private IMathTransform CreateTransformation(string utmZone)
        {
            bool isNorthHemisphere = utmZone[utmZone.Length - 1] >= 'N';
            var  zone = int.Parse(utmZone.Substring(0, utmZone.Length - 1));

            IProjectedCoordinateSystem pcsUTM = ProjectedCoordinateSystem.WGS84_UTM(zone, isNorthHemisphere);
            var transformation = this.coordinateTransformationFactory.CreateFromCoordinateSystems(this.gcsWGS84, pcsUTM);

            return(transformation.MathTransform);
        }
Пример #24
0
        private double[] TransformToUTM(Coordinate p)
        {
            //For fun, let's use the SharpMap transformation library and display the position in UTM
            int zone   = (int)Math.Floor((p.X + 183) / 6.0);
            var proj   = ProjectedCoordinateSystem.WGS84_UTM(zone, (p.Y >= 0));
            var trans  = new CoordinateTransformationFactory().CreateFromCoordinateSystems(proj.GeographicCoordinateSystem, proj);
            var result = trans.MathTransform.Transform(new[] { p.X, p.Y });

            return(new[] { result[0], result[1], zone });
        }
Пример #25
0
        public double[] ConvertToUTM(double lat, double lon)
        {
            CoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;
            CoordinateSystem utm33 = ProjectedCoordinateSystem.WGS84_UTM(33, true);
            var fact           = new CoordinateTransformationFactory();
            var transformation = fact.CreateFromCoordinateSystems(wgs84, utm33);

            double[] utm = transformation.MathTransform.Transform(new double[] { lon, lat });
            return(utm);
        }
Пример #26
0
        public static List <double[]> ToUTM(int utmzone, List <PointLatLngAlt> list)
        {
            IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(Math.Abs(utmzone), list[0].Lat < 0 ? false : true);

            ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

            List <double[]> data = new List <double[]>();

            list.ForEach(x => { data.Add((double[])x); });

            return(trans.MathTransform.TransformList(data));
        }
        /// <summary>
        /// Reads a projected coordinate system.
        /// </summary>
        private static IProjectedCoordinateSystem ReadProjectedCoordinateSystem(WktStreamTokenizer tokenizer)
        {
            tokenizer.ReadToken("[");
            string name = tokenizer.ReadDoubleQuotedWord();

            tokenizer.ReadToken(",");
            tokenizer.ReadToken("GEOGCS");
            IGeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer);

            tokenizer.ReadToken(",");
            IProjection projection = ReadProjection(tokenizer);
            IUnit       unit       = ReadLinearUnit(tokenizer);

            string authority     = String.Empty;
            long   authorityCode = -1;

            tokenizer.NextToken();
            List <AxisInfo> axes = new List <AxisInfo>(2);

            if (tokenizer.GetStringValue() == ",")
            {
                tokenizer.NextToken();
                while (tokenizer.GetStringValue() == "AXIS")
                {
                    axes.Add(ReadAxis(tokenizer));
                    tokenizer.NextToken();
                    if (tokenizer.GetStringValue() == ",")
                    {
                        tokenizer.NextToken();
                    }
                }
                if (tokenizer.GetStringValue() == ",")
                {
                    tokenizer.NextToken();
                }
                if (tokenizer.GetStringValue() == "AUTHORITY")
                {
                    //tokenizer.ReadAuthority(ref authority, ref authorityCode);
                    ReadAuthority(tokenizer, ref authority, ref authorityCode);
                    tokenizer.ReadToken("]");
                }
            }
            //This is default axis values if not specified.
            if (axes.Count == 0)
            {
                axes.Add(new AxisInfo("X", AxisOrientationEnum.East));
                axes.Add(new AxisInfo("Y", AxisOrientationEnum.North));
            }
            IProjectedCoordinateSystem projectedCS = new ProjectedCoordinateSystem(geographicCS.HorizontalDatum, geographicCS, unit as LinearUnit, projection, axes, name, authority, authorityCode, String.Empty, String.Empty, String.Empty);

            return(projectedCS);
        }
        private static IProjectedCoordinateSystem ReadProjectedCoordinateSystem(WktStreamTokenizer tokenizer)
        {
            /*			PROJCS[
             *      "OSGB 1936 / British National Grid",
             *      GEOGCS[
             *              "OSGB 1936",
             *              DATUM[...]
             *              PRIMEM[...]
             *              AXIS["Geodetic latitude","NORTH"]
             *              AXIS["Geodetic longitude","EAST"]
             *              AUTHORITY["EPSG","4277"]
             *      ],
             *      PROJECTION["Transverse Mercator"],
             *      PARAMETER["latitude_of_natural_origin",49],
             *      PARAMETER["longitude_of_natural_origin",-2],
             *      PARAMETER["scale_factor_at_natural_origin",0.999601272],
             *      PARAMETER["false_easting",400000],
             *      PARAMETER["false_northing",-100000],
             *      AXIS["Easting","EAST"],
             *      AXIS["Northing","NORTH"],
             *      AUTHORITY["EPSG","27700"]
             * ]
             */
            tokenizer.ReadToken("[");
            string name = tokenizer.ReadDoubleQuotedWord();

            tokenizer.ReadToken(",");
            tokenizer.ReadToken("GEOGCS");
            IGeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer);

            tokenizer.ReadToken(",");
            IProjection projection = ReadProjection(tokenizer);
            IAxisInfo   axis0      = ReadAxisInfo(tokenizer);

            tokenizer.ReadToken(",");
            tokenizer.ReadToken("AXIS");
            IAxisInfo axis1 = ReadAxisInfo(tokenizer);

            tokenizer.ReadToken(",");
            string authority     = "";
            string authorityCode = "";

            tokenizer.ReadAuthority(ref authority, ref authorityCode);
            tokenizer.ReadToken("]");
            IAxisInfo[] axisArray = new IAxisInfo[2];
            axisArray[0] = axis0;
            axisArray[1] = axis1;
            ILinearUnit linearUnit = LinearUnit.Meters;
            IProjectedCoordinateSystem projectedCS = new ProjectedCoordinateSystem(null, axisArray, geographicCS, linearUnit, projection, "", authority, authorityCode, name, "", "");

            return(projectedCS);
        }
Пример #29
0
        // force a zone
        public double[] ToUTM(int utmzone)
        {
            IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(Math.Abs(utmzone), Lat < 0 ? false : true);

            ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

            double[] pll = { Lng, Lat };

            // get leader utm coords
            double[] utmxy = trans.MathTransform.Transform(pll);

            return(utmxy);
        }
Пример #30
0
        public void TestProjectedCoordinateSystem_EPSG27700_UnitBeforeProjection()
        {
            const string wkt = "PROJCS[\"OSGB 1936 / British National Grid\"," +
                               "GEOGCS[\"OSGB 1936\"," +
                               "DATUM[\"OSGB_1936\"," +
                               "SPHEROID[\"Airy 1830\",6377563.396,299.3249646,AUTHORITY[\"EPSG\",\"7001\"]]," +
                               "AUTHORITY[\"EPSG\",\"6277\"]]," +
                               "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," +
                               "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]]," +
                               "AUTHORITY[\"EPSG\",\"4277\"]]," +
                               "UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]]," +
                               "PROJECTION[\"Transverse_Mercator\"]," +
                               "PARAMETER[\"latitude_of_origin\",49]," +
                               "PARAMETER[\"central_meridian\",-2]," +
                               "PARAMETER[\"scale_factor\",0.9996012717]," +
                               "PARAMETER[\"false_easting\",400000]," +
                               "PARAMETER[\"false_northing\",-100000]," +
                               "AUTHORITY[\"EPSG\",\"27700\"]," +
                               "AXIS[\"Easting\",EAST]," +
                               "AXIS[\"Northing\",NORTH]]";

            ProjectedCoordinateSystem pcs = null;

            Assert.That(() => pcs = _coordinateSystemFactory.CreateFromWkt(wkt) as ProjectedCoordinateSystem, Throws.Nothing);

            CheckInfo(pcs, "OSGB 1936 / British National Grid", "EPSG", 27700);

            var gcs = pcs.GeographicCoordinateSystem;

            CheckInfo(gcs, "OSGB 1936", "EPSG", 4277);
            CheckDatum(gcs.HorizontalDatum, "OSGB_1936", "EPSG", 6277);
            CheckEllipsoid(gcs.HorizontalDatum.Ellipsoid, "Airy 1830", 6377563.396, 299.3249646, "EPSG", 7001);
            CheckPrimem(gcs.PrimeMeridian, "Greenwich", 0, "EPSG", 8901);
            CheckUnit(gcs.AngularUnit, "degree", 0.0174532925199433, "EPSG", 9122);

            Assert.AreEqual("Transverse_Mercator", pcs.Projection.ClassName, "Projection Classname");
            CheckProjection(pcs.Projection, "Transverse_Mercator", new []
            {
                Tuple.Create("latitude_of_origin", 49d),
                Tuple.Create("central_meridian", -2d),
                Tuple.Create("scale_factor", 0.9996012717),
                Tuple.Create("false_easting", 400000d),
                Tuple.Create("false_northing", -100000d)
            });

            CheckUnit(pcs.LinearUnit, "metre", 1d, "EPSG", 9001);

            string newWkt = pcs.WKT.Replace(", ", ",");

            Assert.AreEqual(wkt, newWkt);
        }
Пример #31
0
        double calcpolygonarea(List <PointLatLng> polygon)
        {
            // should be a closed polygon
            // coords are in lat long
            // need utm to calc area

            if (polygon.Count == 0)
            {
                CustomMessageBox.Show("Please define a polygon!");
                return(0);
            }

            // close the polygon
            if (polygon[0] != polygon[polygon.Count - 1])
            {
                polygon.Add(polygon[0]); // make a full loop
            }
            CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

            IGeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

            int utmzone = (int)((polygon[0].Lng - -186.0) / 6.0);

            IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone, polygon[0].Lat < 0 ? false : true);

            ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

            double prod1 = 0;
            double prod2 = 0;

            for (int a = 0; a < (polygon.Count - 1); a++)
            {
                double[] pll1 = { polygon[a].Lng, polygon[a].Lat };
                double[] pll2 = { polygon[a + 1].Lng, polygon[a + 1].Lat };

                double[] p1 = trans.MathTransform.Transform(pll1);
                double[] p2 = trans.MathTransform.Transform(pll2);

                prod1 += p1[0] * p2[1];
                prod2 += p1[1] * p2[0];
            }

            double answer = (prod1 - prod2) / 2;

            if (polygon[0] == polygon[polygon.Count - 1])
            {
                polygon.RemoveAt(polygon.Count - 1); // unmake a full loop
            }
            return(Math.Abs(answer));
        }
 ////private static int _defaultWkid = int.Parse(ConfigurationManager.AppSettings["DefaultSpatialReference"]);
 ////private static int _sqlSR = int.Parse(ConfigurationManager.AppSettings["SqlSpatialReferenceWkid"]);
 /////// <summary>
 /////// The default spatial reference id (probably WGS_84 - id: 4326)
 /////// </summary>
 ////public static int DefaultSpatialReferenceId { get { return _defaultWkid; } }
 /////// <summary>
 /////// The default spatial reference system
 /////// </summary>
 ////public static SpatialReference DefaultSpatialReference { get { return DefaultSpatialReferenceId.ToSpatialReference(); } }
 /////// <summary>
 /////// The spatial reference that will be used when writing geometry data to a SQL Server database.
 /////// </summary>
 ////public static int SqlSpatialReference { get { return _sqlSR; } }
 ////public static int[] ProjectedWkids { get { return _projectedWkids; } }
 ////public static int[] GeographicWkids { get { return _geographicWkids; } }
 /// <summary>
 /// Returns a <see cref="SpatialReference"/> object corresponding to the specified WKID.
 /// </summary>
 /// <param name="wkid">A Well-Known Identifier (WKID) for a spatial reference system.</param>
 /// <returns>
 /// <para>Returns a <see cref="SpatialReference"/> object corresponding to <paramref name="wkid"/>.</para>
 /// <para>
 /// If <paramref name="wkid"/> matches one of the values defined in web.config,
 /// either a <see cref="GeographicCoordinateSystem"/> or <see cref="ProjectedCoordinateSystem"/>
 /// is returned.  Otherwise a <see cref="UnknownCoordinateSystem"/> is returned.
 /// </para>
 /// </returns>
 public static SpatialReference ToSpatialReference(this int wkid)
 {
     SpatialReference sr;
     if (_projectedWkids.Contains(wkid))
     {
         sr = new ProjectedCoordinateSystem();
     }
     else if (_geographicWkids.Contains(wkid))
     {
         sr = new GeographicCoordinateSystem();
     }
     else
     {
         sr = new UnknownCoordinateSystem();
     }
     sr.WKID = wkid;
     sr.WKIDSpecified = true;
     return sr;
 }
        /// <summary>
        /// Create a CIM Spatial Reference. Has to be created from scratch
        /// </summary>
        /// <param name="WKID">The wkid for the spatial reference to be created</param>
        /// <returns>A CIM spatial reference</returns>
        public SpatialReference CreateSpatialReference(int WKID)
        {
            SpatialReference sr = null;
            if (WKID == 104115 || WKID == 4326)
            {
                GeographicCoordinateSystem gs = new GeographicCoordinateSystem();
                gs.WKID = 104115;
                gs.WKIDSpecified = true;
                gs.LatestWKID = 104115;
                gs.LatestVCSWKIDSpecified = true;
                gs.LeftLongitude = -180;
                gs.LeftLongitudeSpecified = true;
                gs.HighPrecision = true;
                gs.HighPrecisionSpecified = true;
                gs.MTolerance = 0.001;
                gs.MToleranceSpecified = true;
                gs.ZTolerance = 0.001;
                gs.ZToleranceSpecified = true;
                gs.XYTolerance = 8.9831528411952133E-09;
                gs.XYToleranceSpecified = true;
                gs.MScale = 10000;
                gs.MScaleSpecified = true;
                gs.MOrigin = -100000;
                gs.MOriginSpecified = true;
                gs.ZScale = 10000;
                gs.ZScaleSpecified = true;
                gs.ZOrigin = -100000;
                gs.ZOriginSpecified = true;
                gs.XYScale = 999999999.99999988;
                gs.XYScaleSpecified = true;
                gs.XOrigin = -400;
                gs.XOriginSpecified = true;
                gs.YOrigin = -400;
                gs.YOriginSpecified = true;
                gs.WKT = "GEOGCS[\"GCS_ITRF_1988\",DATUM[\"D_ITRF_1988\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433],AUTHORITY[\"ESRI\",104115]]";
                sr = gs as SpatialReference;

            }
            else if (WKID == 102100)
            {
                //Note: In testing, I could not get Web Mercator to
                //work on the mapview.
                ProjectedCoordinateSystem pcs = new ProjectedCoordinateSystem();
                pcs.HighPrecision = true;
                pcs.HighPrecisionSpecified = true;
                pcs.LatestVCSWKID = 0;
                pcs.LatestVCSWKIDSpecified = false;
                pcs.LatestWKID = 3857;
                pcs.LatestWKIDSpecified = true;
                pcs.LeftLongitude = 0.0;
                pcs.LeftLongitudeSpecified = false;
                pcs.MOrigin = -100000.0;
                pcs.MOriginSpecified = true;
                pcs.MScale = 10000.0;
                pcs.MScaleSpecified = true;
                pcs.MTolerance = 0.001;
                pcs.MToleranceSpecified = true;
                pcs.VCSWKID = 0;
                pcs.VCSWKIDSpecified = false;
                pcs.WKID = 102100;
                pcs.WKIDSpecified = true;
                pcs.WKT = "PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"false ;_Easting\",0.0],PARAMETER[\"false ;_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0],AUTHORITY[\"EPSG\",3857]]";
                pcs.XOrigin = -20037700.0;
                pcs.XOriginSpecified = true;
                pcs.XYScale = 10000.0;
                pcs.XYScaleSpecified = true;
                pcs.XYTolerance = 0.001;
                pcs.XYToleranceSpecified = true;
                pcs.YOrigin = -30241100.0;
                pcs.YOriginSpecified = true;
                pcs.ZOrigin = -100000.0;
                pcs.ZOriginSpecified = true;
                pcs.ZScale = 10000.0;
                pcs.ZScaleSpecified = true;
                pcs.ZTolerance = 0.001;
                pcs.ZToleranceSpecified = true;
                sr = pcs as SpatialReference;
            }
            else
            {
                throw new System.NotImplementedException(string.Format("Sorry. Support for wkid {0} is not implemented in this example", WKID));
            }
            return sr;
        }