/// <summary> /// Attempts to open a file using the specified parameters. Given the popularity of the /// float data type, the grid will make an effort to open everything as a float data type. /// </summary> /// <param name="Filename">The Filename of the grid to open</param> /// <param name="InRam">Specifies whether or not the grid is in ram.</param> /// <param name="FileType">The file format as specified by a MapWindow.Interfaces.Types.GridFileType</param> /// <exception cref="System.ApplicationException">Returns an exception if there is a failure</exception> public void Open(string Filename, bool InRam, GridFileType FileType) { if (m_Grid.Open(Filename, MapWinGIS.GridDataType.FloatDataType, InRam, Convert.mwGridFileType(FileType), m_ICallBack) == false) { throw new MapWinException(m_Grid.LastErrorCode); } }
public bool RunAutoSnap(string outletPath, string newOutletPath, string d8Result, string streamShapeResult, double snapThreshod) { MapWinGIS.Grid g = new MapWinGIS.Grid(); g.Open(d8Result); double dx = g.Header.dX; g.Close(); return(MapWinGeoProc.Utils.SnapPointsToLines(outletPath, streamShapeResult, snapThreshod, dx / 2, newOutletPath, true, null)); }
/// <summary> /// Er... Changes a grid format? /// </summary> /// <param name="origFilename">Original Grid Filename</param> /// <param name="newFilename">Output Grid Filename</param> /// <param name="newFileType">Specifies the original file format of the grid</param> /// <param name="newFileFormat">Specifies the new file format</param> /// <param name="multFactor">Like Extrusion, this multiplies the Z value</param> /// <returns>Boolean, false if there was an error</returns> public static bool ChangeGridFormat(string origFilename, string newFilename, MapWinGIS.GridFileType newFileType, MapWinGIS.GridDataType newFileFormat, float multFactor) { bool Errors = false; MapWinGIS.Grid tGrd = new MapWinGIS.Grid(); tGrd.Open(origFilename, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null); Logger.Status("Writing Grid to New Format"); //If we're multiplying by a factor, must //create the new grid and actually do it ourselves. //Otherwise, can save directly //Jiri Kadlec 1-28-2009 we still neet to create a new grid when the data or file type is different. if (multFactor == 1 && newFileFormat == tGrd.DataType) { Logger.Dbg("Saving directly to new format"); tGrd.Save(newFilename, newFileType, null); // ProgressForm) } else { Logger.Dbg("Saving to new format with mult. factor: " + multFactor.ToString()); MapWinGIS.GridHeader hdr = new MapWinGIS.GridHeader(); hdr.CopyFrom(tGrd.Header); MapWinGIS.Grid newgrid = new MapWinGIS.Grid(); if (!newgrid.CreateNew(newFilename, hdr, newFileFormat, hdr.NodataValue, true, newFileType, null)) { Logger.Message("Unable to create new grid!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK); Errors = true; } else { int ncols = tGrd.Header.NumberCols; int nrows = tGrd.Header.NumberRows; float[] oneRow = new float[ncols + 1]; for (int i = 0; i <= nrows - 1; i++) { tGrd.GetFloatWindow(i, i, 0, ncols, ref oneRow[0]); for (int z = 0; z <= ncols - 1; z++) { oneRow[z] *= multFactor; } newgrid.PutFloatWindow(i, i, 0, ncols, ref oneRow[0]); } newgrid.Save(newFilename, newFileType, null); newgrid.Close(); } } return(!Errors); }
public bool Open(string gridFile, bool inRAM) { if (grid.Open(gridFile, MapWinGIS.GridDataType.UnknownDataType, inRAM, MapWinGIS.GridFileType.UseExtension, null) == false) { gErrorMsg = "Problem opening grid: " + grid.get_ErrorMsg(grid.LastErrorCode); Error.SetErrorMsg(gErrorMsg); Debug.WriteLine(gErrorMsg); return(false); } else { return(true); } }
public bool SetSoilPath(string soilPath) { string soilFileName = System.IO.Path.GetFileName(soilPath); string temp = prjPath + @"\Source\soil\" + soilFileName; if (System.IO.File.Exists(temp) == false) { System.IO.File.Copy(soilPath, temp); } // copy .prj file if any string prjsource = System.IO.Path.ChangeExtension(soilFileName, ".prj"); string prjtarget = System.IO.Path.ChangeExtension(temp, ".prj"); if (System.IO.File.Exists(prjsource) && (!System.IO.File.Exists(prjtarget))) { System.IO.File.Copy(prjsource, prjtarget); } hruGlobals.soilPath = temp; soilLayer = new MapWinGIS.Grid(); soilLayer.Open(soilPath); return(true); }
/// <summary> /// This creates a new shapefile that has Z values and follows along the same line segments. /// The boundaries for grid cells are marked with vertices and the segment is given a Z value /// that corresponds to the grid elevation it intersects. /// </summary> /// <param name="ElevGrid">A string filename for the grid that contains the elevations.</param> /// <param name="PolyLine">A string filename for a polyline shapefile that shows the pathways of the cross sections in the X-Y direction.</param> /// <param name="OutFileName">A string containing the full path of the desired output shapefile. The extension should be *.shp</param> /// <param name="CrossSectionType">Clarifies the type of output</param> /// <param name="ICallBack">A MapWinGIS.ICallback for progress messages. [Optional]</param> /// <remarks>This function throws Argument or Application exceptions on errors, so it's recommended that coders enclose it in a try catch block.</remarks> public static void GetCrossSection(string ElevGrid, string PolyLine, string OutFileName, CrossSectionTypes CrossSectionType, MapWinGIS.ICallback ICallBack) { bool res; // Load the grid if (ElevGrid == null) { throw new ArgumentException("ElevGrid cannot be null."); } if (System.IO.File.Exists(ElevGrid) == false) { throw new ArgumentException("The file " + ElevGrid + " does not exist."); } MapWinGIS.Grid mwGrid = new MapWinGIS.Grid(); res = mwGrid.Open(ElevGrid, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { throw new ApplicationException(mwGrid.get_ErrorMsg(mwGrid.LastErrorCode)); } // Load the Shapefile if (PolyLine == null) { throw new ArgumentException("PolyLine cannot be null."); } if (System.IO.File.Exists(PolyLine) == false) { throw new ArgumentException("The file " + PolyLine + " does not exist."); } MapWinGIS.Shapefile mwPolyLine = new MapWinGIS.Shapefile(); res = mwPolyLine.Open(PolyLine, ICallBack); if (res == false) { throw new ApplicationException(mwPolyLine.get_ErrorMsg(mwPolyLine.LastErrorCode)); } GetCrossSection(mwGrid, mwPolyLine, OutFileName, CrossSectionType, ICallBack); }
/// <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); }
/// <summary> /// This overload calculates the difference between files. THe number of rows and columns should be the same. /// </summary> /// <param name="SourceFile1">String filename of one grid to compare</param> /// <param name="SourceFile2">String filename of another grid to compare</param> /// <param name="DestFile">String filename of the output difference file</param> /// <param name="Overwrite">Boolean, true if you wish to overwrite an existing output /// file and delete the associated .bmp file. False raises a messagebox if the files exist.</param> /// <param name="ICallBack">A MapWinGIS.ICallBack for status messages</param> public static void Difference(string SourceFile1, string SourceFile2, string DestFile, bool Overwrite, MapWinGIS.ICallback ICallBack) { MapWinGIS.Grid Source1 = new MapWinGIS.Grid(); MapWinGIS.Grid Source2 = new MapWinGIS.Grid(); MapWinGIS.Grid Dest = new MapWinGIS.Grid(); bool res; // Open the source grids if (ICallBack != null) { ICallBack.Progress("Status", 0, "Opening Files..."); } res = Source1.Open(SourceFile1, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Argument Exception: " + Source1.get_ErrorMsg(Source1.LastErrorCode)); throw new ArgumentException(Source1.get_ErrorMsg(Source1.LastErrorCode)); } res = Source2.Open(SourceFile2, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { throw new ArgumentException(Source2.get_ErrorMsg(Source2.LastErrorCode)); } // Delete any existing files for our output grid if (System.IO.File.Exists(DestFile)) { string bmp = System.IO.Path.ChangeExtension(DestFile, "bmp"); string bpw = System.IO.Path.ChangeExtension(DestFile, "bpw"); string prj = System.IO.Path.ChangeExtension(DestFile, "prj"); string mwleg = System.IO.Path.ChangeExtension(DestFile, "mwleg"); if (Overwrite == false) { if (System.IO.File.Exists(bmp) || System.IO.File.Exists(bpw) || System.IO.File.Exists(prj) || System.IO.File.Exists(mwleg)) { if (MapWinUtility.Logger.Message("The output file exists, or associated files of the same name exist. Do you wish to delete the existing files?\n", "Output Files Exist", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.DialogResult.No) == System.Windows.Forms.DialogResult.No) { return; } // This ensures mapwindow will recognize the new image as a new file. if (System.IO.File.Exists(bmp)) { System.IO.File.Delete(bmp); } if (System.IO.File.Exists(bpw)) { System.IO.File.Delete(bpw); } if (System.IO.File.Exists(prj)) { System.IO.File.Delete(prj); } if (System.IO.File.Exists(mwleg)) { System.IO.File.Delete(mwleg); } } else { if (MapWinUtility.Logger.Message("The output file already exists. Do you wish to delete it?", "Destination File Already Exists", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.DialogResult.No) == System.Windows.Forms.DialogResult.No) { return; } } } else { if (System.IO.File.Exists(bmp)) { System.IO.File.Delete(bmp); } if (System.IO.File.Exists(bpw)) { System.IO.File.Delete(bpw); } if (System.IO.File.Exists(prj)) { System.IO.File.Delete(prj); } if (System.IO.File.Exists(mwleg)) { System.IO.File.Delete(mwleg); } } System.IO.File.Delete(DestFile); } // Create a new output grid MapWinGIS.GridHeader newHeader = new MapWinGIS.GridHeader(); newHeader.CopyFrom(Source1.Header); if (ICallBack != null) { MapWinUtility.Logger.Dbg("Creating Output File..."); ICallBack.Progress("Status", 0, "Creating Output File..."); } res = Dest.CreateNew(DestFile, newHeader, Source1.DataType, 0, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Argument Exception: " + Dest.get_ErrorMsg(Dest.LastErrorCode)); throw new ArgumentException(Dest.get_ErrorMsg(Dest.LastErrorCode)); } // Calculate the differences Difference(Source1, Source2, Dest, ICallBack); // Close Source grids Source1.Close(); Source2.Close(); // Save and close the output grid res = Dest.Save(DestFile, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Application Exception: " + Dest.get_ErrorMsg(Dest.LastErrorCode)); throw new ArgumentException(Dest.get_ErrorMsg(Dest.LastErrorCode)); } Dest.Close(); MapWinUtility.Logger.Dbg("Finished Difference"); }
public bool LabelBasins(string watershedShpPath, string streamNetShpPath, string oiShpPath, string extraOiShpPath) { SetProjection(); MapWinGIS.Grid dem = new MapWinGIS.Grid(); dem.Open(basedem); //MapWindow.Interfaces.Layer demLayer = (MapWindow.Interfaces.Layer)dem; wshd = new MapWinGIS.Shapefile(); wshd.Open(watershedShpPath); //MapWindow.Interfaces.Layer wshdLayer = (MapWindow.Interfaces.Layer)wshd; net = new MapWinGIS.Shapefile(); net.Open(streamNetShpPath); // MapWindow.Interfaces.Layer netLayer = (MapWindow.Interfaces.Layer)net; oiFile = new MapWinGIS.Shapefile(); oiFile.Open(oiShpPath); //MapWindow.Interfaces.Layer oiFileLayer = (MapWindow.Interfaces.Layer)oiFile; if (extraOiShpPath != "") { extraOiFile = new MapWinGIS.Shapefile(); extraOiFile.Open(extraOiShpPath); } //MapWindow.Interfaces.Layer extraOiFileLayer = (MapWindow.Interfaces.Layer)extraOiFile; //hruGlobals.populateLinkToBasin(demLayer, wshdLayer, netLayer, oiFileLayer, extraOiFileLayer); //Passing, exception,, cannot convert UTM to LatLong hruGlobals.populateLinkToBasin(dem, wshd, net, oiFile, extraOiFile); //Passing, exception,, cannot convert UTM to LatLong hruGlobals.clearCentroids(); int numFields = wshd.NumFields; // Find index for PolygonID field int polyidField = -1; for (int i = 0; i < numFields; i++) { if (wshd.Field[i].Name.Equals("PolygonID", System.StringComparison.InvariantCultureIgnoreCase)) { polyidField = i; break; } } ////////////////////////////////////////////////////////////////////////// int numShapes = wshd.NumShapes; for (int i = 0; i < numShapes; i++) { MapWinGIS.Shape shape = wshd.Shape[i]; MapWinGIS.Point centroid = MapWinGeoProc.Utils.Centroid(ref shape); int link = Convert.ToInt32(wshd.CellValue[polyidField, i]); if (hruGlobals.linkToBasin.ContainsKey(link) == false) { //MessageBox.Show(strings_vb.nobasinforlink & link.ToString() & _ //strings_vb.tryrestart, MWSWATName, _ //MessageBoxButtons.OK, MessageBoxIcon.Error) return(false); } int basin = hruGlobals.linkToBasin[link]; hruGlobals.setCentroid(basin, centroid); if (hruGlobals.basinToSWATBasin.ContainsKey(basin)) { int SWATBasin = hruGlobals.basinToSWATBasin[basin]; //wshdLayer.AddLabel(SWATBasin.ToString(), System.Drawing.Color.Black, centroid.x, centroid.y, MapWinGIS.tkHJustification.hjCenter) } } return(true); }
private void cmdIdentify_Click(object sender, EventArgs e) { if (m_MapWin.View.SelectedShapes.NumSelected == 0) { MapWinUtility.Logger.Msg(resMan.GetString("msgZeroShapesSelected.Text"), resMan.GetString("titleSelectShapes.Text")); return; } if (cmbIdentFrom.SelectedIndex == -1) { MapWinUtility.Logger.Msg(resMan.GetString("msgIdentFromNotSelected.Text"), resMan.GetString("titleSpecifyLayer.Text")); return; } if (cmbIdentWith.SelectedIndex == -1) { MapWinUtility.Logger.Msg(resMan.GetString("msgIdentWithNotSelected.Text"), resMan.GetString("titleSpecifyLayer.Text")); return; } if (m_MapWin.View.SelectedShapes.NumSelected == 0) { return; } // If it's a polygon layer we're identifying, call SelectByPolygon // If it's a grid, extract by mask // ...then, open that temporary file (not Add to Map, just "Open"), and summarize all data within that // file. int fromLayerHandle = -1; int maskLayerHandle = -1; if (cmbIdentFrom.SelectedIndex != -1) { string s = cmbIdentFrom.Items[cmbIdentFrom.SelectedIndex].ToString(); if (s.Contains(")")) { s = s.Substring(0, s.IndexOf(")")); } s = s.Replace("(", ""); if (!int.TryParse(s, out fromLayerHandle)) { return; } if (fromLayerHandle == -1) { return; } } if (cmbIdentWith.SelectedIndex != -1) { string s = cmbIdentWith.Items[cmbIdentWith.SelectedIndex].ToString(); if (s.Contains(")")) { s = s.Substring(0, s.IndexOf(")")); } s = s.Replace("(", ""); if (!int.TryParse(s, out maskLayerHandle)) { return; } if (maskLayerHandle == -1) { return; } } string TempPath = System.IO.Path.GetTempFileName(); System.IO.File.Delete(TempPath); MapWinGIS.Shape IdentifyBy; MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)m_MapWin.Layers[m_MapWin.Layers.CurrentLayer].GetObject(); if (m_MapWin.View.SelectedShapes.NumSelected > 1) { // Get 0 and 1 first to initialize IdentifyBy MapWinGIS.Shape shp1 = sf.get_Shape(m_MapWin.View.SelectedShapes[0].ShapeIndex); MapWinGIS.Shape shp2 = sf.get_Shape(m_MapWin.View.SelectedShapes[1].ShapeIndex); MapWinGeoProc.SpatialOperations.MergeShapes(ref shp1, ref shp2, out IdentifyBy); // ...now, the rest if (m_MapWin.View.SelectedShapes.NumSelected > 2) { for (int i = 2; i < m_MapWin.View.SelectedShapes.NumSelected; i++) { MapWinGIS.Shape tmpResultShp; MapWinGIS.Shape shp3 = sf.get_Shape(m_MapWin.View.SelectedShapes[i].ShapeIndex); MapWinGeoProc.SpatialOperations.MergeShapes(ref IdentifyBy, ref shp3, out tmpResultShp); IdentifyBy = tmpResultShp; tmpResultShp = null; } } // Ready to identify based on a single shape now regardless of multiple selected } else { IdentifyBy = sf.get_Shape(m_MapWin.View.SelectedShapes[0].ShapeIndex); } MapWindow.Interfaces.eLayerType layerType = m_MapWin.Layers[fromLayerHandle].LayerType; if (layerType == MapWindow.Interfaces.eLayerType.Grid) { // Grid TempPath = System.IO.Path.ChangeExtension(TempPath, ".bgd"); string fn = m_MapWin.Layers[fromLayerHandle].FileName; MapWinGeoProc.SpatialOperations.ClipGridWithPolygon(ref fn, ref IdentifyBy, ref TempPath, chbJustToExtents.Checked); MapWinGIS.Grid grd = new MapWinGIS.Grid(); grd.Open(TempPath, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null); if (grd == null || grd.Header == null) { MapWinUtility.Logger.Msg(resMan.GetString("msgNoGridValues.Text"), resMan.GetString("titleNoGridValues.Text")); return; } m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); MapWinGIS.Extents exts = new MapWinGIS.Extents(); exts.SetBounds(grd.Header.XllCenter, grd.Header.YllCenter + grd.Header.NumberRows * grd.Header.dY, 0, grd.Header.XllCenter + grd.Header.NumberCols * grd.Header.dX, grd.Header.YllCenter, 0); m_MapWin.Layers.CurrentLayer = fromLayerHandle; m_Plugin.m_GridPropfrm.PopulateForm(!m_Plugin.m_HavePanel, grd, m_MapWin.Layers[fromLayerHandle].Name, exts, fromLayerHandle); this.Close(); } else { // SF if (!chbJustToExtents.Checked) { string fn = m_MapWin.Layers[fromLayerHandle].FileName; // 2/14/2008 jk the results ArrayList cannot be null, // when it was null it caused an exception in SpatialOperations.SelectWithPolygon method //System.Collections.ArrayList results = null; System.Collections.ArrayList results = new System.Collections.ArrayList(); MapWinGeoProc.SpatialOperations.SelectWithPolygon(ref fn, ref IdentifyBy, ref results); // Switch current layer over to the one we're identifying so that the shapes // can be reselected for visual effect m_MapWin.Layers.CurrentLayer = fromLayerHandle; m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); int[] iresults = new int[results.Count]; for (int i = 0; i < results.Count; i++) { iresults[i] = (int)results[i]; m_MapWin.View.SelectedShapes.AddByIndex((int)results[i], m_MapWin.View.SelectColor); } m_Plugin.m_shpFilePropfrm.PopulateForm(!m_Plugin.m_HavePanel, (MapWinGIS.Shapefile)m_MapWin.Layers[fromLayerHandle].GetObject(), iresults, m_MapWin.Layers[fromLayerHandle].Name, false); this.Close(); } else { object rslt = null; m_MapWin.Layers.CurrentLayer = fromLayerHandle; MapWinGIS.Shapefile DestSF = (MapWinGIS.Shapefile)m_MapWin.Layers[fromLayerHandle].GetObject(); DestSF.SelectShapes(IdentifyBy.Extents, 0.1, MapWinGIS.SelectMode.INTERSECTION, ref rslt); m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); int[] results = (int[])rslt; for (int i = 0; i < results.Length; i++) { m_MapWin.View.SelectedShapes.AddByIndex((int)results[i], m_MapWin.View.SelectColor); } m_Plugin.m_shpFilePropfrm.PopulateForm(!m_Plugin.m_HavePanel, DestSF, results, m_MapWin.Layers[fromLayerHandle].Name, false); this.Close(); } } }