private void generateShapeInfo() { if (!this.hShpIsOpen) { hShp = ShapeLib.SHPOpenW(this.filePath, this.access); } if (hShp.Equals(IntPtr.Zero)) { MessageBox.Show("Oops - hShp = 0"); } else { // get shape info and verify shapes were created correctly double[] minB = new double[4]; double[] maxB = new double[4]; int nEntities = 0; ShapeLib.ShapeType shapeType = ShapeLib.ShapeType.PolyLine; ShapeLib.SHPGetInfo(hShp, ref nEntities, ref shapeType, minB, maxB); this.numberOfShapes = nEntities; this.shapeType = shapeType; this.minB = minB; this.maxB = maxB; ShapeLib.SHPClose(hShp); this.hShpIsOpen = false; this.isShapeInfoRead = true; } }
public override void Close() { try { if (this.intptr_0 != IntPtr.Zero) { ShapeLib.SHPClose(this.intptr_0); this.intptr_0 = IntPtr.Zero; } } catch { } try { if (this.intptr_1 != IntPtr.Zero) { ShapeLib.DBFClose(this.intptr_1); this.intptr_1 = IntPtr.Zero; } } catch { } }
public ShapeLayerClass(string string_1, string string_2, ICoLayer icoLayer_1) { this.method_0(string_1); this.list_0.Clear(); this.string_0 = string_1.ToUpper(); if (this.string_0.EndsWith(".SHP")) { this.string_0 = this.string_0.Substring(0, this.string_0.Length - 4); } if (string_2.ToLower().Trim() == "point") { this.shapeType_0 = ShapeLib.ShapeType.Point; } if (string_2.ToLower().Trim() == "line") { this.shapeType_0 = ShapeLib.ShapeType.PolyLine; } if (string_2.ToLower().Trim() == "polygon") { this.shapeType_0 = ShapeLib.ShapeType.Polygon; } if (string_2.ToLower().Trim() == "text") { this.shapeType_0 = ShapeLib.ShapeType.Point; } this.intptr_0 = ShapeLib.SHPCreate(this.string_0, this.shapeType_0); if (!this.intptr_0.Equals(IntPtr.Zero)) { this.intptr_1 = ShapeLib.DBFCreate(this.string_0); if (!this.intptr_1.Equals(IntPtr.Zero)) { this.method_1(icoLayer_1); } } }
private void method_1(ICoLayer icoLayer_1) { for (int i = 0; i < icoLayer_1.Fields.Count; i++) { ICoField field = icoLayer_1.Fields[i]; string name = field.Name; switch (field.Type) { case CoFieldType.整型: ShapeLib.DBFAddField(this.intptr_1, name, ShapeLib.DBFFieldType.FTInteger, 16, 0); this.list_0.Add(name); break; case CoFieldType.浮点型: { int length = field.Length; int precision = field.Precision; ShapeLib.DBFAddField(this.intptr_1, name, ShapeLib.DBFFieldType.FTDouble, length, precision); this.list_0.Add(name); break; } case CoFieldType.字符型: { int num4 = field.Length; ShapeLib.DBFAddField(this.intptr_1, name, ShapeLib.DBFFieldType.FTString, num4, 0); this.list_0.Add(name); break; } case CoFieldType.日期型: ShapeLib.DBFAddField(this.intptr_1, name, ShapeLib.DBFFieldType.FTInteger, 8, 0); this.list_0.Add(name); break; case CoFieldType.二进制: ShapeLib.DBFAddField(this.intptr_1, name, ShapeLib.DBFFieldType.FTLogical, 5, 0); this.list_0.Add(name); break; } } }
/// <summary> /// Utility method to write shapefiles /// </summary> /// <param name="filename">Output Shapefile name</param> private void writeShape(string filename) { IntPtr shphandle = ShapeLib.SHPCreate(filename,ShapeLib.ShapeType.PolyLine); double[] lat = new double[m_multiline.Count]; double[] lon = new double[m_multiline.Count]; int i=0; foreach(MeasureLine line in m_multiline) { lat[i] = line.StartLatitude.Degrees; lon[i] = line.StartLongitude.Degrees; i++; } ShapeLib.SHPObject poly = ShapeLib.SHPCreateSimpleObject(ShapeLib.ShapeType.Polygon,m_multiline.Count,lon,lat,null); ShapeLib.SHPWriteObject(shphandle,0,poly); ShapeLib.SHPDestroyObject(poly); ShapeLib.SHPClose(shphandle); }
//从源文件获取字段信息 public List <R_FieldInf> GetFieldInfs(string path) { List <R_FieldInf> FieldInfs = new List <R_FieldInf>(); string dbfpath = path; #region 该部分使用FastDBF获取字段名称 返回List<string> fieldNames DbfFile dbf = new DbfFile(Encoding.Default); dbf.Open(dbfpath, FileMode.Open); DbfHeader dh = dbf.Header; List <string> fieldNames = new List <string>(); int fieldCount = dh.ColumnCount; for (int index = 0; index < fieldCount; index++) { fieldNames.Add(dh[index].Name); } dbf.Close(); #endregion #region 该部分使用Shapelib获取字段类型 返回List<string> fieldTypes //获取字段类型 IntPtr hDbf = ShapeLib.DBFOpen(dbfpath, "rb+");//"rb"(只读)"rb+"(读/写) int pointCount = ShapeLib.DBFGetRecordCount(hDbf); List <string> fieldTypes = new List <string>(); StringBuilder stringBuilder = new StringBuilder(20); int pnWidth = 10; int pnDecimals = 10; for (int index = 0; index < fieldCount; index++) { string type = TypeConvert(ShapeLib.DBFGetFieldInfo(hDbf, index, stringBuilder, ref pnWidth, ref pnDecimals).ToString()); fieldTypes.Add(type); } ShapeLib.DBFClose(hDbf); #endregion //实例化类型 for (int index = 0; index < fieldCount; index++) { FieldInfs.Add(new R_FieldInf(fieldNames[index], fieldTypes[index])); } return(FieldInfs); }
public static void ConvertToOra(string[] args) { string pkValue = string.Empty; if (args == null || args.Length < 4) { Console.Write("\nUsage: shape2ora <username/password>@dbalias> <spatial_table_name> <shape_col> <shapefile> <srid> \n\nPress any key to exit"); Console.ReadLine(); return; } string connectionstring = Utils.ParseConnectionString(args[0].ToString()); string spatial_table = args[1].ToString(); string shape_col = args[2].ToString(); string inShapeFile = args[3].ToString(); string strSRID = "NULL"; if (args.Length == 5) { strSRID = args[4].ToString(); } if (inShapeFile.ToUpper().EndsWith(".SHP")) { inShapeFile = inShapeFile.Substring(0, inShapeFile.Length - 4); } IntPtr hShp = ShapeLib.SHPOpen(inShapeFile, "rb"); IntPtr hDbf = ShapeLib.DBFOpen(inShapeFile, "rb"); if (hDbf.Equals(IntPtr.Zero)) { Console.WriteLine("\nCould not open {0}.dbf\nProbable cause: You do not have permissions or filename is incorrect\n\nPress any key to exit", inShapeFile); Console.ReadLine(); return; } OracleConnection oracon = new OracleConnection(connectionstring); oracon.Open(); try { //Check if table exists bool tabExists = TabExists(oracon, spatial_table); //Get dbf info int recCount = ShapeLib.DBFGetRecordCount(hDbf); // get shape info double[] minXY = new double[4]; double[] maxXY = new double[4]; int nEntities = 0; ShapeLib.ShapeType shapeType = 0; ShapeLib.SHPGetInfo(hShp, ref nEntities, ref shapeType, minXY, maxXY); string sqlCreateTab = @"CREATE TABLE " + spatial_table.ToUpper() + "("; bool flag = true; for (int i = 0; i < nEntities; i++) { if (flag) { sqlCreateTab = sqlCreateTab + GetShapeColumnNames(ref hDbf); sqlCreateTab = sqlCreateTab + shape_col + "\tMDSYS.SDO_GEOMETRY\n)"; if (!tabExists) { //EXECUTE table creation sql ExecuteStatement(oracon, sqlCreateTab); } flag = false; } #region Deal With Geometry IntPtr pshpObj = ShapeLib.SHPReadObject(hShp, i); // Get the SHPObject associated with our IntPtr pshpObj // We create a new SHPObject in managed code, then use Marshal.PtrToStructure // to copy the unmanaged memory pointed to by pshpObj into our managed copy. ShapeLib.SHPObject shpObj = new ShapeLib.SHPObject(); Marshal.PtrToStructure(pshpObj, shpObj); //Number of parts int nParts = shpObj.nParts; //Part starts List int[] partStarts = new int[nParts]; //Coordinate arrays double[] xCoord = new double[shpObj.nVertices]; double[] yCoord = new double[shpObj.nVertices]; double[] zCoord = new double[shpObj.nVertices]; double[] MCoord = new double[shpObj.nVertices]; // Use Marshal.Copy to copy the memory pointed // to by shpObj.padfX and shpObj.padfX (each an IntPtr) to an actual array. Marshal.Copy(shpObj.padfX, xCoord, 0, shpObj.nVertices); Marshal.Copy(shpObj.padfY, yCoord, 0, shpObj.nVertices); if (shapeType == ShapeLib.ShapeType.MultiPointM || shapeType == ShapeLib.ShapeType.PointM || shapeType == ShapeLib.ShapeType.PolygonM || shapeType == ShapeLib.ShapeType.PolyLineM) { Marshal.Copy(shpObj.padfM, zCoord, 0, shpObj.nVertices); } if (shapeType == ShapeLib.ShapeType.MultiPointZ || shapeType == ShapeLib.ShapeType.PointZ || shapeType == ShapeLib.ShapeType.PolygonZ || shapeType == ShapeLib.ShapeType.PolyLineZ) { Marshal.Copy(shpObj.padfZ, zCoord, 0, shpObj.nVertices); } if (nParts > 0) { Marshal.Copy(shpObj.paPartStart, partStarts, 0, nParts); } string sqlInsertShape = " MDSYS.SDO_GEOMETRY("; string gType = GetGTYPE(shapeType, nParts); string elem_info = "NULL"; string sdo_point = "NULL"; if (shapeType == ShapeLib.ShapeType.Point || shapeType == ShapeLib.ShapeType.PointM || shapeType == ShapeLib.ShapeType.PointZ) { sdo_point = "MDSYS.SDO_POINT_TYPE(" + xCoord[0].ToString() + "," + yCoord[0].ToString(); if (shapeType == ShapeLib.ShapeType.PointZ) { sdo_point = sdo_point + "," + zCoord[0].ToString(); } else if (shapeType == ShapeLib.ShapeType.PointM) { sdo_point = sdo_point + "," + MCoord[0].ToString(); } else { sdo_point = sdo_point + ", NULL"; } sdo_point = sdo_point + ")"; } else { elem_info = GetElemInfoString(shapeType, nParts, partStarts, shpObj.nVertices); } string vert_String = GetVerticesString(shapeType, xCoord, yCoord, zCoord, MCoord); //Construct the geometry statement sqlInsertShape = sqlInsertShape + gType + "," + strSRID + "," + sdo_point + "," + elem_info + "," + vert_String + ")"; # endregion #region Deal with Attributes string[] attrs = InsAttrSQL(ref hDbf, i); string insStatement = "INSERT INTO " + spatial_table.ToUpper() + "\n" + "(" + attrs[0] + "," + shape_col + ")\n" + " VALUES (" + attrs[1] + "," + sqlInsertShape + ")"; //Do the insert ExecuteStatement(oracon, insStatement); #endregion } //Create user_sdo_geom_metadata and spatial index for a new table if (!tabExists) { string usgm = GetUSGMString(shapeType, spatial_table, shape_col, minXY, maxXY); ExecuteStatement(oracon, usgm); string spidx = GetSPIDXString(spatial_table, shape_col); ExecuteStatement(oracon, spidx); } // free resources ShapeLib.SHPClose(hShp); ShapeLib.DBFClose(hDbf); Console.Write("Done.\nPress any key to exit"); Console.ReadLine(); }
public static void CreateShapeFile(string[] args) { string pkValue = string.Empty; bool pkValIsString = false; bool isSdoPoint = false; if (args == null || args.Length < 5) { Console.Write("\nUsage: sdo2shp <username/password>@dbalias> <spatial_table_name> <PK_col> <shape_col> <shapefile> [\"optional_where_clause\"]\n\nPress any key to exit"); Console.ReadLine(); return; } System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string version = assembly.GetName().Version.ToString(); Console.Write("\nORA2SHP Oracle SDO to Shapefile Utility. Version: " + version + "\n"); Console.Write("====================================================================\n"); string connectionstring = Utils.ParseConnectionString(args[0].ToString()); string where_clause = string.Empty; try { where_clause = args[5].ToString().Trim('"'); } catch (Exception) { } if (where_clause != string.Empty) { if (!where_clause.ToUpper().StartsWith("WHERE")) { where_clause = " where " + where_clause; } } string outShpFile = args[4].ToString(); string tab_name = args[1].ToString(); string pk_column = args[2].ToString(); string sdo_column = args[3].ToString(); if (outShpFile.ToUpper().EndsWith(".SHP")) { outShpFile = outShpFile.Substring(0, outShpFile.Length - 4); } OracleConnection oracon = new OracleConnection(connectionstring); List <GeoInfo> lShpInfo = new List <GeoInfo>(); try { oracon.Open(); string selFirstShp = string.Empty; if (where_clause == string.Empty) { selFirstShp = "select " + args[2].ToString() + "," + args[3].ToString() + " from " + args[1] + " where rownum = 1"; } else { selFirstShp = "select " + pk_column + "," + sdo_column + " from " + tab_name + " " + where_clause + " and rownum = 1"; } try { lShpInfo = getGeomInfo(oracon, selFirstShp, sdo_column); if (lShpInfo.Count == 0) { Console.WriteLine("\nNo rows found it table {0}", args[1]); Console.ReadLine(); oracon.Close(); oracon.Dispose(); return; } } catch (Exception ex) { Console.WriteLine("\nORA2SHP ERROR:\n" + ex.Message + "\n" + ex.StackTrace); } finally { } //Check if its an SDO point geometry GeoInfo geomInfo = lShpInfo[0]; isSdoPoint = isSDOPointType(geomInfo); //Initialize shape type ShapeLib.ShapeType shpType = ShapeLib.ShapeType.Point; try { shpType = GetShapeType(geomInfo); } catch (Exception ex) { Console.Write(ex.Message); Console.ReadLine(); return; } IntPtr hShp = ShapeLib.SHPCreate(outShpFile, shpType); if (hShp.Equals(IntPtr.Zero)) { Console.WriteLine("\nCould not create {0}.shp\nProbable cause: You do not have permissions or file is in use by another process\n\nPress any key to exit", outShpFile); Console.ReadLine(); return; } string sqlselect = string.Empty; if (where_clause == string.Empty) { sqlselect = @"SELECT " + GetColumnNames(oracon, tab_name) + ", " + sdo_column + " from " + tab_name; } else { sqlselect = @"SELECT " + GetColumnNames(oracon, tab_name) + ", " + sdo_column + " from " + tab_name + " " + where_clause; } OracleCommand command1 = oracon.CreateCommand(); command1.CommandText = sqlselect; OracleDataReader dr = command1.ExecuteReader(); int iShape = 0; IntPtr hDbf = IntPtr.Zero; DataTable dt = new DataTable(); System.Collections.Hashtable ht = new System.Collections.Hashtable(); //#if (DEBUG==true) // Console.WriteLine("Before Loop Elapsed Time: " + (DateTime.Now - tstart).ToString()); tstart = DateTime.Now; //#endif #region create dbf // create dbase file hDbf = ShapeLib.DBFCreate(outShpFile); if (!hDbf.Equals(IntPtr.Zero)) { dt = dr.GetSchemaTable(); //Get table metadata dt.Columns.Add("dBaseName"); } int ordinal1 = 0; foreach (DataRow row in dt.Rows) { string name = row["ColumnName"].ToString().ToUpper(); if (name.Length > 10) //Truncate column name to 10 chars { name = name.Substring(0, 10); } int i = 0; while (ht.ContainsKey(name)) //Check if column name exists after truncation { string iVal = (i++).ToString(); if (name.Length + iVal.Length > 10) { name = name.Substring(0, 10 - iVal.Length) + iVal; } else { name = name + iVal; } } ht.Add(name, ordinal1++); row["dBaseName"] = name; string type = row["DataType"].ToString(); switch (type) { case "System.Int32": case "System.Int16": ShapeLib.DBFAddField(hDbf, name, ShapeLib.DBFFieldType.FTInteger, 16, 0); break; case "System.String": int len = Math.Min(255, int.Parse(row["ColumnSize"].ToString())); ShapeLib.DBFAddField(hDbf, name, ShapeLib.DBFFieldType.FTString, len, 0); if (name == args[1].ToString()) { pkValIsString = true; } break; case "System.Boolean": ShapeLib.DBFAddField(hDbf, name, ShapeLib.DBFFieldType.FTLogical, 5, 0); break; case "System.Double": case "System.Float": case "System.Decimal": int prec = int.Parse(row["NumericPrecision"].ToString()); int scale = int.Parse(row["NumericScale"].ToString()); ShapeLib.DBFAddField(hDbf, name, ShapeLib.DBFFieldType.FTDouble, prec, scale); break; case "System.DateTime": ShapeLib.DBFAddField(hDbf, name, ShapeLib.DBFFieldType.FTDate, 8, 0); break; default: ht.Remove(name); row["dBaseName"] = null; ordinal1--; break; } } #endregion create dbf ShapeCreator sc = new ShapeCreator(); IntPtr pShp = new IntPtr(); while (dr.Read()) { //Console.Write("Processing record ..." + iShape.ToString() +"."); pkValue = dr[args[2]].ToString(); OraShape shp = new OraShape(); ShapePartInfo shpInfo = new ShapePartInfo(); try { GeoInfo geoInfo = new GeoInfo(); geoInfo.Geo = (SdoGeometry)dr[sdo_column]; shp = sc.getOraShape(geoInfo, shpType, Convert.ToInt32(dr[pk_column])); } catch (Exception) { continue; } if (!isSdoPoint) { try { shpInfo = sc.getShapePartInfo(geomInfo); } catch (Exception) { continue; } shp.nParts = shpInfo.nParts; shp.PartType = null; shp.PartStarts = shpInfo.PartStarts; if (shp.MList == null || shp.MList.Length == 0) { if (shp.ZList == null || shp.ZList.Length == 0) { pShp = ShapeLib.SHPCreateObject(shpType, -1, shp.nParts, shp.PartStarts, null, shp.nVertices, shp.XList, shp.YList, null, null); } else { pShp = ShapeLib.SHPCreateObject(shpType, -1, shp.nParts, shp.PartStarts, null, shp.nVertices, shp.XList, shp.YList, shp.ZList, null); } } else { pShp = ShapeLib.SHPCreateObject(shpType, -1, shp.nParts, shp.PartStarts, null, shp.nVertices, shp.XList, shp.YList, null, shp.MList); } } else { shp = sc.CreatePointShape(geomInfo, shpType, pkValue); if (shpType == ShapeLib.ShapeType.PointM) { pShp = ShapeLib.SHPCreateObject(shpType, -1, 0, null, null, 1, shp.XList, shp.YList, null, shp.MList); } else if (shpType == ShapeLib.ShapeType.PointZ) { pShp = ShapeLib.SHPCreateObject(shpType, -1, 0, null, null, 1, shp.XList, shp.YList, shp.ZList, null); } else { pShp = ShapeLib.SHPCreateObject(shpType, -1, 0, null, null, 1, shp.XList, shp.YList, null, null); } } try //In case of invalid shapes { ShapeLib.SHPWriteObject(hShp, -1, pShp); } catch (Exception) { Console.WriteLine("Shape with " + args[2].ToString().ToUpper() + "= " + pkValue + " is invalid. Number of vertices: " + shp.nVertices.ToString() + " Number of parts: " + shp.nParts.ToString()); continue; } ShapeLib.SHPDestroyObject(pShp); foreach (DataRow row in dt.Rows) { if (row["dBaseName"] == null || row["dBaseName"].ToString() == string.Empty) { continue; } int ordinal = (int)ht[row["dBaseName"].ToString()]; string fieldName = row["ColumnName"].ToString(); if (dr[fieldName] is DBNull) { continue; } switch (row["DataType"].ToString()) { case "System.Int32": case "System.Int16": ShapeLib.DBFWriteIntegerAttribute(hDbf, iShape, ordinal, int.Parse(dr[fieldName].ToString())); break; case "System.String": ShapeLib.DBFWriteStringAttribute(hDbf, iShape, ordinal, dr[fieldName].ToString()); break; case "System.Boolean": ShapeLib.DBFWriteLogicalAttribute(hDbf, iShape, ordinal, bool.Parse(dr[fieldName].ToString())); break; case "System.Double": case "System.Float": case "System.Decimal": ShapeLib.DBFWriteDoubleAttribute(hDbf, iShape, ordinal, double.Parse(dr[fieldName].ToString())); break; case "System.DateTime": DateTime date = DateTime.Parse(dr[fieldName].ToString()); ShapeLib.DBFWriteDateAttribute(hDbf, iShape, ordinal, date); break; } } iShape++; //dr.NextResult(); } Console.WriteLine("Converted " + iShape.ToString() + " shapes in: " + (DateTime.Now - tstart).ToString()); // free resources ShapeLib.SHPClose(hShp); ShapeLib.DBFClose(hDbf); //Create projection file if needed CreatePrjFile(oracon, args[1].ToString(), args[3].ToString(), outShpFile); //Console.Write("Done.\n"); Console.Write("\nCreated shapefile " + args[4].ToString() + " with " + iShape.ToString() + " records.\nTotal Elapsed Time: " + (DateTime.Now - tProgramstart).ToString() + "\nPress any key to exit."); Console.ReadLine(); } catch (Exception ex) { Console.Write("ERROR: " + ex.Message + "\nPress any key to exit"); Utils.WriteErrLog(ex); Console.ReadLine(); } finally { //Close and free connection oracon.Close(); oracon.Dispose(); } }
/// <summary> /// Creates the database file that contains meta data about the shapes. /// </summary> /// <param name="shapetype"></param> /// <param name="SHPFile"></param> private void WriteDBF(ShapeLib.ShapeType shapetype, string SHPFile, bool convertTags) { string filename; int shapes = 0; List <MetaData> elementData; List <string> fields = new List <string>(); switch (shapetype) { case ShapeLib.ShapeType.Polygon: filename = SHPFile + "-polygons"; shapes = areas; elementData = polygonsData; break; case ShapeLib.ShapeType.PolyLine: filename = SHPFile + "-lines"; shapes = ways; elementData = linesData; break; case ShapeLib.ShapeType.Point: filename = SHPFile + "-points"; shapes = points; elementData = pointsData; break; default: return; } IntPtr hDbf = ShapeLib.DBFCreate(filename); if (hDbf.Equals(IntPtr.Zero)) { Console.WriteLine("Error: Unable to create {0}.dbf!", filename); return; } // add some fields. Fields have to be initialized before data is added int iRet = ShapeLib.DBFAddField(hDbf, "shapeID", ShapeLib.DBFFieldType.FTInteger, 4, 0); iRet = ShapeLib.DBFAddField(hDbf, "shapeName", ShapeLib.DBFFieldType.FTString, 50, 0); // if tags have to be converted, collect the names of all tags if (convertTags) { for (int iShape = 0; iShape < shapes; iShape++) { foreach (KeyValuePair <string, string> entry in elementData[iShape].Tags) { // Make sure that fields are only added once if (!fields.Contains(entry.Key)) { fields.Add(entry.Key); } } } // create fields in the DB for all tags foreach (string field in fields) { iRet = ShapeLib.DBFAddField(hDbf, field, ShapeLib.DBFFieldType.FTString, 128, 0); } } // populate for (int iShape = 0; iShape < shapes; iShape++) { iRet = (ShapeLib.DBFWriteIntegerAttribute(hDbf, iShape, 0, iShape)); iRet = (ShapeLib.DBFWriteStringAttribute(hDbf, iShape, 1, elementData[iShape].Name)); // If tags should be converted, write their values to the appropriate fields if (convertTags) { foreach (KeyValuePair <string, string> entry in elementData[iShape].Tags) { // Cut the entry after 128 characters int stringLength = entry.Value.Length; if (stringLength > 127) { stringLength = 127; } iRet = ShapeLib.DBFWriteStringAttribute(hDbf, iShape, fields.IndexOf(entry.Key) + 2, entry.Value.Substring(0, stringLength)); } } } ShapeLib.DBFClose(hDbf); }
public string SaveToShapefile(ConversionOptions options) { ShapeLib.ShapeType shapetype; double[] x, y; IntPtr hShpPoly = IntPtr.Zero, hShpLine = IntPtr.Zero, hShpPoint = IntPtr.Zero; linesData = new List <MetaData>(); polygonsData = new List <MetaData>(); pointsData = new List <MetaData>(); if (options.Lines) { // create a new PolyLines shapefile hShpLine = ShapeLib.SHPCreate(options.Filename + "-lines", ShapeLib.ShapeType.PolyLine); if (hShpLine.Equals(IntPtr.Zero)) { return("Cannot create lines file!"); } } if (options.Polygons) { // create a new Polygons shapefile hShpPoly = ShapeLib.SHPCreate(options.Filename + "-polygons", ShapeLib.ShapeType.Polygon); if (hShpPoly.Equals(IntPtr.Zero)) { return("Cannot create polygons file!"); } } if (options.Points) { // create a new Points shapefile hShpPoint = ShapeLib.SHPCreate(options.Filename + "-points", ShapeLib.ShapeType.Point); if (hShpPoint.Equals(IntPtr.Zero)) { return("Cannot create points file!"); } } /*iterate through OSM ways*/ foreach (way strada in infile.wayCollection) { /*check if the way is closed, set shape type accordingly*/ if (strada.ndCollection[0].reff == strada.ndCollection[strada.ndCollection.Count - 1].reff) { shapetype = ShapeLib.ShapeType.Polygon; } else { shapetype = ShapeLib.ShapeType.PolyLine; } x = new double[strada.ndCollection.Count]; y = new double[strada.ndCollection.Count]; /*iterate through all the nodes in the way, set x and y coords*/ int i = 0; foreach (nd nod in strada.ndCollection) { node nodcomplet = infile.nodeCollection.GetByRef(nod.reff); /*TO DO: Regional settings - to be checked - should be ok now*/ x[i] = double.Parse(nodcomplet.lon, CultureInfo.InvariantCulture); y[i] = double.Parse(nodcomplet.lat, CultureInfo.InvariantCulture); nodcomplet.InWay = true; i++; } /*finding way name*/ MetaData elementData = new MetaData(); elementData = extractMetaData(strada); foreach (tag t in strada.tagCollection) { /*just to make sure that all the streets are * put in the polylines file*/ if ((t.k == "highway") && (shapetype == ShapeLib.ShapeType.Polygon)) { shapetype = ShapeLib.ShapeType.PolyLine; areas--; ways++; } /*exception for circular ways: junction:roundabout * should be marked as polyline, not as polygon*/ if ((t.k == "junction") && (t.v == "roundabout") && (shapetype == ShapeLib.ShapeType.Polygon)) { shapetype = ShapeLib.ShapeType.PolyLine; areas--; ways++; } } /*create object, write it to file and destroy it*/ IntPtr pshpObj = ShapeLib.SHPCreateSimpleObject(shapetype, strada.ndCollection.Count, x, y, new double[strada.ndCollection.Count]); int iRet; if ((shapetype == ShapeLib.ShapeType.PolyLine) && options.Lines) { iRet = ShapeLib.SHPWriteObject(hShpLine, -1, pshpObj); /*add shape meta data to correct list*/ linesData.Add(elementData); } else if ((shapetype == ShapeLib.ShapeType.Polygon) && (options.Polygons)) { iRet = ShapeLib.SHPWriteObject(hShpPoly, -1, pshpObj); /*add shape meta data to correct list*/ polygonsData.Add(elementData); } ShapeLib.SHPDestroyObject(pshpObj); } if (options.Points) { /*write the nodes that are not part of any way*/ foreach (node nod in infile.nodeCollection) { if (!nod.InWay) { x = new double[1]; y = new double[1]; /*TO DO: Regional settings - to be checked*/ x[0] = double.Parse(nod.lon, CultureInfo.InvariantCulture); y[0] = double.Parse(nod.lat, CultureInfo.InvariantCulture); /*create object, write it to file and destroy it*/ IntPtr pshpObj = ShapeLib.SHPCreateSimpleObject(ShapeLib.ShapeType.Point, 1, x, y, new double[1]); int iRet = ShapeLib.SHPWriteObject(hShpPoint, -1, pshpObj); /*finding node meta data*/ MetaData elementData = extractMetaData(nod); pointsData.Add(elementData); ShapeLib.SHPDestroyObject(pshpObj); } } } // free resources and write dbf files if (options.Polygons) { ShapeLib.SHPClose(hShpPoly); WriteDBF(ShapeLib.ShapeType.Polygon, options.Filename, options.ConvertTags); writeProjectionFile(options.Filename + "-polygons", options.Projection); } if (options.Lines) { ShapeLib.SHPClose(hShpLine); WriteDBF(ShapeLib.ShapeType.PolyLine, options.Filename, options.ConvertTags); writeProjectionFile(options.Filename + "-lines", options.Projection); } if (options.Points) { ShapeLib.SHPClose(hShpPoint); WriteDBF(ShapeLib.ShapeType.Point, options.Filename, options.ConvertTags); writeProjectionFile(options.Filename + "-points", options.Projection); } return("Completed!"); }
private void method_3(ICoFeature icoFeature_0, int int_0) { try { int num2; DateTime time; if (this.coLayerMapper_0 == null) { goto Label_016A; } int num = 0; Label_0011: if (num >= this.coLayerMapper_0.FieldRelation.Count) { return; } CoFieldMapper mapper = this.coLayerMapper_0.FieldRelation[num]; ICoField destField = mapper.DestField; ICoField sourceField = mapper.SourceField; object obj2 = ""; try { obj2 = icoFeature_0.GetValue(sourceField); } catch { obj2 = ""; } goto Label_010A; Label_006B: ShapeLib.DBFWriteStringAttribute(this.intptr_1, int_0, num2, obj2.ToString().ToUpper()); goto Label_0101; Label_0088: ShapeLib.DBFWriteIntegerAttribute(this.intptr_1, int_0, num2, this.method_7(obj2.ToString())); goto Label_0101; Label_00A6: ShapeLib.DBFWriteDoubleAttribute(this.intptr_1, int_0, num2, this.method_6(obj2.ToString())); goto Label_0101; Label_00C4: ShapeLib.DBFWriteLogicalAttribute(this.intptr_1, int_0, num2, this.method_5(obj2.ToString())); goto Label_0101; Label_00E2: time = DateTime.Parse(obj2.ToString()); ShapeLib.DBFWriteDateAttribute(this.intptr_1, int_0, num2, time); Label_0101: num++; goto Label_0011; Label_010A: num2 = ShapeLib.DBFGetFieldIndex(this.intptr_1, destField.Name); int num3 = 0; int num4 = 0; StringBuilder builder = new StringBuilder(destField.Name); switch (ShapeLib.DBFGetFieldInfo(this.intptr_1, num2, builder, ref num3, ref num4)) { case ShapeLib.DBFFieldType.FTString: goto Label_006B; case ShapeLib.DBFFieldType.FTInteger: goto Label_0088; case ShapeLib.DBFFieldType.FTDouble: goto Label_00A6; case ShapeLib.DBFFieldType.FTLogical: goto Label_00C4; case ShapeLib.DBFFieldType.FTInvalid: goto Label_0101; case ShapeLib.DBFFieldType.FTDate: goto Label_00E2; default: goto Label_0101; } Label_016A: using (List <ICoField> .Enumerator enumerator = icoFeature_0.Layer.Fields.GetEnumerator()) { Label_017D: if (!enumerator.MoveNext()) { return; } ICoField current = enumerator.Current; obj2 = ""; try { obj2 = icoFeature_0.GetValue(current); } catch { obj2 = ""; } goto Label_0256; Label_01B5: ShapeLib.DBFWriteStringAttribute(this.intptr_1, int_0, num2, obj2.ToString().ToUpper()); goto Label_017D; Label_01D2: ShapeLib.DBFWriteIntegerAttribute(this.intptr_1, int_0, num2, this.method_7(obj2.ToString())); goto Label_017D; Label_01F0: ShapeLib.DBFWriteDoubleAttribute(this.intptr_1, int_0, num2, this.method_6(obj2.ToString())); goto Label_017D; Label_0211: ShapeLib.DBFWriteLogicalAttribute(this.intptr_1, int_0, num2, this.method_5(obj2.ToString())); goto Label_017D; Label_0232: time = DateTime.Parse(obj2.ToString()); ShapeLib.DBFWriteDateAttribute(this.intptr_1, int_0, num2, time); goto Label_017D; Label_0256: num2 = ShapeLib.DBFGetFieldIndex(this.intptr_1, current.Name); num3 = 0; num4 = 0; builder = new StringBuilder(current.Name); switch (ShapeLib.DBFGetFieldInfo(this.intptr_1, num2, builder, ref num3, ref num4)) { case ShapeLib.DBFFieldType.FTString: goto Label_01B5; case ShapeLib.DBFFieldType.FTInteger: goto Label_01D2; case ShapeLib.DBFFieldType.FTDouble: goto Label_01F0; case ShapeLib.DBFFieldType.FTLogical: goto Label_0211; case ShapeLib.DBFFieldType.FTDate: goto Label_0232; } goto Label_017D; } } catch { } }
private void method_2(ICoFeature icoFeature_0) { try { int[] numArray; ShapeLib.PartType[] typeArray; int num5; int count = 0; int num2 = 0; int num3 = 0; int index = 0; switch (icoFeature_0.Type) { case CoFeatureType.Point: foreach (ICoPoint point in (icoFeature_0 as ICoPointFeature).Point) { this.double_0 = new double[1]; this.double_1 = new double[1]; this.double_0[0] = point.X; this.double_1[0] = point.Y; this.intptr_2 = ShapeLib.SHPCreateObject(this.shapeType_0, -1, 0, null, null, 1, this.double_0, this.double_1, null, null); num2 = ShapeLib.SHPWriteObject(this.intptr_0, -1, this.intptr_2); ShapeLib.SHPDestroyObject(this.intptr_2); this.method_3(icoFeature_0, num2); } return; case CoFeatureType.Line: case CoFeatureType.Annotation: return; case CoFeatureType.Polygon: { ICoPolygonFeature feature2 = icoFeature_0 as ICoPolygonFeature; if (feature2 != null) { count = feature2.Points.Count; numArray = new int[count]; typeArray = new ShapeLib.PartType[count]; typeArray[0] = ShapeLib.PartType.Ring; numArray[0] = 0; num3 = feature2.Points[0].Count; for (num5 = 1; num5 < count; num5++) { numArray[num5] = num3; typeArray[num5] = ShapeLib.PartType.Ring; num3 += feature2.Points[num5].Count; } this.double_0 = new double[num3]; this.double_1 = new double[num3]; int num6 = 0; foreach (CoPointCollection points in feature2.Points) { int num8; double num7 = this.method_8(points); if (num6 == 0) { if (num7 > 0.0) { foreach (ICoPoint point2 in points) { this.double_0[index] = point2.X; this.double_1[index] = point2.Y; index++; } } else { num8 = points.Count - 1; while (num8 >= 0) { this.double_0[index] = points[num8].X; this.double_1[index] = points[num8].Y; index++; num8--; } } } else if (num7 > 0.0) { for (num8 = points.Count - 1; num8 >= 0; num8--) { this.double_0[index] = points[num8].X; this.double_1[index] = points[num8].Y; index++; } } else { foreach (ICoPoint point2 in points) { this.double_0[index] = point2.X; this.double_1[index] = point2.Y; index++; } } num6++; } this.intptr_2 = ShapeLib.SHPCreateObject(this.shapeType_0, -1, count, numArray, typeArray, num3, this.double_0, this.double_1, null, null); try { num2 = ShapeLib.SHPWriteObject(this.intptr_0, -1, this.intptr_2); ShapeLib.SHPDestroyObject(this.intptr_2); this.method_3(icoFeature_0, num2); } catch { } } return; } case CoFeatureType.Polyline: break; default: return; } ICoPolylineFeature feature = icoFeature_0 as ICoPolylineFeature; count = feature.Points.Count; numArray = new int[count]; typeArray = new ShapeLib.PartType[count]; typeArray[0] = ShapeLib.PartType.Ring; numArray[0] = 0; num3 = feature.Points[0].Count; for (num5 = 1; num5 < count; num5++) { numArray[num5] = num3; typeArray[num5] = ShapeLib.PartType.Ring; num3 += feature.Points[num5].Count; } this.double_0 = new double[num3]; this.double_1 = new double[num3]; foreach (CoPointCollection points in feature.Points) { foreach (ICoPoint point2 in points) { this.double_0[index] = point2.X; this.double_1[index] = point2.Y; index++; } } this.intptr_2 = ShapeLib.SHPCreateObject(this.shapeType_0, -1, count, numArray, typeArray, num3, this.double_0, this.double_1, null, null); num2 = ShapeLib.SHPWriteObject(this.intptr_0, -1, this.intptr_2); ShapeLib.SHPDestroyObject(this.intptr_2); this.method_3(icoFeature_0, num2); } finally { } }
public List <InputFields> GetFieldValues(List <R_FieldInf> fieldInfs, FieldMapping vitalFields, string path) { List <InputFields> result = new List <InputFields>(); string dbfpath = path; IntPtr hDbf = ShapeLib.DBFOpen(dbfpath, "rb+"); int FieldCount = fieldInfs.Count(); int PointCount = ShapeLib.DBFGetRecordCount(hDbf); for (int pi = 0; pi < PointCount; pi++) { InputFields point = new InputFields(); string other = "{"; for (int i = 0; i < FieldCount; i++) { if (fieldInfs[i].FieldName == vitalFields.ID) { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); point.ID = FieldValue; } else { if (fieldInfs[i].FieldName == vitalFields.Name) { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); point.Name = FieldValue; } else { if (fieldInfs[i].FieldName == vitalFields.Address) { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); point.Addresss = FieldValue; } else { if (fieldInfs[i].FieldName == vitalFields.Xcoordinate) { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); point.X = FieldValue; } else { if (fieldInfs[i].FieldName == vitalFields.Ycoordinate) { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); point.Y = FieldValue; } else { if (fieldInfs[i].FieldType == "text") { IntPtr FieldvaluePtr = ShapeLib.DBFReadStringAttribute(hDbf, pi, i); string FieldValue = Marshal.PtrToStringAnsi(FieldvaluePtr, 255).Replace("\0", ""); other += "\"" + fieldInfs[i].FieldName + "\":\"" + FieldValue + "\","; } else { if (fieldInfs[i].FieldType == "integer") { int FieldValue = ShapeLib.DBFReadIntegerAttribute(hDbf, pi, i); other += "\"" + fieldInfs[i].FieldName + "\":" + FieldValue + ","; } else { double FieldValue = ShapeLib.DBFReadDoubleAttribute(hDbf, pi, i); other += "\"" + fieldInfs[i].FieldName + "\":" + FieldValue + ","; } } } } } } } } other = other.Substring(0, other.Length - 1) + "}"; point.Other = other; result.Add(point); } ShapeLib.DBFClose(hDbf); return(result); }
public bool CreatePointFile(string path, string[] pointJson) { if (pointJson == null || pointJson.Length == 0) { return(false); } if (System.IO.Directory.Exists(path) == false) { Directory.CreateDirectory(path); } ShapeLib.ShapeType shpType = ShapeLib.ShapeType.Point; hShpPoint = ShapeLib.SHPCreate(path + "\\poi", shpType); DbfFile odbf = CreateAttr(path, pointJson); DbfRecord orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true }; //逐个点录入属性信息及提取坐标 for (int i = 0; i < pointJson.Length; i++) { //取出JSON中的属性信息 JObject obj = (JObject)JsonConvert.DeserializeObject(pointJson[i]); string attrs = obj["attr"].ToString(); string attrtypes = obj["attrtype"].ToString(); string geometry = obj["geometry"].ToString(); //将该点属性信息记录为List<PointInf> List <PointInf> pointinf = new List <PointInf>(); List <string> values = new List <string>(); List <string> types = new List <string>(); JToken attrname = (JToken)JsonConvert.DeserializeObject(attrs); int listLenhth = 0; foreach (JProperty jp in attrname) { values.Add(jp.Value.ToString()); listLenhth++; } JToken attrtype = (JToken)JsonConvert.DeserializeObject(attrtypes); foreach (JProperty jp in attrtype) { types.Add(jp.Value.ToString()); } for (int a = 0; a < listLenhth - 1; a++) { pointinf.Add(new PointInf(values[a], types[a])); } try { //生成坐标点 List <Point> geo = CreatePointFilePointList(geometry); double[] xCoord = new double[1]; double[] yCoord = new double[1]; xCoord[0] = geo[0].X; yCoord[0] = geo[0].Y; IntPtr pShp = ShapeLib.SHPCreateSimpleObject(shpType, 1, xCoord, yCoord, null); ShapeLib.SHPWriteObject(hShpPoint, -1, pShp); ShapeLib.SHPDestroyObject(pShp); //录入属性信息 for (int a = 0; a < listLenhth - 1; a++) { if (pointinf[a].Type == "text") { orec[a] = pointinf[a].Value; } else { string c = pointinf[a].Value.ToString(); orec[a] = c; } } odbf.Write(orec, true); } catch { string c = pointinf[0].Value.ToString(); } } //关闭 odbf.Close(); if (hShpPoint != IntPtr.Zero) { ShapeLib.SHPClose(hShpPoint); } return(true); }
public void Add(ShapeLib.Shape shape) { _shapes.Add(shape); }