Example #1
0
 public static void Main(string[] args)
 {
     try
     {
         /* -------------------------------------------------------------------- */
         /*      Initialize srs                                                  */
         /* -------------------------------------------------------------------- */
         SpatialReference src = new SpatialReference("");
         src.ImportFromProj4("+proj=latlong +datum=WGS84 +no_defs");
         Console.WriteLine("SOURCE IsGeographic:" + src.IsGeographic() + " IsProjected:" + src.IsProjected());
         SpatialReference dst = new SpatialReference("");
         dst.ImportFromProj4("+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 +x_0=650000 +y_0=200000 +ellps=GRS67 +units=m +no_defs");
         Console.WriteLine("DEST IsGeographic:" + dst.IsGeographic() + " IsProjected:" + dst.IsProjected());
         /* -------------------------------------------------------------------- */
         /*      making the transform                                            */
         /* -------------------------------------------------------------------- */
         CoordinateTransformation ct = new CoordinateTransformation(src, dst);
         double[] p = new double[3];
         p[0] = 19; p[1] = 47; p[2] = 0;
         ct.TransformPoint(p);
         Console.WriteLine("x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
         ct.TransformPoint(p, 19.2, 47.5, 0);
         Console.WriteLine("x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
     }
     catch (Exception e)
     {
         Console.WriteLine("Error occurred: " + e.Message);
         System.Environment.Exit(-1);
     }
 }
        /// <summary>
        /// 坐标系转换
        /// </summary>
        /// <param name="IN"></param>
        /// <param name="T"></param>
        /// <param name="OUT"></param>
        public LocationMap Calculation(LocationMap IN, CoordinateTransformation T)
        {
            LocationMap Loc = new LocationMap();


            return(Loc);
        }
Example #3
0
        public static void Transform(Proj4Projection src, Proj4Projection dst,
                                     double[] x, double[] y, double[] z)
        {
            lock (lockObj)
            {
                //Proj4Projection.CheckInitialized(src);
                //Proj4Projection.CheckInitialized(dst);
                if (x == null)
                {
                    throw new ArgumentException("Argument is required", "x");
                }

                if (y == null)
                {
                    throw new ArgumentException("Argument is required", "y");
                }

                if (x.Length != y.Length || (z != null && z.Length != x.Length))
                {
                    throw new ArgumentException("Coordinate arrays must have the same length");
                }

                CoordinateTransformation trans = new CoordinateTransformation(src.srs, dst.srs);

                trans.TransformPoints(x.Length, x, y, z);
            }
        }
        private void imageshow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CoordinateTransformation dd = new CoordinateTransformation();

            Mat    rgb     = null;
            string rgbpath = System.IO.Path.Combine(Global.ImageDataPath, "rgb_" + pCurrentImage.ToString("D5") + ".jpg");

            rgb = Cv2.ImRead(rgbpath);

            OpenCvSharp.Size imagesize = rgb.Size();



            int inputx = ((int)e.GetPosition(imageshow).X *imagesize.Width) / ((int)imageshow.ActualWidth);
            int inputy = ((int)e.GetPosition(imageshow).Y *imagesize.Height) / ((int)imageshow.ActualHeight);



            pt = dd.getvalue(pCurrentImage, inputx, inputy);
            //   Console.WriteLine(pt);
            if (pt != new Point3D(0, 0, 0))
            {
                VIewer3D.Instance.ClickedCoordinate();
            }
        }
Example #5
0
        public static double GetVariationEclipticLongitude(double julianDate)
        {
            var    millenniasCount = Tools.GetMillenniasCount(julianDate);
            double deltaLambda     = 3548.193
                                     + 118.568 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(87.5287 + 359993.7286 * millenniasCount))
                                     + 2.476 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(85.0561 + 719987.4571 * millenniasCount))
                                     + 1.376 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(27.8502 + 4452671.1152 * millenniasCount))
                                     + 0.119 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(73.1375 + 450368.8564 * millenniasCount))
                                     + 0.114 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(337.2264 + 329644.6718 * millenniasCount))
                                     + 0.086 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(222.5400 + 659289.3436 * millenniasCount))
                                     + 0.078 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(162.8136 + 9224659.7915 * millenniasCount))
                                     + 0.054 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(82.5823 + 1079981.1857 * millenniasCount))
                                     + 0.052 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(171.5189 + 225184.4282 * millenniasCount))
                                     + 0.034 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(30.3214 + 4092677.3866 * millenniasCount))
                                     + 0.033 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(119.8105 + 337181.4711 * millenniasCount))
                                     + 0.023 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(247.5418 + 299295.6151 * millenniasCount))
                                     + 0.023 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(325.1526 + 315559.5560 * millenniasCount))
                                     + 0.021 * Math.Sin(CoordinateTransformation.SetDegreesToRadians(155.1241 + 675553.2846 * millenniasCount))
                                     + 7.311 * millenniasCount * Math.Sin(CoordinateTransformation.SetDegreesToRadians(333.4515 + 359993.7286 * millenniasCount))
                                     + 0.305 * millenniasCount * Math.Sin(CoordinateTransformation.SetDegreesToRadians(330.9814 + 719987.4571 * millenniasCount))
                                     + 0.010 * millenniasCount * Math.Sin(CoordinateTransformation.SetDegreesToRadians(328.5170 + 1079981.1857 * millenniasCount))
                                     + 0.309 * Tools.GetRaisedValue(millenniasCount, Power.Square) * Math.Sin(CoordinateTransformation.SetDegreesToRadians(241.4518 + 359993.7286 * millenniasCount))
                                     + 0.021 * Tools.GetRaisedValue(millenniasCount, Power.Square) * Math.Sin(CoordinateTransformation.SetDegreesToRadians(205.0482 + 719987.4571 * millenniasCount))
                                     + 0.004 * Tools.GetRaisedValue(millenniasCount, Power.Square) * Math.Sin(CoordinateTransformation.SetDegreesToRadians(297.8610 + 4452671.1152 * millenniasCount))
                                     + 0.010 * Tools.GetRaisedValue(millenniasCount, Power.Cube) * Math.Sin(CoordinateTransformation.SetDegreesToRadians(154.7066 + 359993.7286 * millenniasCount));

            return(deltaLambda);
        }
