/// <summary> /// 将地理坐标转成投影坐标 /// </summary> /// <param name="llGeomerty"></param> /// <param name="geographySpatialRef"></param> /// <param name="projectionSpatialRef"></param> /// <returns></returns> public static Geometry GeographyToProjection(Geometry llGeomerty, SpatialReference geographySpatialRef, SpatialReference projectionSpatialRef) { llGeomerty.AssignSpatialReference(geographySpatialRef); llGeomerty.ExportToWkt(out string wkt); var coordinateTransformation = Osr.CreateCoordinateTransformation(geographySpatialRef, projectionSpatialRef); var xyGoemetry = llGeomerty.Clone(); xyGoemetry.Transform(coordinateTransformation); return(xyGoemetry); }
// 将给定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(); }
/// <summary> /// 将投影坐标转成地理坐标 /// </summary> /// <param name="xyGeometries">投影坐标系图斑</param> /// <param name="projectionSpatialRef">投影坐标系</param> /// <returns></returns> public static Geometry[] ProjectionToGeography(this Geometry[] xyGeometries, SpatialReference projectionSpatialRef) { //将投影坐标转成地理坐标 var geographySpatialRef = projectionSpatialRef.CloneGeogCS(); //获取投影坐标对应的地理坐标系 var coordinateTransformation = Osr.CreateCoordinateTransformation(projectionSpatialRef, geographySpatialRef); var llGeometries = new List <Geometry>(); //转换坐标系后的图斑 for (int i = 0; i < xyGeometries.Length; i++) { var llGoemetry = xyGeometries[i].Clone(); llGoemetry.Transform(coordinateTransformation); //转换坐标系 llGeometries.Add(llGoemetry); } return(llGeometries.ToArray()); }
private static void TransformWKT(object srcProj, object dstProj, EPSGType srcType, EPSGType dstType, ref string wkt) { try { GdalConfiguration.ConfigureOgr(); SpatialReference src = new SpatialReference(""); switch (srcType) { case EPSGType.OGC_WKT: string srcProj_str = srcProj.ToString(); src.ImportFromWkt(ref srcProj_str); break; case EPSGType.PROJ4: src.ImportFromProj4(srcProj.ToString()); break; case EPSGType.EPSG_NUM: src.ImportFromEPSG((int)srcProj); break; } SpatialReference dst = new SpatialReference(""); switch (dstType) { case EPSGType.OGC_WKT: string dstProj_str = dstProj.ToString(); dst.ImportFromWkt(ref dstProj_str); break; case EPSGType.PROJ4: dst.ImportFromProj4(dstProj.ToString()); break; case EPSGType.EPSG_NUM: dst.ImportFromEPSG((int)dstProj); break; } CoordinateTransformation coordinate = Osr.CreateCoordinateTransformation(src, dst); string wktType = wkt.Split('(')[0]; wkt = wkt.Split('(')[2].Split(')')[0]; string[] splitWKT = wkt.Split(','); double[] xPoints = new double[splitWKT.Length]; double[] yPoints = new double[splitWKT.Length]; for (int i = 0; i < splitWKT.Length; i++) { double.TryParse(splitWKT[i].Split(' ')[0], out xPoints[i]); double.TryParse(splitWKT[i].Split(' ')[1], out yPoints[i]); } coordinate.TransformPoints(splitWKT.Length, xPoints, yPoints, null); wkt = wktType + "(("; for (int i = 0; i < xPoints.Length; i++) { wkt += xPoints[i] + " " + yPoints[i] + ","; } wkt = wkt.Substring(0, wkt.Length - 1); wkt += "))"; } catch (Exception e) { Debug.WriteLine(e.ToString()); } }
public static ReturnValue ExportFeatureLayerToMySQL(string pConnStr, IPointLayer pLayer, string pSchemaName, bool pTruncateTable, int pSrcEPSG = 32640, int pTgtEPSG = 4326) { var mRV = new ReturnValue(); var mSrcSRS = new SpatialReference(null); mSrcSRS.ImportFromEPSG(pSrcEPSG); var mTgtSRS = new SpatialReference(null); mTgtSRS.ImportFromEPSG(pTgtEPSG); var mTransformation = Osr.CreateCoordinateTransformation(mSrcSRS, mTgtSRS); MySQLLib.Create(pConnStr); // Check if table exists if (!MySQLLib.TableExists("geoobjects", pSchemaName)) { var mSql = "delimiter $$ CREATE TABLE `geoobjects` ( `id` int(11) NOT NULL AUTO_INCREMENT, `geom` geometry NOT NULL, `left` float(10,6) NOT NULL, `bottom` float(10,6) NOT NULL, `right` float(10,6) NOT NULL, `top` float(10,6) NOT NULL, `namepart` varchar(250) DEFAULT NULL, `numberpart` int(11) DEFAULT NULL, `title` varchar(250) DEFAULT NULL, `description` text, `gtype` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`), SPATIAL KEY `idxSpatial` (`geom`), FULLTEXT KEY `idxFullText` (`title`,`description`)) ENGINE=MyISAM AUTO_INCREMENT=2585 DEFAULT CHARSET=utf8$$"; SLib.ExecuteNonQuery(mSql); } if (pTruncateTable) { var mSql = "DELETE FROM geoobjects"; MySQLLib.ExecuteNonQuery(mSql); } foreach (IFeature mFeature in pLayer.DataSet.Features) { var mGeom = OSGeo.OGR.Geometry.CreateFromWkb(mFeature.ToBinary()); if (pSrcEPSG != pTgtEPSG) { mGeom.Transform(mTransformation); } Envelope mEnvelope = new Envelope(); mGeom.GetEnvelope(mEnvelope); string mWkt; mGeom.ExportToWkt(out mWkt); var mSql = String.Format("INSERT INTO `admadr`.`geoobjects` (`geom`, `left`, `bottom`, `right`, `top`, `namepart`, `numberpart`, `title`, `description`, `gtype`) VALUES (GeomFromText('{0}'),{1},{2},{3},{4},'{5}',{6}, '{7}', '{8}', '{9}')", mWkt, mEnvelope.MinX, mEnvelope.MinY, mEnvelope.MaxX, mEnvelope.MaxY, Utilities.NormalizeString(mFeature.DataRow["ROADNAME_EN"].ToString()), mFeature.DataRow["ADDRESSUNITNR"], // Function to convert to number? mFeature.DataRow["ADDRESSUNITNR"] + ", " + Utilities.NormalizeString(mFeature.DataRow["ROADNAME_EN"].ToString()), Utilities.GetVariants(mFeature.DataRow["ROADNAME_EN"].ToString()), "address" ); MySQLLib.ExecuteNonQuery(mSql); } MySQLLib.Dbx.Close(); MySQLLib.Dbx.Dispose(); return(mRV); }
/// <summary> /// 转换坐标系 /// </summary> /// <param name="sourceShpPath"></param> /// <param name="resultShpPath"></param> /// <param name="resultSpaitalRef"></param> /// <param name="isPrjToGeo"></param> public static void ConvertSpatialRef(string sourceShpPath, string resultShpPath, SpatialReference resultSpaitalRef = null, bool isPrjToGeo = true) { //打开源shp文件 var dataSource = Ogr.Open(sourceShpPath, 0); if (dataSource == null) { throw new Exception("GDAL打开数据源失败,请确定GDAL已正常初始化、数据源存在且数据可读!"); } var sourceLayer = dataSource.GetLayerByIndex(0); var sourceSpatialRef = sourceLayer.GetSpatialRef(); if (sourceSpatialRef == null) { throw new Exception("坐标系为空,请先正确设置坐标系!"); } if (isPrjToGeo) { if (resultSpaitalRef == null) { resultSpaitalRef = sourceSpatialRef.CloneGeogCS(); } if (sourceSpatialRef.IsProjected() == 0) { throw new Exception("源shp文件坐标系不是投影坐标系!"); } } else { if (resultSpaitalRef == null) { resultSpaitalRef = TryGetProjectionSpatialRef(sourceLayer); } if (sourceSpatialRef.IsGeographic() == 0) { throw new Exception("源shp文件坐标系不是地理坐标系!"); } } //获取坐标转换规则 var coordinateTransformation = Osr.CreateCoordinateTransformation(sourceSpatialRef, resultSpaitalRef); //创建结果shp文件 var sourceFeatureDefn = sourceLayer.GetLayerDefn(); var resultDataSource = CreateShapefileSource(resultShpPath); var resultLayer = resultDataSource.CreateLayer(Path.GetFileNameWithoutExtension(resultShpPath), resultSpaitalRef, wkbGeometryType.wkbPolygon, null); for (int i = 0; i < sourceFeatureDefn.GetFieldCount(); i++) { var sourceFieldDefn = sourceFeatureDefn.GetFieldDefn(i); resultLayer.CreateField(sourceFieldDefn, 1); } //投影转地理坐标系并保存 var sourceFeatures = GetFeatures(sourceLayer); var resultFeatureDefn = resultLayer.GetLayerDefn(); foreach (var sourceFeature in sourceFeatures) { var sourceGeometry = sourceFeature.GetGeometryRef(); var resultGeometry = sourceGeometry.Clone(); resultGeometry.Transform(coordinateTransformation); //转换坐标系 Feature resultFeature = new Feature(resultFeatureDefn); resultFeature.SetFrom(sourceFeature, 1); resultFeature.SetGeometry(resultGeometry); resultLayer.CreateFeature(resultFeature); } resultLayer.SyncToDisk(); }