Beispiel #1
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 });
        }
Beispiel #2
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);
        }
Beispiel #3
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);
     }
 }
Beispiel #4
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);
                    }
                }
            }
        }
Beispiel #5
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);
                    }
                }
            }
        }
Beispiel #6
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]));
        }
Beispiel #7
0
        public double getElevation(double x, double y, double z)
        {
            double[] geo       = threeD2geo(x, y, z); //B L
            double[] lonlat2xy = { geo[1], geo[0] };  //L B:lon lat

            transGeo2Pro.TransformPoint(lonlat2xy);

            double[] xy = DEMpro2raster(lonlat2xy[0], lonlat2xy[1]);
            x = xy[0];
            y = xy[1];
            switch (DEMInter)
            {
            case Interpolate.NEAREST:
            {
                int[] gray = new int[1];
                _DEMband.ReadRaster((int)Math.Round(x), (int)Math.Round(y), 1, 1,
                                    gray, 1, 1, 0, 0);

                return(gray[0]);
            }

            case Interpolate.LINEAR:
            {
                int[] grays = new int[4];
                _DEMband.ReadRaster((int)x, (int)y, 2, 2,
                                    grays, 2, 2, 0, 0);

                int g11, g12, g21, g22;
                g11 = grays[0];
                g12 = grays[1];
                g21 = grays[2];
                g22 = grays[3];

                double yInv = y - (int)y;
                double xInv = x - (int)x;

                double g1 = (1 - yInv) * g11 + yInv * g21;
                double g2 = (1 - yInv) * g12 + yInv * g22;

                return((1 - xInv) * g1 + xInv * g2);
            }

            default:
                break;
            }
            return(0);
        }
Beispiel #8
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();
        }
Beispiel #9
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);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        public static GeographicPolygon ConvertUtmPolygonToGeographic(UtmPolygon utmPolygon, Dataset ds)
        {
            SpatialReference monUtm = new SpatialReference(ds.GetProjectionRef());

            var geoPolygon = new GeographicPolygon();

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

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

            CoordinateTransformation coordTrans = new CoordinateTransformation(monUtm, monGeo);

            coordTrans.TransformPoint(res, utmPolygon.UpperLeft.Easting, utmPolygon.UpperLeft.Northing, 0);
            geoPolygon.UpperLeft.Longitude = res[0];
            geoPolygon.UpperLeft.Latitude  = res[1];

            coordTrans.TransformPoint(res, utmPolygon.LowerRight.Easting, utmPolygon.LowerRight.Northing, 0);
            geoPolygon.LowerRight.Longitude = res[0];
            geoPolygon.LowerRight.Latitude  = res[1];

            return(geoPolygon);
        }
        private List <double[]> readImageCoordinatesBoundsInLonLat(OSGeo.GDAL.Dataset imageDataset)
        {
            var band = imageDataset.GetRasterBand(1);

            if (band == null)
            {
                return(null);
            }

            var width  = band.XSize;
            var height = band.YSize;

            double[] geoTransformerData = new double[6];
            imageDataset.GetGeoTransform(geoTransformerData);


            SpatialReference         currentReference = new SpatialReference(imageDataset.GetProjectionRef());
            SpatialReference         newReference     = GdalUtilities.getWgs84Reference();
            CoordinateTransformation ct = new CoordinateTransformation(currentReference, newReference);

            double[] northWestPoint = new double[2] {
                geoTransformerData[0], geoTransformerData[3]
            };
            ct.TransformPoint(northWestPoint);

            double[] southEastPoint = new double[2] {
                geoTransformerData[0] + geoTransformerData[1] * width,
                geoTransformerData[3] + geoTransformerData[5] * height
            };
            ct.TransformPoint(southEastPoint);


            return(new List <double[]> {
                northWestPoint, southEastPoint
            });
        }
Beispiel #13
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);
        }
