private static void AddPoint(this OSGeo.OGR.Geometry geometry, ICoordinate coordinate) { if (geometry != null && coordinate != null) { geometry.AddPoint(coordinate.X, coordinate.Y, coordinate.Z, coordinate.M); } }
////////////////////////////////////////////////////// ////////////////////////////////////////////////////// ///TODO: Converting Rhino/GH geometry type to GDAL geometry types public static OSGeo.OGR.Geometry Point3dToOgrPoint(Point3d pt3d) { OSGeo.OGR.Geometry ogrPoint = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); ogrPoint.AddPoint(pt3d.X, pt3d.Y, pt3d.Z); return(ogrPoint); }
private static OSGeo.OGR.Geometry GetOgrGeometry(wkbGeometryType geometryType, IEnumerable <ICoordinate> coordinates) { OSGeo.OGR.Geometry ogrGeometry = null; var firstCoord = coordinates?.FirstOrDefault(); if (firstCoord != null) { ogrGeometry = new OSGeo.OGR.Geometry(geometryType); Action <ICoordinate> addCoordAction; switch (firstCoord.Dimension) { case 2: addCoordAction = (coordinate) => ogrGeometry.AddPoint_2D(coordinate.X, coordinate.Y); break; case 3: addCoordAction = (coordinate) => ogrGeometry.AddPoint(coordinate.X, coordinate.Y, coordinate.Z); break; case 4: addCoordAction = (coordinate) => ogrGeometry.AddPointZM(coordinate.X, coordinate.Y, coordinate.Z, coordinate.M); break; default: return(ogrGeometry); } foreach (var item in coordinates) { addCoordAction(item); } } return(ogrGeometry); }
private static void AddPoint(this OSGeo.OGR.Geometry geometry, double x, double y, double z = double.NaN, double m = double.NaN) { if (geometry != null) { if (double.IsNaN(z)) { if (double.IsNaN(m)) { geometry.AddPoint_2D(x, y); } else { geometry.AddPointM(x, y, m); } } else { if (double.IsNaN(m)) { geometry.AddPoint(x, y, z); } else { geometry.AddPointZM(x, y, z, m); } } } }
////////////////////////////////////////////////////// ////////////////////////////////////////////////////// ///TODO: Converting Rhino/GH geometry type to GDAL geometry types public static OSGeo.OGR.Geometry Point3dToOgrPoint(Point3d pt3d, Transform transform) { pt3d.Transform(transform); OSGeo.OGR.Geometry ogrPoint = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint25D); ogrPoint.AddPoint(pt3d.X, pt3d.Y, pt3d.Z); return(ogrPoint); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { ///GDAL setup RESTful.GdalConfiguration.ConfigureOgr(); ///Working with data trees allows us to only call the osr coordinate transformation once, which seems to be expensive GH_Structure <GH_Point> sourcePoints = new GH_Structure <GH_Point>(); DA.GetDataTree(0, out sourcePoints); GH_Structure <GH_Point> destPoints = new GH_Structure <GH_Point>(); string sourceString = string.Empty; DA.GetData(1, ref sourceString); OSGeo.OSR.SpatialReference sourceSRS = new OSGeo.OSR.SpatialReference(""); sourceSRS.SetFromUserInput(sourceString); if (sourceSRS.Validate() == 1) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Source SRS."); return; } string destString = string.Empty; DA.GetData(2, ref destString); OSGeo.OSR.SpatialReference destSRS = new OSGeo.OSR.SpatialReference(""); destSRS.SetFromUserInput(destString); if (destSRS.Validate() == 1) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Destination SRS."); return; } OSGeo.OSR.CoordinateTransformation trans = new OSGeo.OSR.CoordinateTransformation(sourceSRS, destSRS); foreach (var path in sourcePoints.Paths) { List <GH_Point> branchPts = (List <GH_Point>)sourcePoints.get_Branch(path); foreach (var sp in branchPts) { OSGeo.OGR.Geometry destOgrPoint = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); destOgrPoint.AddPoint(sp.Value.X, sp.Value.Y, sp.Value.Z); destOgrPoint.AssignSpatialReference(sourceSRS); destOgrPoint.Transform(trans); Point3d destPoint = new Point3d(destOgrPoint.GetX(0), destOgrPoint.GetY(0), destOgrPoint.GetZ(0)); destPoints.Append(new GH_Point(destPoint), path); destOgrPoint.Dispose(); } } DA.SetDataTree(0, destPoints); }
/// <summary> /// 三点夹角的判定条件,输出为满足条件的成员的ID所组成的ID数组 /// </summary> /// <param name="aFeat"></param> /// <returns></returns> private static OSGeo.OGR.Geometry JID(Point[] aFeat, double userSet, int seleTime) { List <Point[]> pjGroupL = new List <Point[]>(); List <Point[]> zjGroupL = new List <Point[]>(); List <Point> pjGroup = new List <Point>(); List <Point> zjGroup = new List <Point>(); for (int i = 0; i < aFeat.Length; i++) { int frontId, thisId, backId; bool[] yon = new bool[seleTime]; for (int t = 1; t <= seleTime; t++) { frontId = i < t ? aFeat.Length - 1 + i - t : i - t; thisId = i; backId = i > aFeat.Length - 1 - t ? i - (aFeat.Length - 1) + t : backId = i + t; double jiaodu = cosCalculator(aFeat[frontId], aFeat[thisId], aFeat[backId]); yon[t - 1] = jiaodu > userSet; } if (yon.Contains(true)) { pjGroup.Add(aFeat[i]); } else { zjGroup.Add(aFeat[i]); } } OSGeo.OGR.Geometry outGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon); OSGeo.OGR.Geometry subGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); for (int g = 0; g < zjGroup.Count(); g++) { Point a = zjGroup[g]; subGeom.AddPoint(a.X, a.Y, a.Z); } if (subGeom.GetPointCount() < 4) { return(null); } subGeom.CloseRings(); outGeom.AddGeometry(subGeom); return(outGeom); }
public static OSGeo.OGR.Geometry CurveToOgrRing(Curve curve) { Polyline pL = new Polyline(); curve.TryGetPolyline(out pL); OSGeo.OGR.Geometry ring = new OSGeo.OGR.Geometry(wkbGeometryType.wkbLinearRing); foreach (Point3d pt in pL) { ring.AddPoint(pt.X, pt.Y, pt.Z); } return(ring); }
public static OSGeo.OGR.Geometry CurveToOgrLinestring(Curve curve, Transform transform) { Polyline pL = new Polyline(); curve.TryGetPolyline(out pL); OSGeo.OGR.Geometry linestring = new OSGeo.OGR.Geometry(wkbGeometryType.wkbLineString25D); foreach (Point3d pt in pL) { pt.Transform(transform); linestring.AddPoint(pt.X, pt.Y, pt.Z); } return(linestring); }
public static OSGeo.OGR.Geometry ToOgrPoint(double x, double y, double z = double.NaN, double m = double.NaN) { OSGeo.OGR.Geometry ogrGeometry = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); if (double.IsNaN(z)) { ogrGeometry.AddPoint_2D(x, y); } else { if (double.IsNaN(m)) { ogrGeometry.AddPoint(x, y, z); } else { ogrGeometry.AddPointZM(x, y, z, m); } } return(ogrGeometry); }
public static OSGeo.OGR.Geometry CurveToOgrRing(Curve curve, Transform transform) { Polyline pL = new Polyline(); curve.TryGetPolyline(out pL); OSGeo.OGR.Geometry ring = new OSGeo.OGR.Geometry(wkbGeometryType.wkbLinearRing); if (pL[0] != pL[pL.Count - 1]) { pL.Add(pL[0]); } foreach (Point3d pt in pL) { pt.Transform(transform); ring.AddPoint(pt.X, pt.Y, pt.Z); } return(ring); }
/// <summary> /// 转换是否纠偏,只使用与火星坐标纠偏 /// </summary> /// <param name="dataTable">数据表,如果是点表中含X,Y字段,如果是线和面,表中含有PATH字段</param> /// <param name="filePath">存储路径</param> /// <param name="geoType">数据类型,暂时支持简单的点线面</param> /// <param name="jiupian">是否纠偏[火星坐标转84坐标]</param> public static void SaveShpFile(DataTable dataTable, string filePath, wkbGeometryType geoType, ProjectConvert jiupian) { if (geoType == wkbGeometryType.wkbLineString || geoType == wkbGeometryType.wkbPolygon) { if (!dataTable.Columns.Contains("PATH")) { return; } } else if (geoType == wkbGeometryType.wkbPoint) { if (!dataTable.Columns.Contains("X") || !dataTable.Columns.Contains("Y")) { return; } } else { return; } // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); string strVectorFile = filePath; // 注册所有的驱动 Ogr.RegisterAll(); //创建数据,这里以创建ESRI的shp文件为例 string strDriverName = "ESRI Shapefile"; int count = Ogr.GetDriverCount(); Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { log.ErrorFormat("{0}驱动不可用!\n", strVectorFile); Console.WriteLine("{0}驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { log.ErrorFormat("创建矢量文件{0}失败!\n", strVectorFile); Console.WriteLine("创建矢量文件【%s】失败!\n", strVectorFile); return; } string strwkt = "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",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\"]]"; OSGeo.OSR.SpatialReference srs = new OSGeo.OSR.SpatialReference(strwkt); // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("test", null, geoType, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } for (int i = 0; i < dataTable.Columns.Count; i++) { if (dataTable.Columns[i].ColumnName == "PATH") { continue; } string columnName = dataTable.Columns[i].ColumnName; FieldDefn oFieldName = new FieldDefn(columnName, FieldType.OFTString); oFieldName.SetWidth(255); oLayer.CreateField(oFieldName, 1); } FeatureDefn oDefn = oLayer.GetLayerDefn(); foreach (DataRow row in dataTable.Rows) { if ((geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) && string.IsNullOrEmpty(row["PATH"].ToString())) { continue; } // 创建Multi要素 Feature oFeatureMulty = new Feature(oDefn); for (int i = 0; i < dataTable.Columns.Count; i++) { if (geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) { if (dataTable.Columns[i].ColumnName == "PATH") { continue; } } string name = row[i] != null ? row[i].ToString() : ""; if (!string.IsNullOrEmpty(name)) { try { //oFeatureMulty.SetField(dataTable.Columns[i].ColumnName,name); var value = name.Trim().Replace("'", "").Replace(",", ""); if (value.Length > 255) { value = value.Substring(0, 250); } oFeatureMulty.SetField(i, value); } catch (Exception ex) { Console.WriteLine(ex); } } } if (geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) { string path = row["PATH"] != null ? row["PATH"].ToString() : ""; if (string.IsNullOrEmpty(path)) { continue; } var geoCount = path.Split('|').Length; wkbGeometryType newGeometryType = geoType; OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(geoType); if (geoType == wkbGeometryType.wkbPolygon) { if (geoCount > 1) { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbMultiPolygon); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } var polygon = new Geometry(wkbGeometryType.wkbPolygon); polygon.AddGeometry(innGeometry); geo1.AddGeometry(polygon); } } else { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPolygon); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } geo1.AddGeometry(innGeometry); } } } else { if (geoCount > 1) { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbMultiLineString); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } geo1.AddGeometry(innGeometry); } } else { for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); geo1.AddPoint_2D(c.lon, c.lat); } } } } //if (geoType == wkbGeometryType.wkbLineString) //{ // for (int i = 0; i < ps.Length; i++) // { // var c = ProjectChange(ps[i], jiupian); // geo1.AddPoint_2D(c.lon, c.lat); // } //} //else if (geoType == wkbGeometryType.wkbPolygon) //{ // List<int> indexs = new List<int>(); // indexs.Add(0); // for (int i = 0; i < ps.Length; i++) // { // if (ps[i].Split('|', ',').Length > 2) // { // indexs.Add(i); // } // } // indexs.Add(ps.Length - 1); // if (indexs.Count == 2) // { // OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); // for (int i = 0; i < ps.Length; i++) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint_2D(c.lon, c.lat); // } // var c1 = ProjectChange(ps[0], jiupian); // outGeo.AddPoint_2D(c1.lon, c1.lat); // geo1.AddGeometryDirectly(outGeo); // } // else // { // for (int j = 0; j < indexs.Count - 1; j++) // { // OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); // Coord sc = new Coord(); // int first = indexs[j]; // int end = indexs[j + 1]; // for (int i = first; i < end + 1; i++) // { // if (i == first && first != 0) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint(c.lon, c.lat,0); // } // else // { // if (jiupian != ProjectConvert.NONE) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint(c.lon, c.lat,0); // } // else // { // double x = double.Parse(ps[i].Split('|', ',')[0]); // double y = double.Parse(ps[i].Split('|', ',')[1]); // if (i == first) // { // sc.lon = x; // sc.lat = y; // } // outGeo.AddPoint(x, y, 0); // } // } // } // outGeo.AddPoint(sc.lon, sc.lat, 0); // geo1.AddGeometryDirectly(outGeo); // } // } //} oFeatureMulty.SetGeometry(geo1); } else if (geoType == wkbGeometryType.wkbPoint) { OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); string xstring = row["X"] != null ? row["X"].ToString() : ""; string ystring = row["Y"] != null ? row["Y"].ToString() : ""; double x = double.Parse(xstring); double y = double.Parse(ystring); Coord c = CoordHelper.Gcj2Wgs(x, y); geo1.AddPoint(c.lon, c.lat, 0); oFeatureMulty.SetGeometry(geo1); } oLayer.CreateFeature(oFeatureMulty); } oLayer.Dispose(); oDS.Dispose(); }
public static Tuple <List <string>, List <Geometry> > ReadPropertyFromFile(string inputfilename, string layerName) { List <string> layerList = new List <string>(); //图层列表 Database pDb; Transaction trans; List <string> result = new List <string>(); List <Geometry> resultGeo = new List <Geometry>(); using (Services ser = new Services()) { using (pDb = new Database(false, false))//不加参数会出错 { pDb.ReadDwgFile(inputfilename, FileOpenMode.OpenForReadAndReadShare, false, ""); using (trans = pDb.TransactionManager.StartTransaction()) { BlockTableRecord btab = (BlockTableRecord)pDb.CurrentSpaceId.GetObject(OpenMode.ForRead); List <string> bb = new List <string>(); foreach (ObjectId btr in btab) //所有对象遍历 { DBObject obj; try { obj = trans.GetObject(btr, OpenMode.ForWrite); } catch { return(null); }; string a = obj.GetType().Name; if (!bb.Contains(a)) { bb.Add(a); } #region switch switch (obj.GetType().Name) { case "DBPoint": DBPoint dbpoint = (DBPoint)obj; OSGeo.OGR.Geometry point = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); point.AddPoint(dbpoint.Position.X, dbpoint.Position.Y, 0); resultGeo.Add(point); if (dbpoint.Layer != layerName) { break; } result.Add(string.Format("Point---X:{0},T:{1}", dbpoint.Position.X, dbpoint.Position.Y)); break; case "Line": Line line = (Line)obj; if (line.Layer != layerName) { break; } //result.Add(line); break; case "Ellipse": Ellipse ellipse = (Ellipse)obj; if (ellipse.Layer != layerName) { break; } //result.Add(ellipse); break; #region case "Arc": Arc arc = (Arc)obj; if (arc.Layer != layerName) { break; } // result.Add(arc); break; #endregion case "Circle": Circle circle = (Circle)obj; if (circle.Layer != layerName) { break; } result.Add(string.Format("Circle---centerX:{0},centerY:{1},radius:{2}", circle.Center.X, circle.Center.Y, circle.Radius)); //result.Add(circle); break; case "Polyline": Teigha.DatabaseServices.Polyline polyline = (Teigha.DatabaseServices.Polyline)obj; if (polyline.Layer != layerName) { break; } //result.Add(polyline); break; case "DBText": DBText dBText = (DBText)obj; if (dBText.Layer != layerName) { break; } result.Add(string.Format("DBText---TextString:{0}", dBText.TextString)); // result.Add(dBText); break; case "Region": Region region = (Region)obj; if (region.Layer != layerName) { break; } //result.Add(region); break; default: break; } #endregion } } } } return(new Tuple <List <string>, List <Geometry> >(result, resultGeo)); }
//生成的线shp函数 public void lines() { double x = 0; double y = 0; int z = 0; string pszDriverName = "ESRI Shapefile"; OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName); if (poDriver == null) { MessageBox.Show("Driver Error"); } OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //用此Driver创建Shape文件//数据源 OSGeo.OGR.DataSource poDS; poDS = poDriver.CreateDataSource("D:\\SHP_TRY", null);//指定存储文件 if (poDS == null) { MessageBox.Show("DataSource Creation Error"); } // 创建图层 Layer oLayer = poDS.CreateLayer("lines", null, wkbGeometryType.wkbLineString, null);//图层名字为【CreateLayer(名字,类型,null)】 if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 FieldDefn oFieldID = new FieldDefn("FieldID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 0); // 再创建一个叫FeatureName的字符型属性,字符长度为50 FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 创建要素 Feature oFeatureTriangle = new Feature(oDefn); OSGeo.OGR.Geometry pt = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString); oFeatureTriangle.SetField(0, 1); oFeatureTriangle.SetField(1, "line_try");//线要素名字 //写入属性!!!!!!这里是根据基站的TXT的做的实验以后可以改数据,文件地址根据实际情况可以修改 string path = "C:\\Users\\Tianh\\Desktop\\station.txt"; string l; StreamReader sr = new StreamReader(path, Encoding.Default); while ((l = sr.ReadLine()) != null) { string[] strArr = sr.ReadLine().Split('\t'); x = Convert.ToDouble(strArr[2]); //经度 y = Convert.ToDouble(strArr[1]); //纬度 pt.AddPoint(x, y, z); } oFeatureTriangle.SetGeometry(pt); oLayer.CreateFeature(oFeatureTriangle); oFeatureTriangle.Dispose(); poDS.Dispose(); MessageBox.Show("生成文件在:D:\\SHP_TRY!"); }
public static Transform GetUserSRSToModelTransform(OSGeo.OSR.SpatialReference userSRS) { ///TODO: Check what units the userSRS is in and coordinate with the scaling function. Currently only accounts for a userSRS in meters. ///TODO: translate or scale GCS (decimal degrees) to something like a Projectected Coordinate System. Need to go dd to xy ///transform rhino EAP from rhinoSRS to userSRS double eapLat = EarthAnchorPoint.EarthBasepointLatitude; double eapLon = EarthAnchorPoint.EarthBasepointLongitude; double eapElev = EarthAnchorPoint.EarthBasepointElevation; Plane eapPlane = EarthAnchorPoint.GetEarthAnchorPlane(out Vector3d eapNorth); OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference(""); rhinoSRS.SetWellKnownGeogCS("WGS84"); OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS); //OSGeo.OGR.Geometry userAnchorPointDD = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLon, eapLat, eapElev)); OSGeo.OGR.Geometry userAnchorPointDD = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); userAnchorPointDD.AddPoint(eapLon, eapLat, eapElev); Transform t = new Transform(1.0); userAnchorPointDD.Transform(coordTransform); Point3d userAnchorPointPT = Heron.Convert.OgrPointToPoint3d(userAnchorPointDD, t); ///setup userAnchorPoint plane for move and rotation double eapLatNorth = EarthAnchorPoint.EarthBasepointLatitude + 0.5; double eapLonEast = EarthAnchorPoint.EarthBasepointLongitude + 0.5; //OSGeo.OGR.Geometry userAnchorPointDDNorth = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLon, eapLatNorth, eapElev)); OSGeo.OGR.Geometry userAnchorPointDDNorth = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); userAnchorPointDDNorth.AddPoint(eapLon, eapLatNorth, eapElev); //OSGeo.OGR.Geometry userAnchorPointDDEast = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLonEast, eapLat, eapElev)); OSGeo.OGR.Geometry userAnchorPointDDEast = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); userAnchorPointDDEast.AddPoint(eapLonEast, eapLat, eapElev); userAnchorPointDDNorth.Transform(coordTransform); userAnchorPointDDEast.Transform(coordTransform); Point3d userAnchorPointPTNorth = Heron.Convert.OgrPointToPoint3d(userAnchorPointDDNorth, t); Point3d userAnchorPointPTEast = Heron.Convert.OgrPointToPoint3d(userAnchorPointDDEast, t); Vector3d userAnchorNorthVec = userAnchorPointPTNorth - userAnchorPointPT; Vector3d userAnchorEastVec = userAnchorPointPTEast - userAnchorPointPT; Plane userEapPlane = new Plane(userAnchorPointPT, userAnchorEastVec, userAnchorNorthVec); ///shift (move and rotate) from userSRS EAP to 0,0 based on SRS north direction Transform scale = Transform.Scale(new Point3d(0.0, 0.0, 0.0), (1 / Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters))); if (userSRS.GetLinearUnitsName().ToUpper().Contains("FEET") || userSRS.GetLinearUnitsName().ToUpper().Contains("FOOT")) { scale = Transform.Scale(new Point3d(0.0, 0.0, 0.0), (1 / Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Feet))); } ///if SRS is geographic (ie WGS84) use Rhino's internal projection ///this is still buggy as it doesn't work with other geographic systems like NAD27 if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0)) { userEapPlane.Transform(WGSToXYZTransform()); scale = WGSToXYZTransform(); } Transform shift = Transform.ChangeBasis(eapPlane, userEapPlane); Transform shiftScale = Transform.Multiply(scale, shift); return(shiftScale); }
protected override void SolveInstance(IGH_DataAccess DA) { ///Gather GHA inputs List <Curve> boundary = new List <Curve>(); DA.GetDataList <Curve>("Boundary", boundary); string shpFilePath = string.Empty; DA.GetData <string>("Vector Data Location", ref shpFilePath); bool cropIt = true; DA.GetData <Boolean>("Crop file", ref cropIt); string userSRStext = "WGS84"; DA.GetData <string>(2, ref userSRStext); ///GDAL setup ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB ///It can be spotty with KML, MVT and GML and doesn't throw informative errors. Likely has to do with getting a valid CRS and ///TODO: resolve errors with reading KML, MVT, GML. DataSource dataSource = CreateDataSource(shpFilePath); List <Layer> layerSet = GetLayers(dataSource); ///Declare trees GH_Structure <GH_Rectangle> recs = new GH_Structure <GH_Rectangle>(); GH_Structure <GH_String> spatialReferences = new GH_Structure <GH_String>(); GH_Structure <GH_String> fnames = new GH_Structure <GH_String>(); GH_Structure <GH_String> fset = new GH_Structure <GH_String>(); GH_Structure <GH_Point> gset = new GH_Structure <GH_Point>(); GH_Structure <GH_Point> gsetUser = new GH_Structure <GH_Point>(); GH_Structure <GH_Rectangle> recsUser = new GH_Structure <GH_Rectangle>(); GH_Structure <GH_String> gtype = new GH_Structure <GH_String>(); GH_Structure <IGH_GeometricGoo> gGoo = new GH_Structure <IGH_GeometricGoo>(); ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer. for (int iLayer = 0; iLayer < dataSource.GetLayerCount(); iLayer++) { OSGeo.OGR.Layer layer = dataSource.GetLayerByIndex(iLayer); if (layer == null) { Console.WriteLine($"Couldn't fetch advertised layer {iLayer}"); System.Environment.Exit(-1); } long count = layer.GetFeatureCount(1); int featureCount = System.Convert.ToInt32(count); AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Layer #{iLayer} {layer.GetName()} has {featureCount} features"); ///Get the spatial reference of the input vector file and set to WGS84 if not known /// OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference(Osr.SRS_WKT_WGS84); string spatialReference = GetSpatialReference(layer, iLayer, dataSource, sourceSRS); spatialReferences.Append(new GH_String(spatialReference), new GH_Path(iLayer)); ///Set transform from input spatial reference to Rhino spatial reference ///TODO: look into adding a step for transforming to CRS set in SetCRS OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference(""); rhinoSRS.SetWellKnownGeogCS("WGS84"); ///TODO: verify the userSRS is valid ///TODO: use this as override of global SetSRS OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference(""); userSRS.SetFromUserInput(userSRStext); ///These transforms move and scale in order to go from userSRS to XYZ and vice versa Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS); Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS); Transform sourceToModelSRSTransform = Heron.Convert.GetUserSRSToModelTransform(sourceSRS); Transform modelToSourceSRSTransform = Heron.Convert.GetModelToUserSRSTransform(sourceSRS); ///Get OGR envelope of the data in the layer in the sourceSRS OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope(); layer.GetExtent(ext, 1); OSGeo.OGR.Geometry extMinSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); extMinSourceOgr.AddPoint(ext.MinX, ext.MinY, 0.0); extMinSourceOgr.AssignSpatialReference(sourceSRS); OSGeo.OGR.Geometry extMaxSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); extMaxSourceOgr.AddPoint(ext.MaxX, ext.MaxY, 0.0); extMaxSourceOgr.AssignSpatialReference(sourceSRS); ///Get extents in Rhino SRS Point3d extPTmin = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, sourceToModelSRSTransform); Point3d extPTmax = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, sourceToModelSRSTransform); Rectangle3d rec = new Rectangle3d(Plane.WorldXY, extPTmin, extPTmax); recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer)); ///Get extents in userSRS ///Can give odd results if crosses 180 longitude extMinSourceOgr.TransformTo(userSRS); extMaxSourceOgr.TransformTo(userSRS); Point3d extPTminUser = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, userSRSToModelTransform); Point3d extPTmaxUser = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, userSRSToModelTransform); Rectangle3d recUser = new Rectangle3d(Plane.WorldXY, extPTminUser, extPTmaxUser); recsUser.Append(new GH_Rectangle(recUser), new GH_Path(iLayer)); if (boundary.Count == 0 && cropIt == true) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Define a boundary or set cropIt to False"); } else if (boundary.Count == 0 && cropIt == false) { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipping boundary has not been defined. File extents will be used instead"); boundary.Add(rec.ToNurbsCurve()); } ///Loop through input boundaries for (int i = 0; i < boundary.Count; i++) { OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn(); ///Get the field names List <string> fieldnames = new List <string>(); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr); fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer)); } ///Check if boundary is contained in extent if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0))) { ///Get field data if even if no geometry is present in the layer AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid."); OSGeo.OGR.Feature feat; int m = 0; while ((feat = layer.GetNextFeature()) != null) { ///Loop through field values for (int iField = 0; iField < feat.GetFieldCount(); iField++) { OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField); fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m)); fdef.Dispose(); } m++; feat.Dispose(); } } else if (boundary[i] == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set."); } else if (!boundary[i].IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " is not valid."); } else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more clipping boundaries may be outside the bounds of the vector datasource."); } else { ///Create bounding box for clipping geometry Point3d min = boundary[i].GetBoundingBox(true).Min; Point3d max = boundary[i].GetBoundingBox(true).Max; min.Transform(modelToSourceSRSTransform); max.Transform(modelToSourceSRSTransform); double[] minpT = new double[3]; double[] maxpT = new double[3]; minpT[0] = min.X; minpT[1] = min.Y; minpT[2] = min.Z; maxpT[0] = max.X; maxpT[1] = max.Y; maxpT[2] = max.Z; OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))"); ///Create bounding box for clipping geometry ///Not working on MVT type files //boundary[i].Transform(modelToSourceSRSTransform); //OSGeo.OGR.Geometry ebbox = Heron.Convert.CurveToOgrPolygon(boundary[i]); ///Clip Shapefile ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html OSGeo.OGR.Layer clipped_layer = layer; if (cropIt) { clipped_layer.SetSpatialFilter(ebbox); } ///Loop through geometry OSGeo.OGR.Feature feat; def = clipped_layer.GetLayerDefn(); int m = 0; while ((feat = clipped_layer.GetNextFeature()) != null) { OSGeo.OGR.Geometry geom = feat.GetGeometryRef(); OSGeo.OGR.Geometry sub_geom; OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone(); OSGeo.OGR.Geometry sub_geomUser; ///reproject geometry to WGS84 and userSRS ///TODO: look into using the SetCRS global variable here if (geom.GetSpatialReference() == null) { geom.AssignSpatialReference(sourceSRS); } if (geomUser.GetSpatialReference() == null) { geomUser.AssignSpatialReference(sourceSRS); } geom.TransformTo(rhinoSRS); geomUser.TransformTo(userSRS); gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(i, iLayer, m)); if (feat.GetGeometryRef() != null) { ///Convert GDAL geometries to IGH_GeometricGoo gGoo.AppendRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform), new GH_Path(i, iLayer, m)); /// Get Feature Values if (fset.PathExists(new GH_Path(i, iLayer, m))) { fset.get_Branch(new GH_Path(i, iLayer, m)).Clear(); } for (int iField = 0; iField < feat.GetFieldCount(); iField++) { OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField); if (feat.IsFieldSet(iField)) { fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m)); } else { fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m)); } } ///End get Feature Values ///Start get points if open polylines and points for (int gpc = 0; gpc < geom.GetPointCount(); gpc++) { ///Loop through geometry points for Rhino SRS double[] ogrPt = new double[3]; geom.GetPoint(gpc, ogrPt); Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]); pt3D.Transform(Heron.Convert.WGSToXYZTransform()); gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m)); ///Loop through geometry points for User SRS double[] ogrPtUser = new double[3]; geomUser.GetPoint(gpc, ogrPtUser); Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]); pt3DUser.Transform(userSRSToModelTransform); gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m)); ///End loop through geometry points /// Get Feature Values if (fset.PathExists(new GH_Path(i, iLayer, m))) { fset.get_Branch(new GH_Path(i, iLayer, m)).Clear(); } for (int iField = 0; iField < feat.GetFieldCount(); iField++) { OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField); if (feat.IsFieldSet(iField)) { fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m)); } else { fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m)); } } ///End Get Feature Values } ///End getting points if open polylines or points ///Start getting points if closed polylines and multipolygons for (int gi = 0; gi < geom.GetGeometryCount(); gi++) { sub_geom = geom.GetGeometryRef(gi); OSGeo.OGR.Geometry subsub_geom; sub_geomUser = geomUser.GetGeometryRef(gi); OSGeo.OGR.Geometry subsub_geomUser; if (sub_geom.GetGeometryCount() > 0) { for (int n = 0; n < sub_geom.GetGeometryCount(); n++) { subsub_geom = sub_geom.GetGeometryRef(n); subsub_geomUser = sub_geomUser.GetGeometryRef(n); for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++) { ///Loop through geometry points double[] ogrPt = new double[3]; subsub_geom.GetPoint(ptnum, ogrPt); Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]); pt3D.Transform(Heron.Convert.WGSToXYZTransform()); gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi, n)); ///Loop through geometry points for User SRS double[] ogrPtUser = new double[3]; subsub_geomUser.GetPoint(ptnum, ogrPtUser); Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]); pt3DUser.Transform(userSRSToModelTransform); gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi, n)); ///End loop through geometry points } subsub_geom.Dispose(); subsub_geomUser.Dispose(); } } else { for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++) { ///Loop through geometry points double[] ogrPt = new double[3]; sub_geom.GetPoint(ptnum, ogrPt); Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]); pt3D.Transform(Heron.Convert.WGSToXYZTransform()); gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi)); ///Loop through geometry points for User SRS double[] ogrPtUser = new double[3]; sub_geomUser.GetPoint(ptnum, ogrPtUser); Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]); pt3DUser.Transform(userSRSToModelTransform); gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi)); ///End loop through geometry points } } sub_geom.Dispose(); sub_geomUser.Dispose(); /// Get Feature Values if (fset.PathExists(new GH_Path(i, iLayer, m))) { fset.get_Branch(new GH_Path(i, iLayer, m)).Clear(); } for (int iField = 0; iField < feat.GetFieldCount(); iField++) { OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField); if (feat.IsFieldSet(iField)) { fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m)); } else { fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m)); } } ///End Get Feature Values } //m++; } m++; geom.Dispose(); geomUser.Dispose(); feat.Dispose(); } ///end while loop through features } ///end clipped layer else statement } ///end loop through boundaries layer.Dispose(); }///end loop through layers dataSource.Dispose(); DA.SetDataTree(0, recs); DA.SetDataTree(1, spatialReferences); DA.SetDataTree(2, fnames); DA.SetDataTree(3, fset); DA.SetDataTree(4, gset); DA.SetDataTree(5, gsetUser); DA.SetDataTree(6, recsUser); DA.SetDataTree(7, gGoo); DA.SetDataTree(8, gtype); }
//将内存中一个图层的数据另存为在文件中 private Boolean SaveAsToFile(String name, String path) { Ogr.RegisterAll(); //to support chinese path OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); //to support chinese field name OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); string strDriverName = "ESRI Shapefile"; Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { //说明driver不可用 return(false); } String pathPrefix = System.IO.Path.GetDirectoryName(path); String pathPostfix = System.Guid.NewGuid().ToString(); if (File.Exists(pathPrefix + "\\" + pathPostfix)) { File.Delete(pathPrefix + "\\" + pathPostfix); } //create a datasource, if successfully, a shp file would be created DataSource oDs = oDriver.CreateDataSource(pathPrefix + "\\" + pathPostfix, null); Schema tmpSchema = this.featureSources[name].schema; Layer layer = oDs.CreateLayer(name, tmpSchema.rs.spetialReference, tmpSchema.geometryType, null); //insert all the fields to layer //use index instead of field name to avoid the error caused by chinese words int fieldcount = tmpSchema.fields.Count; for (int i = 0; i < fieldcount; ++i) { layer.CreateField(tmpSchema.fields.ElementAt(i).Value, 1); } FeatureDefn fdef = layer.GetLayerDefn(); FeatureCollection fc = this.featureSources[name].features; int fcount = fc.count; for (int i = 0; i < fcount; ++i) { GisSmartTools.Data.Feature tmpFeature = fc.featureList[i]; if (!tmpFeature.visible) { continue; } //create a new feature OSGeo.OGR.Feature newFeature = new OSGeo.OGR.Feature(fdef); //set attribute newFeature.SetFID(tmpFeature.featureID); for (int j = 0; j < fieldcount; ++j) { String fieldname = tmpSchema.fields.ElementAt(j).Key; FieldType ft = tmpSchema.fields[fieldname].GetFieldType(); try{ switch (ft) { case FieldType.OFTString: newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]); break; case FieldType.OFTInteger: newFeature.SetField(j, (int)tmpFeature.attributes[fieldname]); break; case FieldType.OFTReal: newFeature.SetField(j, (double)tmpFeature.attributes[fieldname]); break; case FieldType.OFTWideString: newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]); break; default: newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]); break; } }catch (Exception e) { } } //get geometry OSGeo.OGR.wkbGeometryType featType = tmpFeature.geometry.geometryType; OSGeo.OGR.Geometry geo = new OSGeo.OGR.Geometry(featType); if (geo != null) { switch (featType) { case OSGeo.OGR.wkbGeometryType.wkbPoint: GisSmartTools.Geometry.PointD tmpPoint = (GisSmartTools.Geometry.PointD)tmpFeature.geometry; geo.AddPoint(tmpPoint.X, tmpPoint.Y, 0.00); break; case OSGeo.OGR.wkbGeometryType.wkbLineString: GisSmartTools.Geometry.SimplePolyline tmpLine = (GisSmartTools.Geometry.SimplePolyline)tmpFeature.geometry; foreach (GisSmartTools.Geometry.PointD po in tmpLine.points) { geo.AddPoint(po.X, po.Y, 0.00); } break; case wkbGeometryType.wkbMultiLineString: GisSmartTools.Geometry.Polyline lines = (GisSmartTools.Geometry.Polyline)tmpFeature.geometry; foreach (SimplePolyline line in lines.childPolylines) { OSGeo.OGR.Geometry tmpgeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString); foreach (GisSmartTools.Geometry.PointD point in line.points) { tmpgeo.AddPoint(point.X, point.Y, 0.00); } geo.AddGeometryDirectly(tmpgeo); } break; case OSGeo.OGR.wkbGeometryType.wkbPolygon: GisSmartTools.Geometry.SimplePolygon gon = (GisSmartTools.Geometry.SimplePolygon)tmpFeature.geometry; foreach (SimplePolyline ring7 in gon.rings) { OSGeo.OGR.Geometry tmpgeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); foreach (GisSmartTools.Geometry.PointD point in ring7.points) { tmpgeo.AddPoint(point.X, point.Y, 0.00); } geo.AddGeometryDirectly(tmpgeo); } break; case wkbGeometryType.wkbMultiPolygon: GisSmartTools.Geometry.Polygon gons = (GisSmartTools.Geometry.Polygon)tmpFeature.geometry; foreach (GisSmartTools.Geometry.SimplePolygon cgon in gons.childPolygons) { OSGeo.OGR.Geometry geogon = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon); foreach (GisSmartTools.Geometry.SimplePolyline ring6 in cgon.rings) { OSGeo.OGR.Geometry geoline = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); foreach (GisSmartTools.Geometry.PointD point6 in ring6.points) { geoline.AddPoint(point6.X, point6.Y, 0.00); } geogon.AddGeometryDirectly(geoline); } geo.AddGeometryDirectly(geogon); } break; default: break; } } //set feature newFeature.SetGeometry(geo); //add to layer layer.CreateFeature(newFeature); } //call Dispose method to save to file oDs.Dispose(); DataSource tds; if (this.iDses.TryGetValue(path, out tds)) { tds.Dispose(); this.iDses.Remove(path); } //enumerate all the files in the temp file directory and move them to the output directory string[] tmpName = System.IO.Directory.GetFiles(pathPrefix + "\\" + pathPostfix); foreach (string file in tmpName) { string decFile = pathPrefix + "\\" + Path.GetFileName(file); if (File.Exists(decFile)) { File.Delete(decFile); } File.Move(file, decFile); } Directory.Delete(pathPrefix + "\\" + pathPostfix, true); return(true); }
//生成点shp的函数 public void pint() { string shpname = System.IO.Path.GetFileNameWithoutExtension(tra_input_tb.Text);//生产的shp文件名为输入文件的文件名; //注册Ogr库 string pszDriverName = "ESRI Shapefile"; OSGeo.OGR.Ogr.RegisterAll(); //调用对Shape文件读写的Driver接口 OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName); if (poDriver == null) { MessageBox.Show("Driver Error"); } OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //用此Driver创建Shape文件//数据源 OSGeo.OGR.DataSource poDS; poDS = poDriver.CreateDataSource("D:\\SHP_TRY", null); if (poDS == null) { MessageBox.Show("DataSource Creation Error"); } //创建层Layer OSGeo.OGR.Layer poLayer; poLayer = poDS.CreateLayer(shpname, null, OSGeo.OGR.wkbGeometryType.wkbPoint, null);//shpname为提取输入TXT的文件名为shp文件文件名; if (poLayer == null) { MessageBox.Show("Layer Creation Failed"); } //创建属性表!!!!!这里是根据基站的TXT的做的实验以后可以改数据 OSGeo.OGR.FieldDefn oField0 = new OSGeo.OGR.FieldDefn("uid", OSGeo.OGR.FieldType.OFTString); oField0.SetWidth(16); OSGeo.OGR.FieldDefn oField1 = new OSGeo.OGR.FieldDefn("time", OSGeo.OGR.FieldType.OFTString); OSGeo.OGR.FieldDefn oField2 = new OSGeo.OGR.FieldDefn("locationid", OSGeo.OGR.FieldType.OFTString); OSGeo.OGR.FieldDefn oField3 = new OSGeo.OGR.FieldDefn("lat", OSGeo.OGR.FieldType.OFTString); OSGeo.OGR.FieldDefn oField4 = new OSGeo.OGR.FieldDefn("lon", OSGeo.OGR.FieldType.OFTInteger); poLayer.CreateField(oField0, 1); poLayer.CreateField(oField2, 2); poLayer.CreateField(oField0, 3); poLayer.CreateField(oField0, 4); poLayer.CreateField(oField0, 5); //创建一个Feature,一个Point OSGeo.OGR.Feature poFeature = new OSGeo.OGR.Feature(poLayer.GetLayerDefn()); OSGeo.OGR.Geometry pt = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint); string path = tra_input_tb.Text;//TXT输入路径; string l; StreamReader sr = new StreamReader(path, Encoding.Default); while ((l = sr.ReadLine()) != null) { string[] strArr = sr.ReadLine().Split('\t'); //属性表赋值 poFeature.SetField(0, strArr[0]); poFeature.SetField(1, strArr[4]); poFeature.SetField(2, strArr[3]); poFeature.SetField(3, strArr[1]); poFeature.SetField(4, strArr[2]); //添加坐标点 pt.AddPoint(Convert.ToDouble(strArr[2]), Convert.ToDouble(strArr[1]), 0); poFeature.SetGeometry(pt); //将带有坐标及属性的Feature要素点写入Layer中 poLayer.CreateFeature(poFeature); } //关闭文件读写 poFeature.Dispose(); poDS.Dispose(); MessageBox.Show("生成文件在:D:\\SHP_TRY!"); }
public static void WriteVectorFile(string strVectorFile) { Gdal.AllRegister(); // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); //string strVectorFile = @"C:\Users\Administrator\Desktop\shptest\TestPolygon.shp"; // 注册所有的驱动 Ogr.RegisterAll(); //创建数据,这里以创建ESRI的shp文件为例 string strDriverName = "ESRI Shapefile"; OSGeo.OGR.Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { MessageBox.Show("%s 驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { MessageBox.Show("创建矢量文件【%s】失败!\n", strVectorFile); return; } // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("TestPolygon", null, wkbGeometryType.wkbPolygon, null); if (oLayer == null) { MessageBox.Show("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 FieldDefn oFieldID = new FieldDefn("FieldID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 1); // 再创建一个叫FeatureName的字符型属性,字符长度为50 FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 创建三角形要素 Feature oFeatureTriangle = new Feature(oDefn); oFeatureTriangle.SetField(0, 0); oFeatureTriangle.SetField(1, "三角形"); Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON ((0 0,20 0,10 15,0 0))"); oFeatureTriangle.SetGeometry(geomTriangle); oLayer.CreateFeature(oFeatureTriangle); // 创建矩形要素 Feature oFeatureRectangle = new Feature(oDefn); oFeatureRectangle.SetField(0, 1); oFeatureRectangle.SetField(1, "矩形"); Geometry geomRectangle = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))"); oFeatureRectangle.SetGeometry(geomRectangle); oLayer.CreateFeature(oFeatureRectangle); // 创建岛要素 Feature oFeatureHole = new Feature(oDefn); oFeatureHole.SetField(0, 1); oFeatureHole.SetField(1, "环岛测试"); //Geometry geomWYX = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))"); OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); outGeo.AddPoint(40, -30, 0); outGeo.AddPoint(60, -30, 0); outGeo.AddPoint(60, -10, 0); outGeo.AddPoint(40, -10, 0); OSGeo.OGR.Geometry inGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); inGeo.AddPoint(45, -25, 0); inGeo.AddPoint(55, -25, 0); inGeo.AddPoint(55, -15, 0); inGeo.AddPoint(45, -15, 0); OSGeo.OGR.Geometry geo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon); geo.AddGeometryDirectly(outGeo); geo.AddGeometryDirectly(inGeo); oFeatureHole.SetGeometry(geo); oLayer.CreateFeature(oFeatureHole); // 创建Multi要素 Feature oFeatureMulty = new Feature(oDefn); oFeatureMulty.SetField(0, 1); oFeatureMulty.SetField(1, "MultyPart测试"); OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); geo1.AddPoint(25, -10, 0); geo1.AddPoint(5, -10, 0); geo1.AddPoint(5, -30, 0); geo1.AddPoint(25, -30, 0); OSGeo.OGR.Geometry poly1 = new Geometry(wkbGeometryType.wkbPolygon); poly1.AddGeometryDirectly(geo1); OSGeo.OGR.Geometry geo2 = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); geo2.AddPoint(0, -15, 0); geo2.AddPoint(-5, -15, 0); geo2.AddPoint(-5, -20, 0); geo2.AddPoint(0, -20, 0); OSGeo.OGR.Geometry poly2 = new Geometry(wkbGeometryType.wkbPolygon); poly2.AddGeometryDirectly(geo2); OSGeo.OGR.Geometry geoMulty = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbMultiPolygon); geoMulty.AddGeometryDirectly(poly1); geoMulty.AddGeometryDirectly(poly2); oFeatureMulty.SetGeometry(geoMulty); oLayer.CreateFeature(oFeatureMulty); MessageBox.Show("\n数据集创建完成!\n"); }
protected override void SolveInstance(IGH_DataAccess DA) { List <Curve> boundary = new List <Curve>(); DA.GetDataList <Curve>("Boundary", boundary); int Res = -1; DA.GetData <int>("Resolution", ref Res); string fileloc = ""; DA.GetData <string>("File Location", ref fileloc); if (!fileloc.EndsWith(@"\")) { fileloc = fileloc + @"\"; } string prefix = ""; DA.GetData <string>("Prefix", ref prefix); string URL = ""; DA.GetData <string>("REST URL", ref URL); bool run = false; DA.GetData <bool>("run", ref run); string userSRStext = ""; DA.GetData <string>("User Spatial Reference System", ref userSRStext); ///GDAL setup RESTful.GdalConfiguration.ConfigureOgr(); ///TODO: implement SetCRS here. ///Option to set CRS here to user-defined. Needs a SetCRS global variable. //string userSRStext = "EPSG:4326"; OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference(""); userSRS.SetFromUserInput(userSRStext); int userSRSInt = Int16.Parse(userSRS.GetAuthorityCode(null)); ///Set transform from input spatial reference to Rhino spatial reference OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference(""); rhinoSRS.SetWellKnownGeogCS("WGS84"); ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS); Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS); OSGeo.OSR.CoordinateTransformation coordTransformRhinoToUser = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS); OSGeo.OSR.CoordinateTransformation coordTransformUserToRhino = new OSGeo.OSR.CoordinateTransformation(userSRS, rhinoSRS); GH_Structure <GH_String> mapList = new GH_Structure <GH_String>(); GH_Structure <GH_String> mapquery = new GH_Structure <GH_String>(); GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>(); FileInfo file = new FileInfo(fileloc); file.Directory.Create(); string size = ""; if (Res != 0) { size = "&size=" + Res + "%2C" + Res; } for (int i = 0; i < boundary.Count; i++) { GH_Path path = new GH_Path(i); //Get image frame for given boundary BoundingBox imageBox = boundary[i].GetBoundingBox(false); Point3d min = Heron.Convert.XYZToWGS(imageBox.Min); Point3d max = Heron.Convert.XYZToWGS(imageBox.Max); Rectangle3d rect = BBoxToRect(imageBox); ///ogr method OSGeo.OGR.Geometry minOgr = Heron.Convert.Point3dToOgrPoint(min); minOgr.Transform(coordTransformRhinoToUser); OSGeo.OGR.Geometry maxOgr = Heron.Convert.Point3dToOgrPoint(max); maxOgr.Transform(coordTransformRhinoToUser); //Query the REST service string restquery = URL + ///legacy method for creating bounding box string //"bbox=" + Heron.Convert.ConvertLat(min.X, 3857) + "%2C" + Heron.Convert.ConvertLon(min.Y, 3857) + "%2C" + Heron.Convert.ConvertLat(max.X, 3857) + "%2C" + Heron.Convert.ConvertLon(max.Y, 3857) + ///ogr method for creating bounding box string "bbox=" + minOgr.GetX(0) + "%2C" + minOgr.GetY(0) + "%2C" + maxOgr.GetX(0) + "%2C" + maxOgr.GetY(0) + "&bboxSR=" + userSRSInt + size + //"&layers=&layerdefs=" + "&imageSR=" + userSRSInt + //"&transparent=false&dpi=&time=&layerTimeOptions=" + "&format=jpg&f=json"; mapquery.Append(new GH_String(restquery), path); string result = ""; if (run) { ///get extent of image from arcgis rest service as JSON result = Heron.Convert.HttpToJson(restquery); JObject jObj = JsonConvert.DeserializeObject <JObject>(result); Point3d extMin = new Point3d((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0); Point3d extMax = new Point3d((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0); ///convert and transform extents to points OSGeo.OGR.Geometry extOgrMin = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPointZM); extOgrMin.AddPoint((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0.0); extOgrMin.Transform(coordTransformUserToRhino); Point3d ogrPtMin = Heron.Convert.OgrPointToPoint3d(extOgrMin); OSGeo.OGR.Geometry extOgrMax = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPointZM); extOgrMax.AddPoint((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0.0); extOgrMax.Transform(coordTransformUserToRhino); Point3d ogrPtMax = Heron.Convert.OgrPointToPoint3d(extOgrMax); ///if SRS is geographic (ie WGS84) use Rhino's internal projection ///this is still buggy as it doesn't work with other geographic systems like NAD27 if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0)) { rect = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(extMin), Heron.Convert.WGSToXYZ(extMax)); } else { //rect = new Rectangle3d(Plane.WorldXY, Heron.Convert.UserSRSToXYZ(extMin, userSRSToModel), Heron.Convert.UserSRSToXYZ(extMax, userSRSToModel)); rect = new Rectangle3d(Plane.WorldXY, userSRSToModelTransform * extMin, userSRSToModelTransform * extMax); } ///download image from source string imageQuery = jObj["href"].ToString(); System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadFile(imageQuery, fileloc + prefix + "_" + i + ".jpg"); webClient.Dispose(); } var bitmapPath = fileloc + prefix + "_" + i + ".jpg"; mapList.Append(new GH_String(bitmapPath), path); imgFrame.Append(new GH_Rectangle(rect), path); AddPreviewItem(bitmapPath, rect); } DA.SetDataTree(0, mapList); DA.SetDataTree(1, imgFrame); DA.SetDataTree(2, mapquery); }