Example #6
0
        public static Extent TransformExtent(this CoordinateTransformation coordinateTransformation, Extent extent)
        {
            Extent destExtent = null;

            if (coordinateTransformation != null && extent != null)
            {
                double[] xs = { extent.MinX, extent.MaxX };
                double[] ys = { extent.MinY, extent.MaxY };
                double[] zs = { 0, 0 };
                coordinateTransformation.TransformPoints(2, xs, ys, zs);
                double minX, minY, maxX, maxY;
                if (xs[0] > xs[1])
                {
                    minX = xs[1];
                    maxX = xs[0];
                }
                else
                {
                    minX = xs[0];
                    maxX = xs[1];
                }
                if (ys[0] > ys[1])
                {
                    minY = ys[1];
                    maxY = ys[0];
                }
                else
                {
                    minY = ys[0];
                    maxY = ys[1];
                }
                destExtent = new Extent(minX, minY, maxX, maxY);
            }
            return(destExtent);
        }
Example #7
0
        /// <summary>
        /// Converter as coordenadas de WGS 84 / UTM zone 23S para latitude e longitude em graus
        /// </summary>
        /// <param name="lonLat">Array de vetor com as duas coordenadas Geodesicas</param>
        /// <param name="tifProjectionReference"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static double[] LonLatToTifCoordinates(double[][] lonLat, string tifProjectionReference, int imgWidth, int imgHeight)
        {
            // referência do arquivo tif em WGS 84 / UTM zone 23S
            SpatialReference newReference = new SpatialReference(tifProjectionReference);
            // referência em latitude e longitude
            SpatialReference currentReference = GdalUtilities.getWgs84Reference();

            CoordinateTransformation ct = new CoordinateTransformation(currentReference, newReference);

            double[] tifGeoTransformerData = new double[6];
            double[] northwest             = new double[2] {
                lonLat[0][0], lonLat[0][1]
            };
            double[] southeast = new double[2] {
                lonLat[1][0], lonLat[1][1]
            };

            ct.TransformPoint(northwest);
            ct.TransformPoint(southeast);
            southeast = new double[2] {
                (southeast[0] - northwest[0]) / imgWidth,
                (southeast[1] - northwest[1]) / imgHeight
            };

            tifGeoTransformerData[0] = northwest[0];
            tifGeoTransformerData[1] = southeast[0];
            tifGeoTransformerData[2] = 0;
            tifGeoTransformerData[3] = northwest[1];
            tifGeoTransformerData[4] = 0;
            tifGeoTransformerData[5] = southeast[1];

            return(tifGeoTransformerData);
        }
Example #8
0
        /// <summary>
        /// Converter as coordenadas de WGS 84 / UTM zone 23S para latitude e longitude em graus
        /// </summary>
        /// <returns>Array com as coordenadas geodésicas do canto superior esquerdo da imagem e inferior direito, respectivamente</returns>
        public static double[][] TifCoordinatesToLonLat(double[] tifGeoTransformerData, string tifProjectionReference, int imgWidth, int imgHeight)
        {
            // referência atual em WGS 84 / UTM zone 23S
            SpatialReference currentReference = new SpatialReference(tifProjectionReference);
            // referência em latitude e longitude
            SpatialReference newReference = getWgs84Reference();

            CoordinateTransformation ct = new CoordinateTransformation(currentReference, newReference);

            double[] northWestPoint = new double[2] {
                tifGeoTransformerData[0], tifGeoTransformerData[3]
            };
            ct.TransformPoint(northWestPoint);
            double[] northwest = new double[] {
                northWestPoint[0], // x
                northWestPoint[1]  // y
            };

            double[] southEastPoint = new double[2] {
                tifGeoTransformerData[0] + tifGeoTransformerData[1] * imgWidth,
                tifGeoTransformerData[3] + tifGeoTransformerData[5] * imgHeight
            };
            ct.TransformPoint(southEastPoint);
            double[] southeast = new double[] {
                southEastPoint[0], // x
                southEastPoint[1]  // y
            };

            return(new double[][] { northwest, southeast });
        }