Beispiel #15
0
 public Point Change(Point srcPoint)
 {
     try
     {
         SpatialReference src     = new SpatialReference("");
         string           srcproj = ZoonSrcProj;
         src.ImportFromWkt(ref srcproj);
         SpatialReference dest     = new SpatialReference("");
         string           destproj = ZoonDestProj;
         dest.ImportFromWkt(ref destproj);
         CoordinateTransformation ct = new CoordinateTransformation(src, dest);
         double[] p = new double[3];
         p[0] = srcPoint.X;
         p[1] = srcPoint.Y;
         p[2] = 0;
         ct.TransformPoint(p);
         Point destPoint = new Point(p[0], p[1]);
         return(destPoint);
     }
     catch
     {
         return(srcPoint);
     }
 }
Beispiel #16
0
        public void TransformPointIsOk()
        {
            var x = 826158.063;
            var y = 2405844.125;

            var sourceWkt =
                "PROJCS[\"OSGB_1936_British_National_Grid\",GEOGCS[\"GCS_OSGB 1936\",DATUM[\"D_OSGB_1936\",SPHEROID[\"Airy_1830\",6377563.396,299.3249646]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],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],UNIT[\"Meter\",1]]";
            var targetWkt =
                "PROJCS[\"ETRS89_LAEA_Europe\",GEOGCS[\"GCS_ETRS_1989\",DATUM[\"D_ETRS_1989\",SPHEROID[\"GRS_1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],PARAMETER[\"latitude_of_origin\",52],PARAMETER[\"central_meridian\",10],PARAMETER[\"false_easting\",4321000],PARAMETER[\"false_northing\",3210000],UNIT[\"Meter\",1]]";

            Proj.Configure();

            var sourceSr = new SpatialReference(string.Empty);

            sourceSr.ImportFromWkt(ref sourceWkt);
            sourceSr.SetAxisMappingStrategy(AxisMappingStrategy.OAMS_TRADITIONAL_GIS_ORDER);

            var targetSr = new SpatialReference(string.Empty);

            targetSr.ImportFromWkt(ref targetWkt);
            targetSr.SetAxisMappingStrategy(AxisMappingStrategy.OAMS_TRADITIONAL_GIS_ORDER);

            var transformation = new CoordinateTransformation(sourceSr, targetSr);

            var projected = new double[3];

            transformation.TransformPoint(projected, x, y, 0.0);
            var px = projected[0];
            var py = projected[1];

            var ex = 4316331.55;
            var ey = 5331101.98;

            Assert.Equal(ex, px, 0);
            Assert.Equal(ey, py, 0);
        }
