public static void Main(string[] args) { if (args.Length < 1) { usage(); } int count = 0;; CRSInfoList list = Osr.GetCRSInfoListFromDatabase(args[0], out count); if (args.Length > 1) { int maxcount = int.Parse(args[1]); if (count > maxcount) { count = maxcount; } } for (int i = 0; i < count; i++) { PrintCRSInfo(i, list[i]); } }
/// <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); }
public static void Test1() { Ogr.RegisterAll(); OSGeo.OGR.Driver driver = Ogr.GetDriverByName("ESRI Shapefile"); var ds = driver.Open(@"C:\test\continents.shp", 0); var drv = ds.GetDriver(); var layer = ds.GetLayerByIndex(0); var count = layer.GetFeatureCount(0); var name = ds.GetName(); var sr = layer.GetSpatialRef(); sr.ExportToProj4(out var p4Str); var cgcs2000wkt = "GEOGCS[\"ChinaGeodeticCoordinateSystem2000\",DATUM[\"China_2000\",SPHEROID[\"CGCS2000\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"1024\"]],AUTHORITY[\"EPSG\",\"1043\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4490\"]]"; var srCgcs2000 = new SpatialReference(cgcs2000wkt); srCgcs2000.ExportToProj4(out var cgcs2000p4str); var webMctWkt = "PROJCS[\"WGS84/Pseudo-Mercator\",GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION[\"PROJ4\",\"+proj=merc+a=6378137+b=6378137+lat_ts=0.0+lon_0=0.0+x_0=0.0+y_0=0+k=1.0+units=m+nadgrids=@null+wktext+no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]"; var srWebMct = new SpatialReference(webMctWkt); var projMethods = Osr.GetProjectionMethods(); sr.ExportToProj4(out var o1); srWebMct.ExportToProj4(out var o2); Dictionary <string, int> isProjectedDictionary = new Dictionary <string, int>(); isProjectedDictionary.Add(o1, sr.IsProjected()); isProjectedDictionary.Add(o2, srWebMct.IsProjected()); double[] vs = new double[3]; //transform.TransformPoint(vs, 120, 30, 20); SpatialReference srr = new SpatialReference(""); srr.SetWellKnownGeogCS("WGS84"); //srr.SetProjCS("UTM 17 (WGS84) in northern hemisphere."); srr.SetProjCS(""); //srr.SetUTM(17, 1); srr.ExportToProj4(out var srrstr); var defn = layer.GetLayerDefn(); var defnCount = defn.GetFieldCount(); layer.Fields().ToList().ForEach(field => Console.Write(String.Format("{0} {1} ", field.GetName(), field.GetFieldTypeName(field.GetFieldType())))); Console.Write("\n"); var clist = layer.Features().Select(a => a.GetFieldAsString(1)).ToList(); Console.WriteLine(String.Join(" , ", clist)); Console.Write("\n"); foreach (var feature in layer.Features()) { Console.WriteLine(feature.GetFieldAsString(1)); var geomType = feature.GetGeometryRef().GetGeometryType(); Console.WriteLine(geomType); //var j = feature.GetGeometryRef().ExportToJson(null); foreach (var geometry in feature.GetGeometryRef().Geometries()) { //Console.WriteLine(geometry.GetGeometryType()); Envelope envelope = new Envelope(); geometry.GetEnvelope(env: envelope); var pointCount = geometry.GetGeometryRef(0).GetPointCount(); foreach (var point in geometry.GetGeometryRef(0).Points()) { //Console.WriteLine(String.Format("{0} {1}", point[0], point[1])); } var gml = geometry.ExportToGML(); var json = geometry.ExportToJson(null); foreach (var point in geometry.Points()) { ; } } } layer.ResetReading(); var gfr = layer.GetFeaturesRead(); //Console.ReadLine(); }
//private static int GetLayerIndexByName(); //private static int GetFieldIndexByName(); static void Main(string[] args) { Gdal.AllRegister(); Ogr.RegisterAll(); //Gdal.SetConfigOption("GDAL_DATA", // System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "gdal-data")); Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); Gdal.SetConfigOption("SHAPE_ENCODING", "UTF8"); Osr.SetPROJSearchPath(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "proj7", "share")); //Gdal.SetConfigOption("OGR_SKIP","ODBC"); //Gdal.SetConfigOption("PGEO_DRIVER_TEMPLATE", // $"DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"); //Gdal.SetConfigOption("MDB_DRIVER_TEMPLATE", // $"DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"); const string gdbPath = @"C:\Users\x\Documents\ArcGIS\Default.gdb"; // const string mdbPath = @"C:\Users\x\Documents\ArcGIS\个人.mdb"; var gdbDriver = Ogr.GetDriverByName("FileGDB"); // var mdbDriver = Ogr.GetDriverByName("PGeo"); var gdb = gdbDriver.Open(gdbPath, 1); var lrCount = gdb.GetLayerCount(); var lrIndex = -1; for (int j = 0; j < lrCount; j++) { if (gdb.GetLayerByIndex(j).GetName() == GetGB2312("面")) { lrIndex = j; break; } } var lr = gdb.GetLayerByIndex(lrIndex); var i = lr.FindFieldIndex(GetGB2312("描述"), 1); // 写入 gdb var fn = lr.GetLayerDefn(); var msIndex = -1; for (int j = 0; j < fn.GetFieldCount(); j++) { if (fn.GetFieldDefn(j).GetName() == GetGB2312("描述")) { msIndex = j; break; } } Feature f = new Feature(fn); f.SetField(GetGB2312("描述"), "描述内容"); f.SetField(msIndex, "描述内容"); lr.CreateFeature(f); lr.Dispose(); //var b = Encoding.UTF8.GetBytes("AB"); //b = Encoding.GetEncoding("gb2312").GetBytes("景号"); }
public Image GetTile(int level, SizeL address) { // Read tile CheckParameters(level, address); var col = address.Width; var row = address.Height; // Get preferred slide level var preferedSlideLevel = BestSlideLevelForDeepZoomLevel[level]; // Calculate top left and bottom right overlap var topLeftOverlap = new SizeL(col == 0 ? 0 : DeepZoomOverlap, row == 0 ? 0 : DeepZoomOverlap); var bottomRightOverlap = new SizeL(col == TileDimensions[level].Width - 1 ? 0 : DeepZoomOverlap, row == TileDimensions[level].Height - 1 ? 0 : DeepZoomOverlap); // Get final size of the tile var finalTileWidth = Math.Min(TileSize, DeepZoomLevelDimensions[level].Width - TileSize * col) + topLeftOverlap.Width + bottomRightOverlap.Width; var finalTileHeight = Math.Min(TileSize, DeepZoomLevelDimensions[level].Height - TileSize * row) + topLeftOverlap.Height + bottomRightOverlap.Height; var finalTileSize = new SizeL(finalTileWidth, finalTileHeight); if (finalTileSize.Width < 0 || finalTileSize.Height < 0) { throw new ArgumentException($"out of bounds level {level}, row {row}, col {col}"); } // Obtain the region coordinates var deepZoomLocation = new SizeL(TileSize * col, TileSize * row); var levelLocation = new SizeF( (float)DeepZoomLevelDownsamples[level] * (deepZoomLocation.Width - topLeftOverlap.Width), (float)DeepZoomLevelDownsamples[level] * (deepZoomLocation.Height - topLeftOverlap.Height)); // Round location down and size up, and add offset of active area var level0Location = new SizeL( (long)(Osr.LevelDownsamples[preferedSlideLevel] * levelLocation.Width + Level0Offset.Width), (long)(Osr.LevelDownsamples[preferedSlideLevel] * levelLocation.Height + Level0Offset.Height)); var regionWidth = (long)Math.Min(Math.Ceiling(DeepZoomLevelDownsamples[level] * finalTileSize.Width), LevelDimensions[preferedSlideLevel].Width - Math.Ceiling(levelLocation.Width)); var regionHeight = (long)Math.Min(Math.Ceiling(DeepZoomLevelDownsamples[level] * finalTileSize.Height), LevelDimensions[preferedSlideLevel].Height - Math.Ceiling(levelLocation.Height)); var regionSize = new SizeL(regionWidth, regionHeight); var tileBmp = Osr.ReadRegion(level0Location, preferedSlideLevel, regionSize); //Apply on background color (composite) tileBmp = ApplyOnBackgroundColor(tileBmp); // Scale to the correct size var deepZoomSize = finalTileSize; if (regionSize.Width == deepZoomSize.Width && regionSize.Height == deepZoomSize.Height) { return(tileBmp); } tileBmp = new Bitmap(tileBmp, deepZoomSize.ToSize()); return(tileBmp); }
private int[] GetBestSlideLevelsForDeepZoomLevels() { return(Level0DeepZoomDownsamples.Select(d => Osr.GetBestLevelForDownsample(d)).ToArray()); }
/// <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(); }