Example #9
0
        public static double GetSunEclipticLongitude(double julianDate, bool highPrecision)
        {
            if (highPrecision)
            {
                return
                    (CoordinateTransformation.MapTo0To360Range
                         (CoordinateTransformation.SetRadiansToDegrees
                             (CalculateEarthPosition(julianDate)))); // Вроде как для высокой точности
            }
            else
            {
                double julianMillennias = Tools.GetMillenniasCount(julianDate);

                var sunLongitudeBase        = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeBaseArray(), julianMillennias);
                var sunLongitudeFirstGroup  = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeFirstArray(), julianMillennias);
                var sunLongitudeSecondGroup = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeSecondArray(), julianMillennias);
                var sunLongitudeThirdGroup  = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeThirdArray(), julianMillennias);
                var sunLongitudeFourthGroup = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeFourthArray(), julianMillennias);
                var sunLongitudeFifthGroup  = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLongitudeFifthArray(), julianMillennias);

                var value = (sunLongitudeBase
                             + sunLongitudeFirstGroup * julianMillennias
                             + sunLongitudeSecondGroup * Tools.GetRaisedValue(julianMillennias, Power.Square)
                             + sunLongitudeThirdGroup * Tools.GetRaisedValue(julianMillennias, Power.Cube)
                             + sunLongitudeFourthGroup * Tools.GetRaisedValue(julianMillennias, Power.Fourth)
                             + sunLongitudeFifthGroup * Tools.GetRaisedValue(julianMillennias, Power.Fifth)) / 100000000;

                //convert results back to degrees
                return(CoordinateTransformation.MapTo0To360Range(CoordinateTransformation.SetRadiansToDegrees(value)));
            }
        }
Example #10
0
        public static double CalculateEarthPosition(double julianDate)
        {
            var    positions        = PositionBySphereEquinoxArray.GetPositions();
            var    length           = positions.Length;
            double julianMillennias = Tools.GetMillenniasCount(julianDate);
            double raisedJulian     = julianMillennias;
            double result           = 0;

            for (int i = 0; i < length; i++)
            {
                double tempResult = 0;
                for (int j = 0; j < positions[i].Size; j++)
                {
                    tempResult += positions[i].GetPositions()[j].First
                                  * Math.Cos(positions[i].GetPositions()[j].Second
                                             + positions[i].GetPositions()[j].Third * julianMillennias);
                }
                if (i > 0)
                {
                    tempResult   *= raisedJulian;
                    raisedJulian *= julianMillennias;
                }
                result += tempResult;
            }
            return(CoordinateTransformation.MapTo0To2PIRange(result));
        }
Example #11
0
        public System.Windows.Point ImageToWorld(double x, double y)
        {
            double[] adfGeoTransform = new double[6];
            double[] p = new double[3];

            dataset.GetGeoTransform(adfGeoTransform);
            p[0] = adfGeoTransform[0] + adfGeoTransform[1] * x + adfGeoTransform[2] * y;
            p[1] = adfGeoTransform[3] + adfGeoTransform[4] * x + adfGeoTransform[5] * y;

            SpatialReference src = new SpatialReference("");
            string           s   = dataset.GetProjectionRef();

            src.ImportFromWkt(ref s);

            SpatialReference wgs84 = new SpatialReference("");

            wgs84.SetWellKnownGeogCS("WGS84");

            CoordinateTransformation ct = new CoordinateTransformation(src, wgs84);

            ct.TransformPoint(p);

            ct.Dispose();
            wgs84.Dispose();
            src.Dispose();

            return(new System.Windows.Point(p[0], p[1]));
        }
Example #12
0
        public Moon(Dataset DEM, Dataset DOM)
        {
            _DEM = DEM;
            _DOM = DOM;

            double[] _DEMtrans = new double[6];
            double[] _DOMtrans = new double[6];
            DEM.GetGeoTransform(_DEMtrans);
            DOM.GetGeoTransform(_DOMtrans);


            initMatrix(_DOMtrans, _DEMtrans);


            refPro = new SpatialReference(_DOM.GetProjection());
            refGeo = refPro.CloneGeogCS();

            transGeo2Pro = new CoordinateTransformation(refGeo, refPro);
            _R           = refGeo.GetSemiMajor();

            DEMInter = Interpolate.NEAREST;
            DOMInter = Interpolate.NEAREST;

            _DOMband = _DOM.GetRasterBand(1);
            _DEMband = _DEM.GetRasterBand(1);
        }