Beispiel #17
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            string folder = textBoxFolder.Text;

            if (folder == null || folder.Trim().Equals(""))
            {
                MessageBox.Show("请选择数据路径");
                return;
            }

            toolStripStatusLabelState.Text      = "正在处理";
            toolStripProgressBarPercent.Visible = true;
            toolStripStatusLabelPercent.Visible = true;
            statusStrip1.Update();

            // 获取元数据
            string[] tifs   = Directory.GetFiles(folder, "*.tif");
            int      tifNum = tifs.Length;

            string[]   fields    = new string[tifNum];
            Dataset[]  datasets  = new Dataset[tifNum];
            DataType[] dataTypes = new DataType[tifNum];
            double[]   nodatas   = new double[tifNum];
            for (int i = 0; i < tifNum; i++)
            {
                // field
                string[] paths    = tifs[i].Split('\\');
                string   filename = paths[paths.Length - 1];
                fields[i] = filename.Split('_')[0];
                // dataset
                datasets[i]  = Gdal.Open(tifs[i], Access.GA_ReadOnly);
                dataTypes[i] = datasets[i].GetRasterBand(1).DataType;
                // nodata
                int hasVal;
                datasets[i].GetRasterBand(1).GetNoDataValue(out nodatas[i], out hasVal);
                if (hasVal != 1)
                {
                    nodatas[i] = double.NaN;
                }
            }
            double[] geoTransform = new double[6];
            datasets[0].GetGeoTransform(geoTransform);
            string                   proj  = datasets[0].GetProjection();
            SpatialReference         sr    = new SpatialReference(proj);
            CoordinateTransformation trans = new CoordinateTransformation(sr, sr.CloneGeogCS());
            int    isGeographic            = sr.IsGeographic();
            double topLeftX      = geoTransform[0];
            double xRes          = geoTransform[1];
            double topLeftY      = geoTransform[3];
            double yRes          = geoTransform[5];
            int    xSize         = datasets[0].RasterXSize;
            int    ySize         = datasets[0].RasterYSize;
            int    leftYSize     = ySize;
            int    yOffset       = 0;
            int    blockSize     = 100;
            int    progressValue = 0;

            // 写入csv
            using (StreamWriter sw = new StreamWriter(folder + "\\output.csv"))
            {
                sw.WriteLine(getHeader(fields));
                sw.Flush();
                while (leftYSize > 0) // 按行分块
                {
                    int readYSize = (leftYSize > blockSize) ? blockSize : leftYSize;
                    leftYSize = leftYSize - readYSize;
                    double[][] data = new double[tifNum][];

                    // 读入数据
                    for (int i = 0; i < tifNum; i++)
                    {
                        data[i] = new double[xSize * readYSize];
                        datasets[i].GetRasterBand(1).ReadRaster(0, yOffset, xSize, readYSize, data[i], xSize, readYSize, 0, 0);
                    }
                    for (int row = 0; row < readYSize; row++) // 按行
                    {
                        int rowNo   = yOffset + row;
                        int current = rowNo * 100 / ySize;
                        if (current > progressValue) // 改变进度条状态
                        {
                            toolStripProgressBarPercent.Value = current;
                            toolStripStatusLabelPercent.Text  = string.Format("{0}%", current);
                            statusStrip1.Update();
                            progressValue = current;
                        }
                        for (int col = 0; col < xSize; col++) // 按列
                        {
                            StringBuilder builder = new StringBuilder();
                            double[]      latlon  = new double[2];
                            latlon[0] = topLeftX + col * xRes;
                            latlon[1] = topLeftY + rowNo * yRes;
                            if (isGeographic == 0) // 投影转经纬度
                            {
                                trans.TransformPoint(latlon);
                            }
                            builder.Append(latlon[0].ToString("f6")).Append(",").Append(latlon[1].ToString("f6"));
                            bool isNoData = false;
                            for (int i = 0; i < tifNum; i++) // 按文件
                            {
                                builder.Append(",");
                                double v = data[i][row * xSize + col];
                                if (v == nodatas[i])
                                {
                                    isNoData = true;
                                    break;
                                }
                                if (dataTypes[i] == DataType.GDT_Float32 || dataTypes[i] == DataType.GDT_Float64)
                                {
                                    builder.Append(v.ToString("f6"));
                                }
                                else
                                {
                                    builder.Append(v.ToString("f0"));
                                }
                            }
                            if (!isNoData) // 非空值
                            {
                                sw.WriteLine(builder.ToString());
                            }
                        }
                        sw.Flush();
                    }

                    yOffset = yOffset + readYSize;
                }
                sw.Close();
            }

            // 释放资源
            for (int i = 0; i < tifNum; i++)
            {
                datasets[i].Dispose();
            }
            toolStripStatusLabelState.Text      = "就绪";
            toolStripProgressBarPercent.Visible = false;
            toolStripStatusLabelPercent.Visible = false;
            statusStrip1.Update();
            MessageBox.Show("处理完成");
        }
