// Close files and show an error message private void CloseMessage(string message) { if (_outSF != null) { _outSF.Close(); } if (_inSF1 != null) { _inSF1.Close(); } if (_inSF2 != null) { _inSF2.Close(); } MapWinUtility.Logger.Message(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK); }
/// <summary> /// Update projection column for a specified layers /// </summary> private void UpdateProjection(string filename, DataGridView dgv, int rowIndex) { if (this.ControlType == CustomType.Projection) { string name = ""; MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); if (sf.Open(filename, null)) { name = sf.GeoProjection.Name; ProjectionDatabase db = m_mapWin.ProjectionDatabase as ProjectionDatabase; if (db != null) { CoordinateSystem cs = db.GetCoordinateSystem(sf.GeoProjection, ProjectionSearchType.UseDialects); if (cs != null) { name = cs.Name; } } dgv[this.CustomColumnIndex, rowIndex].Value = name; sf.Close(); } sf = null; if (name == "") { dgv[this.CustomColumnIndex, rowIndex].Value = "Undefined"; } } }
/// <summary> /// Actually engages the append shapes process /// </summary> public void DoMergeShapefiles() { MapWinUtility.Logger.Dbg("DoMergeShapefiles()"); string errorMessage; _inSF1 = new MapWinGIS.Shapefile(); _inSF2 = new MapWinGIS.Shapefile(); _outSF = new MapWinGIS.Shapefile(); GetFilenames(); if (OpenFiles(out errorMessage) == false) { MapWinUtility.Logger.Message(errorMessage, "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK); return; } if (_outSF.StartEditingShapes(true, null) == false) { CloseMessage(_outSF.get_ErrorMsg(_outSF.LastErrorCode)); return; } // Determine a list of unique fields to add to the output shapefile. if (CombineFields(out errorMessage) == false) { CloseMessage(errorMessage); return; } if (AddShapes(_inSF1, out errorMessage) == false) { CloseMessage(errorMessage); return; } if (AddShapes(_inSF2, out errorMessage) == false) { CloseMessage(errorMessage); return; } _inSF2.Close(); _inSF1.Close(); if (_outSF.StopEditingShapes(true, true, null) == false) { MapWinUtility.Logger.Message(_outSF.get_ErrorMsg(_outSF.LastErrorCode), "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK); return; } _outSF.Close(); MapWinUtility.Logger.Message("Finished Merging Shapes", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); }
/// <summary> /// Assignes selected projection and displays results /// </summary> public bool Assign(string filename, MapWinGIS.GeoProjection proj) { MapWinGIS.GeoProjection projWGS84 = new MapWinGIS.GeoProjection(); if (!projWGS84.ImportFromEPSG(4326)) { MessageBox.Show("Failed to initialize WGS84 coordinate system.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } bool sameProj = proj.get_IsSame(projWGS84); int count = 0; bool success = false; int rowIndex = dgv.Rows.Add(); m_shapefile = new MapWinGIS.Shapefile(); if (m_shapefile.Open(filename, m_mapWin.Layers as MapWinGIS.ICallback)) { this.Text = "Assigning projection: " + System.IO.Path.GetFileName(filename); this.lblProjection.Text = "Projection: " + proj.Name; // it will be faster to assing new instance of class // as ImportFromEPSG() is slow according to GDAL documentation m_shapefile.GeoProjection = proj; if (!sameProj) { // we can't show preview on map without reprojection if ((m_shapefile.StartEditingShapes(true, null))) { if (m_shapefile.ReprojectInPlace(projWGS84, ref count)) { success = true; } } } else { success = true; } } if (success) { this.AddShapefile(m_shapefile); return(true); } else { // no success in reprojection m_shapefile.Close(); return(false); } }
private static void CachePointsBrute(string InPointsPath, int InValueFieldIndex, out List <InterpolationPoint> PointsCache, out string Projection, out string ProjectionUnits, out MapWinGIS.Extents PointsExtents, MapWinGIS.ICallback callback) { int newperc = 0, oldperc = 0; MapWinGIS.Shapefile points = new MapWinGIS.Shapefile(); points.Open(InPointsPath, null); PointsExtents = points.Extents; Projection = points.Projection; if (Projection != null) { ProjectionUnits = Projection.Substring(Projection.IndexOf("units=") + 6); ProjectionUnits = ProjectionUnits.Substring(0, ProjectionUnits.IndexOf("+")).Trim(); } else { double tmpX = points.Extents.xMax; string tmpstr = Math.Floor(tmpX).ToString(); if (tmpstr.Length > 4) { ProjectionUnits = ""; } else { ProjectionUnits = "lat/long"; } } PointsCache = new List <InterpolationPoint>(); InterpolationPoint pt; MapWinGIS.Point currpt; int ns = points.NumShapes; for (int i = 0; i < ns; i++) { newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(ns)) * 100); if ((newperc > oldperc)) { if (callback != null) { callback.Progress("Status", newperc, "IDW Caching " + i.ToString()); } oldperc = newperc; } currpt = points.get_Shape(i).get_Point(0); pt = new InterpolationPoint(currpt.x, currpt.y, double.Parse(points.get_CellValue(InValueFieldIndex, i).ToString()), 0); PointsCache.Add(pt); } points.Close(); }
// calculate a default cellsize (grid-max.500 rows or columns) // using the input shapefile extent private double calcDefaultCellsize() { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); double result = 0F; if (sf.Open(m_ShpFileName, null)) { double sfX = sf.Extents.xMax - sf.Extents.xMin; double sfY = sf.Extents.yMax - sf.Extents.yMin; double minExt = Math.Max(sfX, sfY); result = Math.Floor(minExt / 250F); } sf.Close(); return(result); }
public void UndoLastChange() { // MapWindow doesn't lock the shapefile so long as we're // not currently editing; so the file can be overwritten // and a redraw triggered. if (UndoStack.Count == 0) { return; } MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)MapWin.Layers[MapWin.Layers.CurrentLayer].GetObject(); if (sf.EditingShapes || sf.EditingTable) { sf.StopEditingShapes(false, true, null); } // Lock the map and legend -- we're about to do evil things to the underlying map MapWin.View.LockMap(); MapWin.View.LockLegend(); string tmp = (string)UndoStack.Pop(); string xtmp = System.IO.Path.ChangeExtension(tmp, ".shx"); string dtmp = System.IO.Path.ChangeExtension(tmp, ".dbf"); string fail = MapWin.Layers[MapWin.Layers.CurrentLayer].FileName; string xfail = System.IO.Path.ChangeExtension(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, ".shx"); string dfail = System.IO.Path.ChangeExtension(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, ".dbf"); sf.Close(); System.IO.File.Copy(tmp, fail, true); System.IO.File.Copy(xtmp, xfail, true); System.IO.File.Copy(dtmp, dfail, true); System.IO.File.Delete(tmp); System.IO.File.Delete(xtmp); System.IO.File.Delete(dtmp); sf.Open(fail, null); // Unlock and refresh: MapWin.View.UnlockMap(); MapWin.View.UnlockLegend(); UpdateView(); UpdateUndoButtons(); }
/// <summary> /// Inverse Distance Weighting Interpolation /// </summary> /// <param name="InPointsPath">Input point shapefile path to interpolate</param> /// <param name="InValueFieldIndex">Input field index where interpolation value is stored</param> /// <param name="OutGridPath">Output grid path where interpolation is stored</param> public static void IDW(string InPointsPath, int InValueFieldIndex, string OutGridPath) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); sf.Open(InPointsPath, null); double height = Math.Abs(sf.Extents.yMax - sf.Extents.yMin); double width = Math.Abs(sf.Extents.xMax - sf.Extents.xMin); double defaultCellSize = -1; if (height <= width) { defaultCellSize = height / 250; } else { defaultCellSize = width / 250; } sf.Close(); IDW(InPointsPath, InValueFieldIndex, OutGridPath, defaultCellSize); }
public int GetNumCellsByDEMAndMask(MapWinGIS.GridHeader head, string strMask) { int numCells = 0, maskCells = 0; numCells = head.NumberCols * head.NumberRows; MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); sf.Open(strMask); for (int iShape = 0; iShape < sf.NumShapes; iShape++) { MapWinGIS.Shape tempShape = sf.Shape[iShape]; int temp = Convert.ToInt32(MapWinGeoProc.Utils.Area(ref tempShape) / (head.dX * head.dY)); maskCells = maskCells + temp; } sf.Close(); if (numCells > maskCells) { numCells = maskCells; } return(numCells); }
private void populateFields(string shpFileName) { cmbFields.Items.Clear(); MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWinGIS.Field curField; if (sf.Open(shpFileName, sf.GlobalCallback)) { for (int i = 0; i < sf.NumFields; ++i) { curField = sf.get_Field(i); if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD || curField.Type == MapWinGIS.FieldType.INTEGER_FIELD) { cmbFields.Items.Add(curField.Name); } } sf.Close(); } if (cmbFields.Items.Count > 0) { cmbFields.SelectedIndex = 0; } }
/// <summary> /// 关闭图层. 设置未定义的图层类型 /// </summary> public void Close() { m_error = LayerSourceError.None; switch (this.Type) { case LayerSourceType.Shapefile: m_shapefile.Close(); m_shapefile = null; break; case LayerSourceType.Image: m_image.Close(); m_image = null; break; case LayerSourceType.Grid: m_grid.Close(); m_grid = null; break; default: break; } }
/// <summary> /// 打开指定数据源的图层 /// </summary> /// <param name="filename">文件名</param> /// <param name="callback"></param> /// <returns></returns> public bool Open(string filename, MapWinGIS.ICallback callback) { this.Close(); if (filename.ToLower().EndsWith(".shp")) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); if (sf.Open(filename, callback)) { // 检查dbf是否存在 bool error = false; if (!File.Exists(Path.ChangeExtension(sf.Filename, ".dbf"))) { m_error = LayerSourceError.DbfIsMissing; error = true; } // 检查DBF记录数相匹配的形状的数量。 MapWinGIS.Table table = new MapWinGIS.Table(); table.Open(Path.ChangeExtension(sf.Filename, ".dbf"), null); if (sf.NumShapes != table.NumRows) { m_error = LayerSourceError.DbfRecordCountMismatch; error = true; } table.Close(); if (error) { sf.Close(); } else { m_shapefile = sf; } return(!error); } else { m_error = LayerSourceError.OcxBased; m_ErrorString = sf.get_ErrorMsg(sf.LastErrorCode); } } else { bool asGrid = true; if (filename.ToLower().EndsWith(".tif")) { asGrid = false; } // TODO: 可能更聪明的选择是在grid/image中使用应用程序设置 if (asGrid) { MapWinGIS.Grid grid = new MapWinGIS.Grid(); if (grid.Open(filename, MapWinGIS.GridDataType.UnknownDataType, false, MapWinGIS.GridFileType.UseExtension, callback)) { m_grid = grid; return(true); } } // 尝试image MapWinGIS.Image image = new MapWinGIS.Image(); if (image.Open(filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, callback)) { m_image = image; return(true); } else { m_error = LayerSourceError.OcxBased; m_ErrorString = image.get_ErrorMsg(image.LastErrorCode); } } return(false); }
// displays the grid extent! private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWindow.Interfaces.Layer curLayer; MapWinGIS.Grid grd = new MapWinGIS.Grid(); MapWinGIS.Extents extents; double cellSize = m_DefaultCellSize; //get the cell size to value from textbox Utils.string2double(txtCellSize.Text, out cellSize); //handle the "as specified below" option if (cmbExtent.Text == msgSpecifiedBelow) { txtMinX.Enabled = true; txtMinY.Enabled = true; txtMaxX.Enabled = true; txtMaxY.Enabled = true; return; } else { txtMinX.Enabled = false; txtMinY.Enabled = false; txtMaxX.Enabled = false; txtMaxY.Enabled = false; } //handle the case when shapefile loaded from disk and selected if (cmbExtent.Text == msgSameAs + m_ShortName) { if (sf.Open(m_ShpFileName, null)) { extents = calcShapefileExtent(sf); UpdateExtentBox(extents); } sf.Close(); } for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i) { //an existing layer is used to determine the extent curLayer = m_MapWin.Layers[i]; if (curLayer != null) { if (msgSameAs + curLayer.Name == cmbExtent.Text) { switch (curLayer.LayerType) { //same extention as an existing grid case MapWindow.Interfaces.eLayerType.Grid: grd = curLayer.GetGridObject; UpdateExtentBox(grd.Header); break; //same extention as an existing shapefile case MapWindow.Interfaces.eLayerType.LineShapefile: case MapWindow.Interfaces.eLayerType.PolygonShapefile: case MapWindow.Interfaces.eLayerType.PointShapefile: sf = (MapWinGIS.Shapefile)curLayer.GetObject(); extents = calcShapefileExtent(sf); UpdateExtentBox(extents); break; default: break; } } } } }
// displays the grid extent! private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWindow.Interfaces.Layer curLayer; MapWinGIS.Grid grd = new MapWinGIS.Grid(); MapWinGIS.Extents extents; double cellSize = m_DefaultCellSize; //get the cell size to value from textbox Utils.string2double(txtCellSize.Text, out cellSize); //handle the "as specified below" option if (cmbExtent.Text == msgSpecifiedBelow) { txtMinX.Enabled = true; txtMinY.Enabled = true; txtMaxX.Enabled = true; txtMaxY.Enabled = true; return; } else { txtMinX.Enabled = false; txtMinY.Enabled = false; txtMaxX.Enabled = false; txtMaxY.Enabled = false; } //handle the case when shapefile loaded from disk and selected if (cmbExtent.Text == msgSameAs + m_ShortName) { if (sf.Open(m_ShpFileName,null)) { extents = calcShapefileExtent(sf); UpdateExtentBox(extents); } sf.Close(); } for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i) { //an existing layer is used to determine the extent curLayer = m_MapWin.Layers[i]; if (curLayer != null) { if (msgSameAs + curLayer.Name == cmbExtent.Text) { switch (curLayer.LayerType) { //same extention as an existing grid case MapWindow.Interfaces.eLayerType.Grid: grd = curLayer.GetGridObject; UpdateExtentBox(grd.Header); break; //same extention as an existing shapefile case MapWindow.Interfaces.eLayerType.LineShapefile: case MapWindow.Interfaces.eLayerType.PolygonShapefile: case MapWindow.Interfaces.eLayerType.PointShapefile: sf = (MapWinGIS.Shapefile)curLayer.GetObject(); extents = calcShapefileExtent(sf); UpdateExtentBox(extents); break; default: break; } } } } }
// calculate a default cellsize (grid-max.500 rows or columns) // using the input shapefile extent private double calcDefaultCellsize() { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); double result = 0F; if (sf.Open(m_ShpFileName, null)) { double sfX = sf.Extents.xMax - sf.Extents.xMin; double sfY = sf.Extents.yMax - sf.Extents.yMin; double minExt = Math.Max(sfX, sfY); result = Math.Floor(minExt / 250F); } sf.Close(); return result; }
private static void CachePoints(string InPointsPath, int InValueFieldIndex, out KDTreeDLL.KDTree PointsTree, out double[][] Points, out double[] PointVals, out string Projection, out string ProjectionUnits, out MapWinGIS.Extents PointsExtents, MapWinGIS.ICallback callback) { int newperc = 0, oldperc = 0; MapWinGIS.Shapefile pointsf = new MapWinGIS.Shapefile(); pointsf.Open(InPointsPath, null); PointsExtents = pointsf.Extents; Projection = pointsf.Projection; if (Projection != null) { ProjectionUnits = Projection.Substring(Projection.IndexOf("units=") + 6); ProjectionUnits = ProjectionUnits.Substring(0, ProjectionUnits.IndexOf("+")).Trim(); } else { double tmpX = pointsf.Extents.xMax; string tmpstr = Math.Floor(tmpX).ToString(); if (tmpstr.Length > 4) { ProjectionUnits = ""; } else { ProjectionUnits = "lat/long"; } } PointsTree = new KDTreeDLL.KDTree(2); MapWinGIS.Point currpt; int ns = pointsf.NumShapes; Points = new double[ns][]; PointVals = new double[ns]; int duplicates = 0; for (int i = 0; i < ns; i++) { Points[i] = new double[2]; newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(ns)) * 100); if ((newperc > oldperc)) { if (callback != null) { callback.Progress("Status", newperc, "IDW Caching " + i.ToString()); } oldperc = newperc; } currpt = pointsf.get_Shape(i).get_Point(0); Points[i][0] = currpt.x; Points[i][1] = currpt.y; PointVals[i] = double.Parse(pointsf.get_CellValue(InValueFieldIndex, i).ToString()); try { if (PointsTree.search(Points[i]) == null) { PointsTree.insert(Points[i], i); } } catch (KDTreeDLL.KeyDuplicateException) { duplicates++; } } pointsf.Close(); }
/// <summary> /// Exports the shapes that are selected in the MapWindow view to a new shapefile. /// </summary> /// <param name="MapWin">A reference to the running MapWindow.</param> /// <param name="ExportToSFPath">The full path to where the result shapefile should be saved.</param> /// <param name="AddToMap">Indicates that the output should be added to the map view immediately.</param> /// <returns>False if an error occurs, true otherwise.</returns> public static bool ExportSelectedMWViewShapes(MapWindow.Interfaces.IMapWin MapWin, string ExportToSFPath, bool AddToMap) { MapWinUtility.Logger.Dbg("ExportSelectedMWViewShapes(MapWin: IMapWin,\n" + " ExportToSFPath: " + ExportToSFPath + ",\n" + " AddToMap: " + AddToMap.ToString() + ")"); if (MapWin.Layers.NumLayers == 0) { gErrorMsg = "Please select a layer first."; Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } if (MapWin.View.SelectedShapes.NumSelected == 0) { gErrorMsg = "There are no selected features to export. Please select a feature first."; Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWinGIS.Shapefile tollSF = new MapWinGIS.Shapefile(); MapWinGIS.Field fld = new MapWinGIS.Field(); MapWinGIS.Shape seg = new MapWinGIS.Shape(); int Segments; bool Status; Status = sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null); if (Status == false) { gErrorMsg = sf.get_ErrorMsg(sf.LastErrorCode); Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } if (System.IO.File.Exists(ExportToSFPath)) { try { DataManagement.DeleteShapefile(ref ExportToSFPath); } catch { gErrorMsg = "The destination file already exists, but could not be deleted. Please check to make sure the file isn't in use."; Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } } Status = tollSF.CreateNew(ExportToSFPath, sf.ShapefileType); if (Status == false) { gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode); Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } try { tollSF.Projection = sf.Projection; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } Status = tollSF.StartEditingShapes(true, null); if (Status == false) { gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode); Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } fld.Name = "MWShapeID"; fld.Type = MapWinGIS.FieldType.INTEGER_FIELD; fld.Width = 12; Segments = 0; // Chris M -- This is already opened above, why open // it again here? // sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null); for (int j = 0; j <= sf.NumFields - 1; j++) { tollSF.EditInsertField(sf.get_Field(j), ref j, null); } MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrWait; try { for (int i = 0; i <= MapWin.View.SelectedShapes.NumSelected - 1; i++) { seg = sf.get_Shape(MapWin.View.SelectedShapes[i].ShapeIndex); Status = tollSF.EditInsertShape(seg, ref Segments); if (Status == false) { gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode); Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); return(false); } for (int h = 0; h <= sf.NumFields - 1; h++) { tollSF.EditCellValue(h, i, sf.get_CellValue(h, MapWin.View.SelectedShapes[i].ShapeIndex)); } Segments = Segments + 1; } sf.Close(); tollSF.StopEditingShapes(true, true, null); } catch (Exception ex) { gErrorMsg = ex.Message; Error.SetErrorMsg(gErrorMsg); MapWinUtility.Logger.Dbg(gErrorMsg); } MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrArrow; tollSF.Close(); if (AddToMap) { MapWin.View.LockMap(); MapWindow.Interfaces.Layer thelayer; thelayer = MapWin.Layers.Add(ExportToSFPath, System.IO.Path.GetFileNameWithoutExtension(ExportToSFPath), true); thelayer.ClearLabels(); MapWin.View.UnlockMap(); } MapWinUtility.Logger.Dbg("Finished ExportSelectedMWViewShapes"); return(true); }
/// <summary> /// Generalization of polyline /// shapefiles using the Douglas-Peucker line simplification /// algorithm. This method will output a line shapefile. /// </summary> /// <param name="inFileName">Input shapefile</param> /// <param name="outFileName">Output shapefile</param> /// <param name="tolerance">tolerance parameter - /// specfies the maximum allowed distance between original polyline /// and simplified polyline</param> /// <param name="cback">Use this parameter for reporting progress. Set to null if not needed</param> public static void Generalize(string inFileName, string outFileName, double tolerance, MapWinGIS.ICallback cback) { MapWinGIS.Shapefile oldSF = new MapWinGIS.Shapefile(); if (!oldSF.Open(inFileName, null)) { throw new ArgumentException(string.Format("Shapefile {0} could not be opened. Error: {1}", inFileName, oldSF.get_ErrorMsg(oldSF.LastErrorCode))); } //Check if it's a line shapefile if (!(oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINE || oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINEM || oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINEZ)) { throw new ArgumentException(string.Format("Shapefile {0} must be a polyline shapefile.", inFileName)); } int numShapes = oldSF.NumShapes; int numFields = oldSF.NumFields; //create a new output shapefile MapWinGIS.Shapefile newSF = new MapWinGIS.Shapefile(); MapWinGIS.ShpfileType sftype = MapWinGIS.ShpfileType.SHP_POLYLINE; // if shapefile exists - open it and clear all shapes if (System.IO.File.Exists(outFileName)) { try { //TODO: ask for overwriting.. bool deleted = MapWinGeoProc.DataManagement.DeleteShapefile(ref outFileName); } finally { } } if (!newSF.CreateNew(outFileName, sftype)) { throw new InvalidOperationException ("Error creating shapefile " + outFileName + " " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } newSF.StartEditingShapes(true, cback); //Copy all fields if (!Globals.CopyFields(ref oldSF, ref newSF)) { throw new InvalidOperationException(string.Format("Error copying fields from {0} to {1}", oldSF.Filename, newSF.Filename)); } int newShapeIndex = 0; for (int shpIdx = 0; shpIdx < numShapes; ++shpIdx) { MapWinGIS.Shape shp = oldSF.get_Shape(shpIdx); // convert each part of the polyline shape to a 'geometry' object Geometry geom = MapWinGeoProc.NTS_Adapter.ShapeToGeometry(shp); for (int partIdx = 0; partIdx < geom.NumGeometries; ++partIdx) { Geometry geomPart = (Geometry)geom.GetGeometryN(partIdx); //do the simplification ICoordinate[] oldCoords = geomPart.Coordinates; DouglasPeuckerLineSimplifier simplifier = new DouglasPeuckerLineSimplifier(oldCoords); simplifier.DistanceTolerance = tolerance; ICoordinate[] newCoords = simplifier.Simplify(); //convert the coordinates back to a geometry Geometry newGeom = new LineString(newCoords); //convert the geometry back to a shape MapWinGIS.Shape newShape = MapWinGeoProc.NTS_Adapter.GeometryToShape(newGeom); //add the shape to the new shapefile newShapeIndex = newSF.NumShapes; if (newSF.EditInsertShape(newShape, ref newShapeIndex) == false) { throw new InvalidOperationException("Error inserting shape: " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } //add attribute values for (int fldIdx = 0; fldIdx < numFields; ++fldIdx) { object val = oldSF.get_CellValue(fldIdx, shpIdx); if (newSF.EditCellValue(fldIdx, newSF.NumShapes - 1, val) == false) { throw new InvalidOperationException("Error editing cell value: " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } } } } //close the old shapefile oldSF.Close(); //stop editing and close the new shapefile newSF.StopEditingShapes(true, true, cback); newSF.Close(); }
/// <summary> /// Converts a list of 3d-points to a point shapefile with z-value field. /// This function creates a new shapefile. The shapefile has two fields: /// a 'MWShapeId' field and a field which contains the z-value. /// </summary> /// <param name="ShpFileName">Name of the resulting point shapefile</param> /// <param name="ZFieldName">Name of the z-field in the shapefile</param> public void ToShapefile(string ShpFileName, string ZFieldName) { MapWinGIS.Shapefile newSF = new MapWinGIS.Shapefile(); try { Hashtable FieldIndices = new Hashtable(); MapWinGIS.ShpfileType sftype; sftype = MapWinGIS.ShpfileType.SHP_POINT; int fldIdx = 0; // if shapefile exists - open it and clear all shapes if (System.IO.File.Exists(ShpFileName)) { newSF.Open(ShpFileName, null); newSF.StartEditingShapes(true, null); newSF.EditClear(); } else //else, create a new shapefile { if (!newSF.CreateNew(ShpFileName, sftype)) { throw new InvalidOperationException ("Error creating shapefile " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } newSF.StartEditingShapes(true, null); } //check existing fields: for (int i = 0; i < newSF.NumFields; ++i) { MapWinGIS.Field fl = newSF.get_Field(i); if (fl.Name == "MWShapeID") { FieldIndices.Add("MWShapeID", i); } if (fl.Name == ZFieldName) { FieldIndices.Add(ZFieldName, i); } } //Add the fields: if (!FieldIndices.ContainsKey("MWShapeID")) { //First an ID field MapWinGIS.Field idFld = new MapWinGIS.Field(); idFld.Name = "MWShapeID"; idFld.Type = MapWinGIS.FieldType.INTEGER_FIELD; fldIdx = newSF.NumFields; if (newSF.EditInsertField(idFld, ref fldIdx, null) == false) { throw new InvalidOperationException("error inserting field " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } FieldIndices.Add("MWShapeID", fldIdx); } if (!FieldIndices.ContainsKey(ZFieldName)) { //Second add a Z-field MapWinGIS.Field zFld = new MapWinGIS.Field(); zFld.Name = "Z"; zFld.Type = MapWinGIS.FieldType.DOUBLE_FIELD; fldIdx = newSF.NumFields; if (newSF.EditInsertField(zFld, ref fldIdx, null) == false) { throw new InvalidOperationException("error inserting field " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } FieldIndices.Add("Z", fldIdx); } foreach (ICoordinate pt in _points) { //first, add a point shape (geometry) MapWinGIS.Shape newShp = new MapWinGIS.Shape(); newShp.Create(MapWinGIS.ShpfileType.SHP_POINT); MapWinGIS.Point newPt = new MapWinGIS.Point(); newPt.x = pt.X; newPt.y = pt.Y; int ptIdx = 0; newShp.InsertPoint(newPt, ref ptIdx); int shpIdx = newSF.NumShapes; newSF.EditInsertShape(newShp, ref shpIdx); //second add the z-value newSF.EditCellValue(fldIdx, shpIdx, pt.Z); } } finally { //finally stop editing and close the shapefile newSF.StopEditingShapes(true, true, null); if (newSF.Close() == false) { throw new InvalidOperationException("error closing shapefile " + newSF.get_ErrorMsg(newSF.LastErrorCode)); } } }
private void populateFields(string shpFileName) { cmbFields.Items.Clear(); MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWinGIS.Field curField; if (sf.Open(shpFileName,sf.GlobalCallback)) { for (int i = 0; i < sf.NumFields; ++i) { curField = sf.get_Field(i); if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD || curField.Type == MapWinGIS.FieldType.INTEGER_FIELD) { cmbFields.Items.Add(curField.Name); } } sf.Close(); } if (cmbFields.Items.Count > 0) { cmbFields.SelectedIndex = 0; } }