Example #13
0
        static void Main(string[] args)
        {
            var kit  = new GdalKit();
            var info = kit.GetGdalInfo();

            Console.WriteLine("Buildinfo: " + info.BuildInfo);
            Console.WriteLine("Releasename: " + info.ReleaseName);
            Console.WriteLine("Versionnumber: " + info.VersionNumber);

            Console.WriteLine("Number of drivers: " + info.Drivers.Count);
            Console.WriteLine("Drivers: " + String.Join(',', info.Drivers));

            // sample reading (city)gml file
            var gmlDriver     = Ogr.GetDriverByName("GML");
            var dsGml         = gmlDriver.Open(@"LoD2_280_5657_1_NW.gml", 0);
            var buildingLayer = dsGml.GetLayerByName("building");
            var featuresGml   = buildingLayer.GetFeatureCount(0);

            Console.WriteLine($"Number of features: {featuresGml}");
            for (var f = 0; f < featuresGml; f++)
            {
                var featureGml = buildingLayer.GetNextFeature();
                var geometry   = featureGml.GetGeometryRef();
                // serialize to wkt... when using wkb there is an error :-(
                var wkt = string.Empty;
                geometry.ExportToWkt(out wkt);
                var geom = Wkx.Geometry.Deserialize <WktSerializer>(wkt);
                // Console.WriteLine(geom.GeometryType + ", " + ((MultiLineString)geom).Geometries.Count); // result is multilinestring...
            }

            // sample read geojson file
            var geojsonDriver = Ogr.GetDriverByName("GeoJSON");
            var ds            = geojsonDriver.Open(@"gemeenten2016.geojson", 0);
            var layer1        = ds.GetLayerByName("gemeenten2016");
            var features      = layer1.GetFeatureCount(0);

            Console.WriteLine("features in geojson: " + features);

            // sample transform coordinate from epsg:28992 to epsg:4326
            var src = new SpatialReference("");

            src.ImportFromEPSG(28992);
            Console.WriteLine("SOURCE IsGeographic:" + src.IsGeographic() + " IsProjected:" + src.IsProjected());
            var dst = new SpatialReference("");

            dst.ImportFromEPSG(4326);
            Console.WriteLine("DEST IsGeographic:" + dst.IsGeographic() + " IsProjected:" + dst.IsProjected());
            var ct = new CoordinateTransformation(src, dst);

            double[] p = new double[3];
            p[0] = 85530; p[1] = 446100; p[2] = 0;
            Console.WriteLine("From: x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
            ct.TransformPoint(p);
            Console.WriteLine("To: x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
            Console.WriteLine("Program finished, press any key to exit.");
            // Console.ReadKey();
        }
        public void TestCoordinateToOrientation()
        {
            DateTime    date            = new DateTime(2018, 11, 15, 13, 00, 00, 00);
            Coordinate  testCoordinate  = new Coordinate(21.5, -14.5);
            Orientation testOrientation = CoordinateTransformation.CoordinateToOrientation(testCoordinate, RT_LAT, RT_LONG, RT_ALT, date);

            Assert.AreEqual(105, testOrientation.Azimuth);
            Assert.AreEqual(-90, testOrientation.Elevation);
        }
Example #15
0
        protected override Task _save()
        {
            RecordSet layer = _layer as RecordSet;

            layer.Position           = transform.position.ToPoint();
            layer.Transform.Position = Vector3.zero;
            layer.Transform.Rotate   = transform.rotation;
            layer.Transform.Scale    = transform.localScale;
            EditableMesh[] meshes = GetComponentsInChildren <EditableMesh>();
            string         ex     = Path.GetExtension(layer.Source).ToLower();

            features = new List <DMesh3>();
            foreach (EditableMesh mesh in meshes)
            {
                features.Add(mesh.GetMesh());
            }
            if (ex == ".obj")
            {
                List <WriteMesh> wmeshes = new List <WriteMesh>();
                foreach (DMesh3 dmesh in features)
                {
                    DMesh3 mesh = new DMesh3(dmesh);
                    foreach (int idx in mesh.VertexIndices())
                    {
                        Vector3d vtx = mesh.GetVertex(idx);
                        mesh.SetVertex(idx, new Vector3d(vtx.x, vtx.z, vtx.y));
                    }
                    wmeshes.Add(new WriteMesh(mesh, ""));
                }
                saveObj(layer.Source, wmeshes);
            }
            if (ex == ".dxf")
            {
                DXF.DxfDocument          doc       = new DXF.DxfDocument();
                CoordinateTransformation transform = null;
                if (GetCrs() != null)
                {
                    transform = new CoordinateTransformation(AppState.instance.mapProj, GetCrs());
                }
                foreach (DMesh3 dmesh in features)
                {
                    foreach (Index3i tri in dmesh.Triangles())
                    {
                        DXF.Vector3 v1 = dmesh.GetVertex(tri.a).ToDxfVector3(transform);
                        DXF.Vector3 v2 = dmesh.GetVertex(tri.b).ToDxfVector3(transform);
                        DXF.Vector3 v3 = dmesh.GetVertex(tri.c).ToDxfVector3(transform);
                        doc.AddEntity(new Face3d(v1, v2, v3));
                    }
                }
                using (Stream stream = File.Open(layer.Source, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) {
                    doc.Save(stream);
                    stream.Close();
                }
            }
            return(Task.CompletedTask);
        }
Example #16
0
        static void CreateIndexes(DataSource OGRDataSource, string MSSQLConnectionString)
        {
            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");

            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");

            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
            {
                Layer  OGRLayer  = OGRDataSource.GetLayerByIndex(iLayer);
                string layerName = OGRLayer.GetName();

                // Get extent in EPSG:900913
                Envelope extent = new Envelope();
                OGRLayer.GetExtent(extent, 0);
                double[] ll = new double[] { extent.MinX, extent.MinY };
                double[] ur = new double[] { extent.MaxX, extent.MaxY };
                transform.TransformPoint(ll);
                transform.TransformPoint(ur);

                using (SqlConnection con = new SqlConnection(MSSQLConnectionString))
                {
                    con.Open();
                    try
                    {
                        // Create primary key/clustered index
                        string pkSQL = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED([id] ASC)  WITH (SORT_IN_TEMPDB = ON);", layerName);
                        using (SqlCommand pkCmd = new SqlCommand(pkSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating clustured index pk_{0} on table {0}...", layerName));
                            pkCmd.CommandTimeout = 0;
                            pkCmd.ExecuteNonQuery();
                        }

                        // Create spatial index
                        OGRLayer.GetExtent(extent, 0);
                        string sidxSQL = string.Format("CREATE SPATIAL INDEX sidx_{0}_ogr_geometry ON [{0}](ogr_geometry) WITH (BOUNDING_BOX = ( {1}, {2}, {3}, {4} ), SORT_IN_TEMPDB = ON );", layerName, ll[0], ll[1], ur[0], ur[1]);
                        using (SqlCommand sidxCmd = new SqlCommand(sidxSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating spatial index sidx_{0}_ogr_geometry on table {0}...", layerName));
                            sidxCmd.CommandTimeout = 0;
                            sidxCmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        log(TraceLevel.Error, e.Message);
                        Environment.Exit(1);
                    }
                }
            }
        }
        public void TestUTCtoJulian()
        {
            //Jan 1st 2010 5:30:30.1234 AM
            DateTime date = new DateTime(2010, 01, 01, 05, 30, 30, 1234);

            //2455197.729515 (only accurate to 1 millisecond)
            double testJD = CoordinateTransformation.UTCtoJulian(date);

            Assert.AreEqual(2455197.729515, testJD);
        }
Example #18
0
        /// <summary>
        /// Creates and initializes an instance of ReprojectionService.
        /// </summary>
        /// <param name="sourceMapService">The inner map service that delivers the map images to be re-projected.</param>
        /// <param name="crs">The CRS to target by this instance.</param>
        /// <param name="reprojector">The re-projector to be used. Uses the default image re-projector if not explicitly set.</param>
        /// <param name="reprojectionServiceOptions">Additional options to be used by this map service.</param>
        public ReprojectionService(MapService sourceMapService, string crs, ImageReprojector reprojector = null, ReprojectionServiceOptions reprojectionServiceOptions = null)
        {
            // store parameters
            SourceMapService = sourceMapService;
            try { TargetToSourceTransformation = CoordinateTransformation.Get(Crs = crs, sourceMapService.Crs); }
            catch { throw new ArgumentException("Failed to setup coordinate transformation for source \"" + sourceMapService.Crs + "\" and target \"" + crs + "\""); }

            Reprojector = reprojector ?? new ImageReprojector();
            ReprojectionServiceOptions = reprojectionServiceOptions ?? new ReprojectionServiceOptions();
        }
Example #19
0
        public static double GetSunEclipticLatitude(double julianDate)
        {
            var julianMillennias = Tools.GetMillenniasCount(julianDate);// (julianDate - 2451545) / 365250;

            var sunLatitudeBase       = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLatitudeBaseArray(), julianMillennias);
            var sunLatitudeFirstGroup = GetCalculatedValue(PositionByOrbitalElementsArray.GetSunLatitudeFirstArray(), julianMillennias);

            double value = (sunLatitudeBase + sunLatitudeFirstGroup * julianMillennias) / 100000000;

            return(CoordinateTransformation.MapToMinus90To90Range(CoordinateTransformation.SetRadiansToDegrees(value)));
        }
Example #20
0
        public double[] convertSirgas200UtmZone24ToWgs84(double x, double y)
        {
            SpatialReference reference    = GetSirgas2000CurrentUTMReferenceInCentimeters();
            SpatialReference newReference = getWgs84Reference();

            CoordinateTransformation ct = new CoordinateTransformation(reference, newReference);

            double[] point = new double[] { x, y };
            ct.TransformPoint(point);
            return(point);
        }
Example #21
0
        static void CreateIndexes(DataSource OGRDataSource, string MSSQLConnectionString)
        {
            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");
            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
            {
                Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer);
                string layerName = OGRLayer.GetName();

                // Get extent in EPSG:900913
                Envelope extent = new Envelope();
                OGRLayer.GetExtent(extent,0);
                double[] ll = new double[] { extent.MinX, extent.MinY };
                double[] ur = new double[] { extent.MaxX, extent.MaxY };
                transform.TransformPoint(ll);
                transform.TransformPoint(ur);

                using (SqlConnection con = new SqlConnection(MSSQLConnectionString))
                {
                    con.Open();
                    try
                    {
                        // Create primary key/clustered index
                        string pkSQL = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED([id] ASC)  WITH (SORT_IN_TEMPDB = ON);", layerName);
                        using (SqlCommand pkCmd = new SqlCommand(pkSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating clustured index pk_{0} on table {0}...", layerName));
                            pkCmd.CommandTimeout = 0;
                            pkCmd.ExecuteNonQuery();
                        }

                        // Create spatial index
                        OGRLayer.GetExtent(extent, 0);
                        string sidxSQL = string.Format("CREATE SPATIAL INDEX sidx_{0}_ogr_geometry ON [{0}](ogr_geometry) WITH (BOUNDING_BOX = ( {1}, {2}, {3}, {4} ), SORT_IN_TEMPDB = ON );", layerName, ll[0], ll[1], ur[0], ur[1]);
                        using (SqlCommand sidxCmd = new SqlCommand(sidxSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating spatial index sidx_{0}_ogr_geometry on table {0}...", layerName));
                            sidxCmd.CommandTimeout = 0;
                            sidxCmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        log(TraceLevel.Error, e.Message);
                        Environment.Exit(1);
                    }
                }
            }
        }
Example #22
0
        public static double ApparentEclipticLongitude(double julianDate, bool highPrecision)
        {
            var longitude = ConvertLongitudeToFK5(julianDate, highPrecision)
                            + CoordinateTransformation.SetDMSToDegrees(0, 0, Nutation.NutationInLongitude(julianDate));

            var radius = Earth.GetSunRadiusVector(julianDate);

            return((highPrecision)
                ? longitude - (0.005775518 * radius * CoordinateTransformation.SetDMSToDegrees(0, 0, GetVariationEclipticLongitude(julianDate)))
                : longitude - CoordinateTransformation.SetDMSToDegrees(0, 0, 20.4898 / radius));
        }
Example #23
0
    protected override void Start()
    {
        base.Start();

        SelectBox.anchoredPosition = new Vector2(1530f, 10f);                                                                                             //預設選擇框位置

        Vector2 rectOffset = baseRect.sizeDelta;                                                                                                          //取得目標尺寸(以便計算偏差值)

        screenPointToAncPos = new CoordinateTransformation(new ScreenPointToAnchoredPosition(cam, canvas, baseRect, rectOffset, OffsetDirection.Bottom)); //座標轉換實例

        TotalOffset = itermOffset + itermSideSize;                                                                                                        //計算每個物件相對於前一個物件的座標偏差值
    }
Example #24
0
        public static ICoordinate TransformPoint(this CoordinateTransformation coordinateTransformation, ICoordinate coord)
        {
            ICoordinate destCoord = null;

            if (coordinateTransformation != null && coord != null)
            {
                var array = coord.ToDoubleArray(coord.Dimension);
                coordinateTransformation.TransformPoint(array);
                destCoord = array.ToCoordinate();
            }
            return(destCoord);
        }
Example #25
0
        // 将给定Tif转换为Web Mercator投影
        public void TransformTiff(Dataset ds, double[] VerticeX, double[] VerticeY, string FilePath, ResampleAlg eResampleMethod)
        {
            //获取Web墨卡托坐标系
            SpatialReference Mercator = new SpatialReference("");

            Mercator.ImportFromEPSG(3857);             // Web Mercator
            Mercator.SetMercator(0d, 0d, 1d, 0d, 0d);
            string MercatorWkt;

            Mercator.ExportToWkt(out MercatorWkt);
            //原栅格坐标信息
            SpatialReference Raster_spf = new SpatialReference(ds.GetProjectionRef());
            //影像四个顶点投影转换
            CoordinateTransformation coordinateTrans = Osr.CreateCoordinateTransformation(Raster_spf, Mercator);

            coordinateTrans.TransformPoints(4, VerticeX, VerticeY, null);            //VerticeX和VerticeY存储的是影像四个顶点坐标
            coordinateTrans.Dispose();
            //计算重投影后栅格顶点坐标
            double dbMinx = 0;
            double dbMaxx = 0;
            double dbMiny = 0;
            double dbMaxy = 0;

            dbMinx = Math.Min(Math.Min(Math.Min(VerticeX[0], VerticeX[1]), VerticeX[2]), VerticeX[3]);
            dbMaxx = Math.Max(Math.Max(Math.Max(VerticeX[0], VerticeX[1]), VerticeX[2]), VerticeX[3]);
            dbMiny = Math.Min(Math.Min(Math.Min(VerticeY[0], VerticeY[1]), VerticeY[2]), VerticeY[3]);
            dbMaxy = Math.Max(Math.Max(Math.Max(VerticeY[0], VerticeY[1]), VerticeY[2]), VerticeY[3]);
            //计算新的仿射变换参数
            double[] newTransform = new double[6];
            newTransform[0] = dbMinx;         //左上角点x坐标
            newTransform[3] = dbMaxy;         //左上角点y坐标
            newTransform[1] = 100;            //像素宽度
            newTransform[5] = -100;           //像素高度
            //计算大小
            int width  = (int)Math.Ceiling(Math.Abs(dbMaxx - dbMinx) / 100.0);
            int height = (int)Math.Ceiling(Math.Abs(dbMaxy - dbMiny) / 100.0);

            //创建新的栅格影像
            OSGeo.GDAL.Driver pGDalDriver = Gdal.GetDriverByName("GTiff");
            Dataset           poDataset   = pGDalDriver.Create(FilePath, width, height, 1, DataType.GDT_Float32, null);

            poDataset.SetGeoTransform(newTransform);
            poDataset.SetProjection(MercatorWkt);
            //重投影
            Gdal.ReprojectImage(ds, poDataset, ds.GetProjectionRef(), MercatorWkt, eResampleMethod, 0, 0, new Gdal.GDALProgressFuncDelegate(ProgressFunc), null, null);
            //设置NoData值
            Band band = poDataset.GetRasterBand(1);

            band.SetNoDataValue(-10000000);
            poDataset.FlushCache();
            poDataset.Dispose();
        }
Example #26
0
        private string generatePolygon(string ring)
        {
            double[][] enPairs = ring.Split(' ')
                                 .Select(line => new double[] { Convert.ToDouble(line.Split(',')[0]), Convert.ToDouble(line.Split(',')[1]) })
                                 .ToArray();
            double[][] transformedENPairs = CoordinateTransformation.TransformEastingNorthing(enPairs);
            double[][] longLatPairs       = CoordinateConversion.ConvertToLongitudeLatitude(transformedENPairs);

            string[] longLat = longLatPairs
                               .Select(longLatPair => string.Join(" ", string.Format("{0:0.00000000000}", longLatPair[0]), string.Format("{0:0.00000000000}", longLatPair[1])))
                               .ToArray();
            string polygon = string.Join(",", longLat);

            return($"({polygon})");
        }
    void SpawnNewImagePOI(float dec, float ra)
    {
        //get the world coordinates
        float   radius   = ImageRadius + UnityEngine.Random.Range(-ImageRadiusVariance, ImageRadius);
        Vector3 spawnPos = CoordinateTransformation.ToWorldCoordiantes(dec, ra, radius);

        //spawn new POI object
        GameObject newPOI = Instantiate(ImagePOI, spawnPos, Quaternion.identity);

        newPOI.transform.SetParent(UniverseTransform);
        newPOI.transform.localPosition = spawnPos;

        //assign index
        //int index = numberOfImages + 1;
        newPOI.GetComponent <ImageDot>().SetIndex(numberOfImages);
        numberOfImages += 1;
    }
Example #28
0
        private static Point GetWgs84Point(Point point)
        {
            if (point.SRID == 4326)
            {
                return(point);
            }
            var cs = CoordinateSystemExtend.Get(point.SRID);

            if (cs is GeographicCoordinateSystem)
            {
                return(CoordinateTransformation.TransformPoint(point, GeographicCoordinateSystem.WGS84, false));
            }
            else
            {
                return(CoordinateTransformation.TransformPoint(point, GeographicCoordinateSystem.WGS84, false));
            }
        }
        public static double[] TransformWGS83ToOSGB(double latitude, double longitude)
        {
            SpatialReference src = new SpatialReference("");

            src.ImportFromEPSG(4326);
            SpatialReference dst = new SpatialReference("");

            dst.ImportFromEPSG(27700);
            CoordinateTransformation ct = new CoordinateTransformation(src, dst);

            double[] point = new double[3];
            point[0] = longitude;
            point[1] = latitude;
            point[2] = 0;
            ct.TransformPoint(point);
            return(point);
        }
        public override void PreExecute()
        {
            base.PreExecute();

            //set input spatail reference
            string           srInput = ComponentMetaData.CustomPropertyCollection["Input Spatial Reference"].Value.ToString();
            SpatialReference inSr    = new SpatialReference("");

            inSr.SetFromUserInput(srInput);

            //Set output spatial reference
            string           srOutput = ComponentMetaData.CustomPropertyCollection["Output Spatial Reference"].Value.ToString();
            SpatialReference outSr    = new SpatialReference("");

            outSr.SetFromUserInput(srOutput);

            //cache coordinate transformation
            this.ct = new CoordinateTransformation(inSr, outSr);
        }
Example #31
0
        public static GeographicPoint ConvertUtmPointToGeographic(UtmPoint utmPoint, Dataset ds)
        {
            SpatialReference monUtm = new SpatialReference(ds.GetProjectionRef());

            var geoPoint = new GeographicPoint();

            SpatialReference monGeo = new SpatialReference(ds.GetProjectionRef());

            monGeo.ImportFromEPSG(4326);
            double[] res = new double[3];

            CoordinateTransformation coordTrans = new CoordinateTransformation(monUtm, monGeo);

            coordTrans.TransformPoint(res, utmPoint.Easting, utmPoint.Northing, 0);
            geoPoint.Longitude = res[0];
            geoPoint.Latitude  = res[1];

            return(geoPoint);
        }
Example #32
0
        static IEnumerable<DataTable> ReadData(DataSource OGRDataSource, DataSet OSMDataSet, int SQLBatchSize)
        {
            int featureCount = 0;

            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");
            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            // Use interleaved reading - http://www.gdal.org/drv_osm.html
            bool bHasLayersNonEmpty = false;
            do
            {
                bHasLayersNonEmpty = false;
                for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
                {
                    Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer);
                    log(TraceLevel.Verbose, string.Format("Processing {0}...", OGRLayer.GetName()));
                    FeatureDefn OGRFeatDef = OGRLayer.GetLayerDefn();
                    DataTable buffer = OSMDataSet.Tables[OGRLayer.GetName()];

                    Feature feat;
                    while ((feat = OGRLayer.GetNextFeature()) != null)
                    {
                        bHasLayersNonEmpty = true;

                        // Commit buffer larger than batch size
                        if (buffer.Rows.Count >= SQLBatchSize)
                        {
                            yield return buffer.Copy();
                            buffer.Rows.Clear();
                        }

                        // Fill buffer row
                        DataRow row = buffer.NewRow();
                        for (int iField = 0; iField < OGRFeatDef.GetFieldCount(); iField++)
                        {
                            if (feat.IsFieldSet(iField))
                            {
                                // Add one to skip id IDENTITY column
                                row[iField + 1] = feat.GetFieldAsString(iField);
                            }
                        }

                        // Get OGR geometry object
                        Geometry geom = feat.GetGeometryRef();

                        // Project from EPSG:4326 to EPSG:900913
                        geom.Transform(transform);

                        // Serialize to WKB
                        byte[] geomBuffer = new byte[geom.WkbSize()];
                        geom.ExportToWkb(geomBuffer);

                        // Set ogr_geometry buffer column from WKB
                        try
                        {
                            SqlGeometry sqlGeom = SqlGeometry.STGeomFromWKB(new SqlBytes(geomBuffer), 900913).MakeValid();
                            row["ogr_geometry"] = sqlGeom;
                            row["ogr_geometry_area"] = sqlGeom.STArea().Value;

                            // Add row to buffer
                            buffer.Rows.Add(row);
                        }
                        catch (Exception e)
                        {
                            log(TraceLevel.Warning, string.Format("Cannot process osm_id: {0} ({1})", feat.GetFID(), e.Message));
                        }

                        // Update progress
                        featureCount++;
                    }

                    // Commit buffer before moving on to another layer
                    if (buffer.Rows.Count != 0)
                    {
                        yield return buffer.Copy();
                        buffer.Rows.Clear();
                    }
                }
            } while (bHasLayersNonEmpty);
        }
Example #33
0
        // gets transform between raster's native projection and the map projection
        private void GetTransform(ProjectionInfo mapProjection)
        {
            if (mapProjection == null || _projectionWkt == "")
            {
                _transform = null;
                return;
            }

            // get our two projections
            var srcCoord = ProjectionInfo.FromEsriString(_projectionWkt);
            ProjectionInfo tgtCoord = mapProjection;

            // raster and map are in same projection, no need to transform
            if (srcCoord.Matches(tgtCoord))
            {
                _transform = null;
                return;
            }

            // create transform
            _transform = new CoordinateTransformation {Source = srcCoord, Target = tgtCoord};
        }