Beispiel #18
0
        public static double Distance(Point point1, Point point2)
        {
            //一个有坐标系一个没有坐标系
            //if (point1.CoordinateSystem != null && point2.CoordinateSystem == null)
            //{
            //    point2 = point2.Clone() as Point;
            //    point2.SetCoordinateSystem(point1.CoordinateSystem, false);
            //}
            //else if (point1.CoordinateSystem == null && point2.CoordinateSystem != null)
            //{
            //    point1 = point1.Clone() as Point;
            //    point1.SetCoordinateSystem(point2.CoordinateSystem, false);
            //}
            ////两个坐标系不同
            //else if (point1.CoordinateSystem != point2.CoordinateSystem)
            //{
            //    if(point1.CoordinateSystem is ProjectedCoordinateSystem)
            //    point2 = CoordinateSystems.Transformations.CoordinateTransformation.TransformPoint(point2, point1.CoordinateSystem, false);
            //}
            //地理坐标系
            //if (point1.CoordinateSystem is GeographicCoordinateSystem)
            //{

            //如果两个都没有坐标系,直接求欧氏距离
            if (point1.SRID == 0 && point2.SRID == 0)
            {
                double x = point1.X - point2.X;
                double y = point1.Y - point2.Y;
                return(Math.Sqrt(x * x + y * y));
            }
            ////一个有坐标系一个没有坐标系
            //if (point1.CoordinateSystem != null && point2.CoordinateSystem == null)
            //{
            //    point2 = point2.Clone() as Point;
            //    point2.SetCoordinateSystem(point1.CoordinateSystem, false);
            //}
            //else if (point1.CoordinateSystem == null && point2.CoordinateSystem != null)
            //{
            //    point1 = point1.Clone() as Point;
            //    point1.SetCoordinateSystem(point2.CoordinateSystem, false);
            //}
            //else
            //{
            //    point1 = GetWgs84Point(point1);
            //    point2 = GetWgs84Point(point2);
            //}
            if (!point1.SRID.Equals(point2.SRID))
            {
                throw new Exception("坐标系不一致");
            }
            var cs = CoordinateSystemExtend.Get(point1.SRID);

            if (cs is IGeographicCoordinateSystem)
            {
                return(CalculateGeodeticCurve(
                           (cs as IGeographicCoordinateSystem).HorizontalDatum.Ellipsoid as Ellipsoid,
                           point1, point2).Length);
            }
            else
            {
                point1 = CoordinateTransformation.TransformPoint(point1, 4326);
                point2 = CoordinateTransformation.TransformPoint(point2, 4326);
                return(CalculateGeodeticCurve(Ellipsoid.WGS84, point1, point2).Length);
            }
            //double lat1 = point1.Latitude;
            //double lat2 = point2.Latitude;
            //double lng1 = point1.Longitude;
            //double lng2 = point2.Longitude;

            //var radLat1 = lat1 * Math.PI / 180.0;
            //var radLat2 = lat2 * Math.PI / 180.0;
            //var a = radLat1 - radLat2;
            //var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            //var s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            //s *= CoordinateSystem.WGS84.HorizontalDatum.Ellipsoid.SemiMajorAxis; //6378137;
            ////s = Math.Round(s * 10000) / 10000;

            //return s;
            //}
        }
        private void btnFindCoords_Click(object sender, EventArgs e)
        {
            // Reads in latidue, longitude and UTM zone and calculates UTM coordinates

            // first read in lat, long and UTM zone
            float Lat      = 0;
            float Long     = 0;
            int   UTM_Zone = 0;


            try
            {
                Lat = Convert.ToSingle(txtLat.Text);
            }
            catch
            {
                MessageBox.Show("Invalid latitude.");
                return;
            }

            try
            {
                Long = Convert.ToSingle(txtLong.Text);
            }
            catch
            {
                MessageBox.Show("Invalid longitude.");
                return;
            }

            try
            {
                UTM_Zone = Convert.ToInt16(txtUTMZone.Text);
            }
            catch
            {
                MessageBox.Show("Invalid UTM zone.");
                return;
            }

            // Now convert lat/long to UTM
            Gdal.AllRegister();

            // Create a spatial reference with geographic (lat/long) coordinates

            String           Lat_Long_Proj_Str = "GEOGCS[\"NAD83\", DATUM[\"North_American_Datum_1983\", SPHEROID[\"GRS 1980\", 6378137, 298.257222101, AUTHORITY[\"EPSG\", \"7019\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\", \"6269\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9108\"]], AUTHORITY[\"EPSG\", \"4269\"]]";
            SpatialReference Lat_Long          = new SpatialReference(Lat_Long_Proj_Str);

            SpatialReference UTM_proj = new SpatialReference("");

            UTM_proj.SetProjCS("UTM Proj");
            UTM_proj.SetWellKnownGeogCS("NAD83");

            int North_or_South = cbo_North_or_South.SelectedIndex;

            UTM_proj.SetUTM(UTM_Zone, North_or_South);

            CoordinateTransformation ct = new CoordinateTransformation(Lat_Long, UTM_proj);

            Double[] UTM_Point = new Double[3];
            UTM_Point[0] = Long;
            UTM_Point[1] = Lat;

            ct.TransformPoint(UTM_Point);

            txtUTMX.Text = Math.Round(UTM_Point[0], 1).ToString();
            txtUTMY.Text = Math.Round(UTM_Point[1], 1).ToString();
        }