private void 添加点型图层ToolStripMenuItem_Click(object sender, EventArgs e) { //创建要素类 #region 创建新的内存工作空间 IWorkspaceFactory pWSF = new InMemoryWorkspaceFactoryClass(); IWorkspaceName pWSName = pWSF.Create("", "Temp", null, 0); IName pName = (IName)pWSName; IWorkspace pMemoryWS = (IWorkspace)pName.Open(); #endregion IField oField = new FieldClass(); IFields oFields = new FieldsClass(); IFieldsEdit oFieldsEdit = null; IFieldEdit oFieldEdit = null; IFeatureClass oFeatureClass = null; IFeatureLayer oFeatureLayer = null; oFieldsEdit = oFields as IFieldsEdit; oFieldEdit = oField as IFieldEdit; oFieldEdit.Name_2 = "OBJECTID"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; oFieldEdit.IsNullable_2 = false; oFieldEdit.Required_2 = false; oFieldsEdit.AddField(oField); oField = new FieldClass(); oFieldEdit = oField as IFieldEdit; IGeometryDef pGeoDef = new GeometryDefClass(); IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.AvgNumPoints_2 = 5; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGeoDefEdit.GridCount_2 = 1; pGeoDefEdit.HasM_2 = false; pGeoDefEdit.HasZ_2 = false; pGeoDefEdit.SpatialReference_2 = axMapControl1.SpatialReference; oFieldEdit.Name_2 = "SHAPE"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; oFieldEdit.GeometryDef_2 = pGeoDef; oFieldEdit.IsNullable_2 = true; oFieldEdit.Required_2 = true; oFieldsEdit.AddField(oField); oField = new FieldClass(); oFieldEdit = oField as IFieldEdit; oFieldEdit.Name_2 = "Code"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; //oFieldEdit.Length = 10; oFieldEdit.IsNullable_2 = true; oFieldsEdit.AddField(oField); //创建要素类 oFeatureClass = (pMemoryWS as IFeatureWorkspace).CreateFeatureClass("Temp", oFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); oFeatureLayer = new FeatureLayerClass(); oFeatureLayer.Name = "PointLayer"; oFeatureLayer.FeatureClass = oFeatureClass; //创建唯一值符号化对象 IUniqueValueRenderer pURender = new UniqueValueRendererClass(); pURender.FieldCount = 1; pURender.set_Field(0, "Code"); pURender.UseDefaultSymbol = false; //创建SimpleMarkerSymbolClass对象 ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass(); //创建RgbColorClass对象为pSimpleMarkerSymbol设置颜色 IRgbColor pRgbColor = new RgbColorClass(); pRgbColor.Red = 255; pSimpleMarkerSymbol.Color = pRgbColor as IColor; //设置pSimpleMarkerSymbol对象的符号类型,选择钻石 pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSDiamond; //设置pSimpleMarkerSymbol对象大小,设置为5 pSimpleMarkerSymbol.Size = 5; //显示外框线 pSimpleMarkerSymbol.Outline = true; //为外框线设置颜色 IRgbColor pLineRgbColor = new RgbColorClass(); pLineRgbColor.Green = 255; pSimpleMarkerSymbol.OutlineColor = pLineRgbColor as IColor; //设置外框线的宽度 pSimpleMarkerSymbol.OutlineSize = 1; //半透明颜色 pURender.AddValue("1", "", pSimpleMarkerSymbol as ISymbol); //唯一值符号化内存图层 (oFeatureLayer as IGeoFeatureLayer).Renderer = pURender as IFeatureRenderer; ILayerEffects pLyrEffect = oFeatureLayer as ILayerEffects; //透明度 pLyrEffect.Transparency = 0; oFeatureLayer.Visible = true; this.axMapControl1.AddLayer(oFeatureLayer,axMapControl1.LayerCount); insertpoint = true; }
public static IFeatureLayer FindMyFeatureLayer(IMap inMap, string inName) { string isfound = "false"; ILayer tempLayer; IFeatureLayer goodLayer = new FeatureLayerClass(); for (int i = 0; i < inMap.LayerCount; i++) { tempLayer = inMap.get_Layer(i); if (tempLayer is IFeatureLayer) { if (tempLayer.Name == inName) { isfound = "true"; goodLayer = tempLayer as IFeatureLayer; } } } //duplicate name in the map.? How we deal with it if (isfound == "true") { return goodLayer; } else { return null; } }
/// <summary> /// 两图层进行裁剪运算 /// </summary> /// <param name="inputLayer">被裁剪图层</param> /// <param name="clipLayer">裁剪图层</param> /// <param name="outputFullPath">输出图层完整路径</param> public void ClipByLayer(ILayer inputLayer, ILayer clipLayer, string outputFullPath) { string inputPath = GetLayerPath(inputLayer); string clipPath = GetLayerPath(clipLayer); Clip clipTool = new Clip(); clipTool.in_features = inputPath; clipTool.clip_features = clipPath; clipTool.out_feature_class = outputFullPath; Geoprocessor processor = new Geoprocessor(); IGPProcess process = null; processor.OverwriteOutput = true; process = clipTool; processor.Validate(process, true); processor.Execute(process, null); FileInfo fi = new FileInfo(outputFullPath); string pathDir = fi.Directory.FullName; string name = fi.Name; IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace fws = wsf.OpenFromFile(pathDir, 0) as IFeatureWorkspace; IFeatureClass featCls = fws.OpenFeatureClass(name); IFeatureLayer layer = new FeatureLayerClass(); layer.FeatureClass = featCls; layer.Name = featCls.AliasName; m_mapControl.Map.AddLayer(layer as ILayer); }
protected override void OnClick() { string tablePath = Path.Combine(DataPath, @"File-Based\MajorCities.csv"); string tableName = Path.GetFileName(tablePath); Type factoryType = Type.GetTypeFromProgID("esriDataSourcesFile.TextFileWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(tablePath), 0); ITable table = ((IFeatureWorkspace) workspace).OpenTable(tableName); ISpatialReference sRef = CreateSpatialReference(esriSRGeoCSType.esriSRGeoCS_WGS1984); IFeatureClass featureClass = CreateXYEventFeature(table, "POINT_X", "POINT_y", sRef); IFeatureLayer featureLayer = new FeatureLayerClass { FeatureClass = featureClass, Name = "CSV XY Event Table" }; IFeatureLayerSourcePageExtension sourcePageExtension = new XYDataSourcePageExtensionClass(); ((ILayerExtensions) featureLayer).AddExtension(sourcePageExtension); ArcMap.Document.FocusMap.AddLayer(featureLayer); ArcMap.Document.UpdateContents(); }
public static Blobber CreateBlobber() { BlobberRepository repository = new BlobberRepository(); repository.StartEdit(); Blobber b = repository.Create(); b.BlobberId = BLOBBER_ID; IFeatureLayer layer = new FeatureLayerClass(); layer.Name = BLOBBER_VALUE_1; IPropertySet properties = new PropertySetClass(); properties.SetProperty("VALUE1", BLOBBER_VALUE_1); properties.SetProperty("VALUE2", BLOBBER_VALUE_2); properties.SetProperty("VALUE3", BLOBBER_VALUE_3); b.Properties = properties; b.Store(); repository.StopEdit(true); return b; }
protected override void OnClick() { // // TODO: Sample code showing how to access button host // // ArcMap.Application.CurrentTool = null; // Nohe did this //IDocument doc = ArcMap.Application.Document; //IMxDocument mxDoc = doc as IMxDocument; //int value = ArcMap.Application.hWnd; //IActiveView av = mxDoc.ActiveView as IActiveView; //IMap map = mxDoc.FocusMap as IMap; //frddie IMap map = ArcMap.Document.ActiveView.FocusMap; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; //nohe //IWorkspaceFactory wsf = new FileGDBWorkspaceFactory(); IFeatureWorkspace ws = wsf.OpenFromFile(@"C:\Users\alex7370\Documents\GitHub\MyAddins\AddingAFeature\features.gdb", 0) as IFeatureWorkspace; IFeatureLayer featureLayer = new FeatureLayerClass { FeatureClass = ws.OpenFeatureClass("pointFeature")}; featureLayer.Name = featureLayer.FeatureClass.AliasName; map.AddLayer(featureLayer); ArcMap.Document.ActiveView.Refresh(); }
/// <summary> Add feature class to active View and then zoom to its extend </summary> /// <param name="view">the current active view</param> /// <param name="inFeatureClass">the feature class to add</param> /// <param name="zoomTo">zoom to loaded feature class</param> /// <returns>the created layer</returns> public static IFeatureLayer addFeatureClassToMap(IActiveView view, IFeatureClass inFeatureClass, bool zoomTo = false) { IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = inFeatureClass; featureLayer.Name = inFeatureClass.AliasName; featureLayer.Visible = true; view.FocusMap.AddLayer(featureLayer); if(zoomTo) view.Extent = featureLayer.AreaOfInterest; return featureLayer; }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; try { if (bDataPath == true) { fileName=txtOutputData.Text; shpDir =fileName.Substring(0, fileName.LastIndexOf("\\")); startX=fileName.LastIndexOf("\\"); endX=fileName.Length; shpFile=fileName.Substring(startX+1,endX-startX-1); } else { shpDir=txtOutputData.Text; shpFile="��ֵ��"; } if (m_pRasterLyr != null) { double dInterval=Convert.ToDouble(txtConInterval.Text); double dBaseLine=Convert.ToDouble(txtBaseLine.Text); object objBaseLine=dBaseLine; ISurfaceOp pRasterSurfaceOp = new RasterSurfaceOpClass(); IRaster pInRaster = m_pRasterLyr.Raster; IFeatureClass pOutFClass= pRasterSurfaceOp.Contour(pInRaster as IGeoDataset , dInterval, ref objBaseLine) as IFeatureClass ; //2. QI to IDataset IDataset pFDS=pOutFClass as IDataset ; //3. Get a shapefile workspace IWorkspaceFactory pSWF=new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS=pSWF.OpenFromFile(shpDir,0) as IFeatureWorkspace ; //4. Copy contour output to a new shapefile IWorkspace pWS = pFWS as IWorkspace; if (pWS.Exists() == true) Utility.DelFeatureFile(shpDir, shpFile + ".shp"); pFDS.Copy(shpFile,pFWS as IWorkspace ); IFeatureLayer pFeatLyr = new FeatureLayerClass(); pFeatLyr.FeatureClass = pOutFClass; pFeatLyr.Name = pOutFClass.AliasName; pFeatLyr.Visible = true; pMainFrm.getMapControl().AddLayer(pFeatLyr, 0); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void init(int programID, AxMapControl mc, Intersect.ProgramStepUserControl.OnFinish of, MainWindow mw) { inited = true; if (program == null) program = new Program(); program.id = programID; program.select(); if (project == null) project = new Project(); project.id = program.projectID; project.select(); NetSizeUserControl.init(program.id); ConditionUserControl.init(program.id); mapControl = mc; onFinish = of; mainWindow = mw; mapControlMouseDown = null; //在初始化时就要对valid进行判断. Thread t = new Thread(delegate() { System.Threading.Thread.Sleep(500); Dispatcher.BeginInvoke((ThreadStart)delegate() { if (isValid()) { valid = true; onFinish(true); IFeatureClass resultFeatureClass; if ((resultFeatureClass = GisUtil.getFeatureClass(System.IO.Path.GetDirectoryName(project.path), "评价结果.shp")) != null) { IFeatureLayer resultFeatureLayer = new FeatureLayerClass(); resultFeatureLayer.FeatureClass = resultFeatureClass; mapControl.AddLayer(resultFeatureLayer); } else { SiteSelector siteSelector = new SiteSelector(mapControl, program.id); siteSelector.startSelectSite(); } } }); }); t.Start(); }
private void btnApply_Click(object sender, EventArgs e) { if (isSelectNode == true) { IFeatureClass pFeatCls = m_pFeatureWorkspace.OpenFeatureClass(m_strSelFeatLayer); IFeatureLayer pFeatLayer = new FeatureLayerClass(); pFeatLayer.FeatureClass = pFeatCls; pFeatLayer.Visible = true; pFeatLayer.Name = pFeatCls.AliasName; AxMapControl axMap = pMainFrm.getMapControl(); axMap.AddLayer(pFeatLayer); axMap.Refresh(); } }
private void MainForm_Load(object sender, EventArgs e) { m_mapControl = (IMapControl3) axMapControl1.Object; //relative file path to the sample data from EXE location string filePath = @"..\..\..\data\USAMajorHighways"; //Add Lakes layer IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Lakes"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("us_lakes"); #region create a SimplerRenderer IRgbColor color = new RgbColorClass(); color.Red = 190; color.Green = 232; color.Blue = 255; ISimpleFillSymbol sym = new SimpleFillSymbolClass(); sym.Color = color; ISimpleRenderer renderer = new SimpleRendererClass(); renderer.Symbol = sym as ISymbol; #endregion ((IGeoFeatureLayer)featureLayer).Renderer = renderer as IFeatureRenderer; axMapControl1.Map.AddLayer((ILayer)featureLayer); //Add Highways layer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Highways"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways"); axMapControl1.Map.AddLayer((ILayer)featureLayer); //******** Important ************* //store a reference to this form (Mainform) using the EditHelper class EditHelper.TheMainForm = this; EditHelper.IsEditorFormOpen = false; //add the EditCmd command to the toolbar axEditorToolbar.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem(new EditCmd(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); }
//新建一个要素类 private void CreateFeatureclass(IQueryDef pQueryDef, IFeatureWorkspace pFeatureWorkspace) { IFeatureDataset pFeatureDataset = pFeatureWorkspace.OpenFeatureQuery("My counties join ", pQueryDef); IFeatureClassContainer pFeatureClassContainer = pFeatureDataset as IFeatureClassContainer; //判断IFeatureClassContainer中是否有要素类存在 if (pFeatureClassContainer.ClassCount != 1) { MessageBox.Show("Failed to create feature class by query!"); return; } IFeatureClass pFeatureClass = pFeatureClassContainer.get_Class(0); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pFeatureClass.AliasName; pMap.AddLayer(pFeatureLayer); }
private void axTOCControl_main_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e) { IBasicMap map = new MapClass(); ILayer layer = new FeatureLayerClass(); object other = new object(); object index = new object(); esriTOCControlItem item = new esriTOCControlItem(); axTOCControl_main.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index); if (e.button == 2) { (m_pMapC2 as IMapControl4).CustomProperty = layer; if (item == esriTOCControlItem.esriTOCControlItemLayer) { m_ToolbarMenu.PopupMenu(e.x, e.y, axTOCControl_main.hWnd); } } }
public bool QueryIntersect(string srcLayerName, string tgtLayerName, IMap imap, esriSpatialRelationEnum spatialRel) { DataOperator pDo = new DataOperator(imap, null); //定义并根据图层名称获取图层对象 IFeatureLayer iSrcLayer = new FeatureLayerClass(); iSrcLayer = (IFeatureLayer)pDo.GetLayerbyName(srcLayerName); IFeatureLayer iTgtLayer = (IFeatureLayer)pDo.GetLayerbyName(tgtLayerName); //通过查询过滤获取continent层中亚洲几何 IGeometry pGt; IFeature pF; IFeatureCursor pFcs; IFeatureClass pFcl; IQueryFilter pQf = new QueryFilter(); pQf.WhereClause = "CONTINENT='Asia'";//设置查询条件 pFcs = iTgtLayer.FeatureClass.Search(pQf, false); pF = pFcs.NextFeature(); pGt = pF.Shape; try { pFcl = iSrcLayer.FeatureClass; } catch { } ISpatialFilter pSf = new SpatialFilter(); pSf.Geometry = pGt; pSf.WhereClause = "POP_RANK=5";//人口等级低于5的城市 pSf.SpatialRel = (ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum)spatialRel; //定义要素选择对象,以要素搜索图层进行实例化 IFeatureSelection pFs = (IFeatureSelection)iSrcLayer; //以空间过滤器对要素进行选择,并建立新选择集 try { pFs.SelectFeatures(pSf, esriSelectionResultEnum.esriSelectionResultNew, false); } catch { } return(true); }
/// <summary> /// 获取最后生成的照片点图层 /// </summary> /// <returns></returns> public ILayer GetPhotosLayer() { IFeatureClass featureclass = CreateFeatureClass(); IFeatureCursor featureCursor = featureclass.Insert(true); //遍历照片链表 以创建缓存的形式插入数据 foreach (var p in PhotoList) { IPoint pPoint = new PointClass(); //坐标转换 var t = CoordinateUtils.gcj02_To_Wgs84(p.latitude, p.longtitude); pPoint.PutCoords(t.longtitude, t.latitude); pPoint.SpatialReference = mainMapControl.SpatialReference; pPoint.Project(mainMapControl.SpatialReference); IFeatureBuffer featureBuffer = featureclass.CreateFeatureBuffer(); featureBuffer.Shape = pPoint; featureBuffer.set_Value(featureBuffer.Fields.FindField("Name"), p.name); featureBuffer.set_Value(featureBuffer.Fields.FindField("Latitude"), p.latitude); featureBuffer.set_Value(featureBuffer.Fields.FindField("Longtitude"), p.longtitude); featureBuffer.set_Value(featureBuffer.Fields.FindField("OSSpath"), p.osspath); featureCursor.InsertFeature(featureBuffer); } featureCursor.Flush(); //创建图层 IFeatureLayer pFeaturelayer = new FeatureLayerClass(); pFeaturelayer.FeatureClass = featureclass; pFeaturelayer.Name = "特征地物照片点"; //修饰该图层 ISimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbol(); pMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSSquare; var pRgbColor = ColorUtils.GetRgbColor(186, 114, 208); pMarkerSymbol.Color = pRgbColor; ISimpleRenderer pSimpleRenderer = new SimpleRendererClass(); pSimpleRenderer.Symbol = (ISymbol)pMarkerSymbol; (pFeaturelayer as IGeoFeatureLayer).Renderer = pSimpleRenderer as IFeatureRenderer; return(pFeaturelayer as ILayer); }
/// <summary> /// Convert IFeatureClass to ILayer. /// </summary> /// <param name="fclass"></param> /// <returns></returns> public static ILayer ToILayer(IFeatureClass fclass) { ILayer layer = null; IFeatureLayer featureLayer = new FeatureLayerClass(); try { featureLayer.FeatureClass = fclass; featureLayer.Name = fclass.AliasName; layer = featureLayer as ILayer; return(layer); } finally { fclass = null; layer = null; featureLayer = null; } }
internal static void addNewShapefile(IApplication m_application, string shpFileName) { IMxDocument pDoc = m_application.Document as IMxDocument; IMap pMap = pDoc.FocusMap; IWorkspaceFactory pFactory = new ShapefileWorkspaceFactory(); // Based on the .NET Application Setting WorldShapefilePath, get the path, make a layer, and add to TOC IFeatureWorkspace pFeatWorkspace = pFactory.OpenFromFile(System.IO.Path.GetDirectoryName(ArcTimData.StaticClass.infoTable.Rows[0]["ShapefilePath"].ToString() + "\\" + shpFileName), 0) as IFeatureWorkspace; IFeatureClass pFeatClass = pFeatWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(ArcTimData.StaticClass.infoTable.Rows[0]["ShapefilePath"].ToString() + "\\" + shpFileName)); IFeatureLayer pfeatureLayer = new FeatureLayerClass(); pfeatureLayer.Name = System.IO.Path.GetFileNameWithoutExtension(shpFileName); pfeatureLayer.FeatureClass = pFeatClass; pMap.AddLayer((ILayer)pfeatureLayer); IActiveView iav = pDoc.ActiveView; iav.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); iav.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); pDoc.UpdateContents(); }
void ThematicView2_Load(object sender, EventArgs e) { SdeConnection conn = new SdeConnection(); ISdeConnectionInfo sdeConn = (ISdeConnectionInfo)conn; IFeatureWorkspace fw = (IFeatureWorkspace)sdeConn.Workspace; IFeatureClass fcThua = fw.OpenFeatureClass("sde.thixa_thua"); IFeatureLayer flThua = new FeatureLayerClass(); flThua.FeatureClass = fcThua; ILayer layerThua = (ILayer)flThua; IFeatureClass fcDuong = fw.OpenFeatureClass("sde.thixa_duong"); IFeatureLayer flDuong = new FeatureLayerClass(); flDuong.FeatureClass = fcDuong; ILayer layerDuong = (ILayer)flDuong; layerDuong.Name = fcDuong.AliasName; layerThua.Name = fcThua.AliasName; _mapController.AddLayer(layerDuong); _mapController.AddLayer(layerThua); }
private void showMap() { SdeConnection conn = new SdeConnection(); ISdeConnectionInfo sdeConn = (ISdeConnectionInfo)conn; IFeatureWorkspace fw = (IFeatureWorkspace)sdeConn.Workspace; IFeatureClass fcHem = fw.OpenFeatureClass("sde.thixa_hem"); IFeatureLayer flHem = new FeatureLayerClass(); flHem.FeatureClass = fcHem; ILayer layerThua = (ILayer)flHem; IFeatureClass fcDuong = fw.OpenFeatureClass("sde.thixa_duong"); IFeatureLayer flDuong = new FeatureLayerClass(); flDuong.FeatureClass = fcDuong; ILayer layerDuong = (ILayer)flDuong; layerDuong.Name = fcDuong.AliasName; layerThua.Name = fcHem.AliasName; _mapController.AddLayer(flHem); _mapController.AddLayer(flDuong); }
// ESRI.ArcGIS.Carto.FeatureLayerClass has version specific dependencies on ESRI.ArcGIS.Display // which means that this code must be compiled specifically for each version of ArcGIS that it // will run on. private static ILayer BuildSpecialQueryLayer(string name, string connection, string predicate) { var geometryType = esriGeometryType.esriGeometryPoint; string oidFields = "ProjectId,AnimalId,FixDate"; const int srid = 4326; string query; switch (name) { case "Invalid Locations": query = "SELECT * FROM InvalidLocations " + (String.IsNullOrEmpty(predicate) ? "" : "WHERE " + predicate.Replace("EndLocalDateTime", "LocalDateTime")); break; case "Valid Locations": query = "SELECT * FROM ValidLocations " + (String.IsNullOrEmpty(predicate) ? "" : "WHERE " + predicate.Replace("EndLocalDateTime", "LocalDateTime")); break; case "Velocity Vectors": query = "SELECT * FROM VelocityVectors " + (String.IsNullOrEmpty(predicate) ? "" : "WHERE " + predicate); geometryType = esriGeometryType.esriGeometryPolyline; oidFields = "ProjectId,AnimalId,LocalDateTime"; break; case "No Movement Points": query = "SELECT * FROM NoMovement " + (String.IsNullOrEmpty(predicate) ? "" : "WHERE " + predicate); oidFields = "ProjectId,AnimalId,LocalDateTime"; break; default: throw new ArgumentOutOfRangeException("name", name, "Unknown layer name"); } var featureClass = BuildQueryFeatureClass(connection, query, name, oidFields, srid, geometryType); var featureLayer = new FeatureLayerClass { FeatureClass = featureClass, Name = name }; return(featureLayer); }
private void AddShapeLayerItem_Click(object sender, EventArgs e) { // OpenFileDialog 类用于创建“打开文件”对话框,它是 C#中的标准控件。 OpenFileDialog OpenShapeDlg = new OpenFileDialog(); // 设置打开文件的类型过滤规则为:仅打开*.shp 文件。 OpenShapeDlg.Filter = "shp files (*.shp)|*.shp"; // 其他参数设置。 OpenShapeDlg.FilterIndex = 1; OpenShapeDlg.RestoreDirectory = true; // 显示“打开文件”对话框,返回值为 DialogResult.OK 表示点击了“确定”按钮。 if (OpenShapeDlg.ShowDialog() == DialogResult.OK) { // OpenFileDialog 类的 FileName 属性存储了选中文件的完整路径名, string strWorkspace = System.IO.Path.GetDirectoryName(OpenShapeDlg.FileName); // 利用 System.IO 库中 Path 类的 GetFileNameWithoutExtension 方法可以解析出 string strLayerName = System.IO.Path.GetFileNameWithoutExtension(OpenShapeDlg.FileName); // 实例化一个 ShapefileWorkspaceFactory 组件对象, IWorkspaceFactory wsFactory = new ShapefileWorkspaceFactory(); // 调用 OpenFromFile 通过目录名方法打开 Shapefile 数据库。 IWorkspace shpWorkspace = wsFactory.OpenFromFile(strWorkspace, 0); if (shpWorkspace != null) { shpDatasets = shpWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass); // 首先利用 Reset 方法将元素定位器重置到起始位置。 shpDatasets.Reset(); // 调用 Next 方法获取其中的第一个数据集对象,并将定位器后移一位 IDataset shpDataset = shpDatasets.Next(); // 循环访问 Datasets 中的每一个数据集对象,shpDataset 为 null 表示循环结束。 while (shpDataset != null) { if (shpDataset.Name == strLayerName) { IFeatureLayer newLayer = new FeatureLayerClass(); newLayer.FeatureClass = shpDataset as IFeatureClass; newLayer.Name = strLayerName; axMapControl1.Map.AddLayer(newLayer); break; } shpDataset = shpDatasets.Next(); } } } }
/// <summary> /// 添加shp文件 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private ILayer addShpData(string fileName) { try { string workSpacePath = System.IO.Path.GetDirectoryName(fileName); string shapeFileName = System.IO.Path.GetFileName(fileName); IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace fws = (IFeatureWorkspace)wsf.OpenFromFile(workSpacePath, 0);//打开工作空间 IFeatureClass pFeatureClass = fws.OpenFeatureClass(shapeFileName); IDataset pDataset = pFeatureClass as IDataset; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pDataset.Name; ILayer pLayer = pFeatureLayer as ILayer; return(pLayer); }catch (Exception e) { MessageBox.Show("打开失败,原因" + e.Message); return(null); } }
/// <summary> /// 打开个人地理数据库 /// </summary> /// <param name="ws"></param> private void addDataSetMap(IWorkspace ws) { IEnumDataset pEnumDataset; pEnumDataset = ws.get_Datasets(esriDatasetType.esriDTFeatureClass); IDataset pDataset; pEnumDataset.Reset(); pDataset = pEnumDataset.Next(); while (pDataset != null) { IFeatureClass pFeatureClass = pDataset as IFeatureClass; IFeatureLayer pLayer = new FeatureLayerClass(); pLayer.FeatureClass = pFeatureClass; pLayer.Name = pDataset.Name; this.view.axMapControl1.AddLayer(pLayer); pDataset = pEnumDataset.Next(); } }
private IFeatureLayer AddTempFeatureLayer() { try { //IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass(); //string gdbName = "FGISTemp" + ".gdb"; //string gdbFullPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), gdbName); //IWorkspace workspace; //IFeatureWorkspace featureWorkspace; //if (System.IO.Directory.Exists(gdbFullPath)) //{ // featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(gdbFullPath, 0); //} //else //{ // IWorkspaceName workspaceName = workspaceFactory.Create(System.IO.Path.GetTempPath(), gdbName, null, 0); // IName name = (ESRI.ArcGIS.esriSystem.IName)workspaceName; // workspace = (IWorkspace)name.Open(); // featureWorkspace = workspace as IFeatureWorkspace; //} IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetTempPath(), 0); IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(tempFeatureLayerName); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; featureLayer.Visible = true; ILayerEffects layerEffects = featureLayer as ILayerEffects; layerEffects.Transparency = 60; IActiveView activeView = m_hookHelper.ActiveView; activeView.FocusMap.AddLayer(featureLayer); activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeography, null, null); txtMessages.Text += "已创建临时层:Temp_Layer\r\n"; return(featureLayer); } catch (Exception) { return(null); } }
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e) { if (e.button == 1) { //Get the required layer esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone; IBasicMap map = new MapClass(); ILayer layer = new FeatureLayerClass(); object other = new object(); object index = new object(); axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index); //Click on the legend class if (item == esriTOCControlItem.esriTOCControlItemLegendClass) { IFeatureLayer featureLayer = layer as IFeatureLayer; if (featureLayer != null) { //Show different frames when the type of feature is different if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint) { RenderLayerPoint layerPoint = new RenderLayerPoint(featureLayer, this); layerPoint.Show(); } else if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryLine || featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline) { RenderLayerLine layerLine = new RenderLayerLine(featureLayer, this); layerLine.Show(); } else if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon) { RenderLayerFill layerFill = new RenderLayerFill(featureLayer, this); layerFill.Show(); } else { ; } } } } }
private void method2ToolStripMenuItem_Click(object sender, EventArgs e) { System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.Filter = "CAD (*.dwg)|*.dwg"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string filename = openFileDialog.FileName; if (filename != "") { //axMapControl1.ClearLayers(); IWorkspaceFactory pCadWorkspaceFactory = new CadWorkspaceFactory(); IFeatureWorkspace pWorkspace = pCadWorkspaceFactory.OpenFromFile( System.IO.Path.GetDirectoryName(filename), 0) as IFeatureWorkspace; IFeatureDataset pFeatureDataset = pWorkspace.OpenFeatureDataset( System.IO.Path.GetFileName(filename)); IFeatureClassContainer pFeatureClassContainer = pFeatureDataset as IFeatureClassContainer; IFeatureClass pFeatureClass; IFeatureLayer pFeatureLayer; for (int i = 0; i < pFeatureClassContainer.ClassCount; i++) { pFeatureClass = pFeatureClassContainer.get_Class(i); if (pFeatureClass.FeatureType == esriFeatureType.esriFTCoverageAnnotation) { pFeatureLayer = new CadAnnotationLayerClass(); } else { pFeatureLayer = new FeatureLayerClass(); } pFeatureLayer.Name = pFeatureClass.AliasName; pFeatureLayer.FeatureClass = pFeatureClass; axMapControl1.AddLayer(pFeatureLayer, 0); } } } }
/// <summary> /// 获取advTree的FeatureClassNode节点 /// </summary> /// <param name="parentNode"></param> private void getFeatureClassNode(DevComponents.AdvTree.Node parentNode) { IFeatureDataset pFeatureDataset = null; //根据节点的Tag属性获取FeatureDataset pFeatureDataset = (IFeatureDataset)parentNode.Tag; IEnumDataset pEnDS = pFeatureDataset.Subsets; pEnDS.Reset(); //遍历DataSet内的各个图层 IDataset pDS = pEnDS.Next(); while (pDS is IFeatureClass) { IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pDS as IFeatureClass; DevComponents.AdvTree.Node node = new DevComponents.AdvTree.Node(); node.Tag = pDS;//把Dataset赋值给item的Tag属性 node.Name = pDS.Name; node.Text = pDS.Name; parentNode.Nodes.Add(node); //根据FeatureClass的不同类型,设置不同的图标 switch (pFeatureLayer.FeatureClass.ShapeType) { case esriGeometryType.esriGeometryPolygon: node.ImageIndex = 9; break; case esriGeometryType.esriGeometryPolyline: node.ImageIndex = 10; break; case esriGeometryType.esriGeometryPoint: node.ImageIndex = 11; break; default: break; } pDS = pEnDS.Next(); } }
/// <summary> /// Add the feature layer to the map /// </summary> /// <param name="fc">IFeatureClass</param> private void AddFeatureLayerToMap(IFeatureClass fc) { IFeatureLayer outputFeatureLayer = new FeatureLayerClass(); outputFeatureLayer.FeatureClass = fc; IGeoFeatureLayer geoLayer = outputFeatureLayer as IGeoFeatureLayer; if (geoLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint) { IFeatureRenderer pFeatureRender; pFeatureRender = (IFeatureRenderer) new SimpleRenderer(); ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass(); pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSimpleMarkerSymbol.Size = 3.0; ISimpleRenderer pSimpleRenderer; pSimpleRenderer = new SimpleRenderer(); pSimpleRenderer.Symbol = (ISymbol)pSimpleMarkerSymbol; geoLayer.Renderer = (IFeatureRenderer)pSimpleRenderer; } else if (geoLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { IFeatureRenderer pFeatureRender; pFeatureRender = (IFeatureRenderer) new SimpleRenderer(); ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass(); pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSHollow; pSimpleFillSymbol.Outline.Width = 0.4; ISimpleRenderer pSimpleRenderer; pSimpleRenderer = new SimpleRenderer(); pSimpleRenderer.Symbol = (ISymbol)pSimpleFillSymbol; geoLayer.Renderer = (IFeatureRenderer)pSimpleRenderer; } geoLayer.Name = fc.AliasName; ESRI.ArcGIS.Carto.IMap map = ArcMap.Document.FocusMap; map.AddLayer((ILayer)outputFeatureLayer); }
/// <summary> /// 获取ListViewEx的FeatureClassItem /// </summary> /// <param name="parentNode"></param> private void getFeatureClassItem(DevComponents.AdvTree.Node parentNode) { IFeatureDataset pFeatureDataset; //根据节点的Tag属性获取FeatureDataset pFeatureDataset = (IFeatureDataset)parentNode.Tag; IEnumDataset pEnDS = pFeatureDataset.Subsets; pEnDS.Reset(); //遍历DataSet内的各个图层 IDataset pDS = pEnDS.Next(); while (pDS is IFeatureClass) { ListViewItem dirItem = new ListViewItem(); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pDS as IFeatureClass; dirItem = lvwData.Items.Add(pDS.Name); dirItem.Name = pDS.Name; dirItem.Text = pDS.Name; dirItem.Tag = pDS;//把Dataset赋值给item的Tag属性 //根据FeatureClass的不同类型,设置不同的图标 switch (pFeatureLayer.FeatureClass.ShapeType) { case esriGeometryType.esriGeometryPolygon: dirItem.ImageIndex = 7; break; case esriGeometryType.esriGeometryPolyline: dirItem.ImageIndex = 8; break; case esriGeometryType.esriGeometryPoint: dirItem.ImageIndex = 9; break; default: break; } pDS = pEnDS.Next(); } }
private IFeatureLayer CreateSHP_Point(List <Point3D> PointList, string FileFullPath) { int index = FileFullPath.LastIndexOf("\\"); string filename = System.IO.Path.GetFileNameWithoutExtension(FileFullPath); string shpFolder = System.IO.Path.GetDirectoryName(FileFullPath); IWorkspaceFactory shpWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace shpFWS = (IFeatureWorkspace)shpWSF.OpenFromFile(WorkSpaceName, 0); //建立基本属性表 IFields pFields = CreateShapeFields(esriGeometryType.esriGeometryPoint); IFeatureClass pFeatureClass; string filename_shp = WorkSpaceName + @"/" + filename + ".shp"; if (System.IO.File.Exists(filename_shp)) { System.IO.File.Delete(filename_shp); System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".dbf")); System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".shx")) ; } pFeatureClass = shpFWS.CreateFeatureClass(filename, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); for (int j = 0; j < PointList.Count; j++) { IPoint pPoint = new PointClass(); pPoint.X = PointList[j].X; pPoint.Y = PointList[j].Y; IFeature pFeature = pFeatureClass.CreateFeature(); pFeature.Shape = pPoint as IGeometry; pFeature.Store(); } //完善属性表 Complete_PropertyTable(ref pFeatureClass, PointList); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.Name = filename; pFeatureLayer.FeatureClass = pFeatureClass; return(pFeatureLayer); }
private IFeatureLayer CreateFeatureLayer(esriGeometryType pesriGeometryType, string pstrLayerName, List <string> pstrFieldNameLt = null, List <esriFieldType> pesriFieldTypeLt = null, int intRed = _intColor, int intGreen = _intColor, int intBlue = _intColor, double dblWidth = 1, int intOutlineRed = _intColor, int intOutlineGreen = _intColor, int intOutlineBlue = _intColor, esriSimpleLineStyle pesriSimpleLineStyle = esriSimpleLineStyle.esriSLSSolid, esriSimpleFillStyle pesriSimpleFillStyle = esriSimpleFillStyle.esriSFSSolid, string strSymbolLayerPath = null, bool blnVisible = true) { var pWorkspace = CConstants.ParameterInitialize.pWorkspace; var pm_mapControl = CConstants.ParameterInitialize.m_mapControl; pstrLayerName += CHelpFunc.GetTimeStampWithPrefix(); IFeatureClass pFeatureClass = CreateFeatureClass(pesriGeometryType, pstrLayerName, pWorkspace, pm_mapControl, pstrFieldNameLt, pesriFieldTypeLt); IFeatureLayer pFLayer = new FeatureLayerClass(); pFLayer.FeatureClass = pFeatureClass; pFLayer.Name = pFeatureClass.AliasName; pFLayer.SpatialReference = pm_mapControl.SpatialReference; RenderLayer(ref pFLayer, pesriGeometryType, intRed, intGreen, intBlue, dblWidth, intOutlineRed, intOutlineGreen, intOutlineBlue, pesriSimpleLineStyle, pesriSimpleFillStyle, strSymbolLayerPath); //save Layer as layer file ".lyr" //create a new LayerFile instance ILayerFile layerFile = new LayerFileClass(); //create a new layer file layerFile.New(pWorkspace.PathName + "\\" + pstrLayerName + ".lyr"); //attach the layer file with the actual layer layerFile.ReplaceContents((ILayer)pFLayer); //save the layer file layerFile.Save(); //***********************************************是否添加到当前文档中来***********************************************// //m_mapControl.AddLayer(pFLayer,m_mapControl .LayerCount); pm_mapControl.AddLayer(pFLayer); pFLayer.Visible = blnVisible; pm_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); return(pFLayer); }
public static void AddData_CAD(AxMapControl axMapControl1) { IWorkspaceFactory pWorkspaceFactory; IFeatureWorkspace pFeatureWorkspace; IFeatureLayer pFeatureLayer; IFeatureDataset pFeatureDataset; //获取当前路径和文件名 OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { string strFullPath = dlg.FileName; if (strFullPath == "") return; int Index = strFullPath.LastIndexOf("//"); string filePath = strFullPath.Substring(0, Index); string fileName = strFullPath.Substring(Index + 1); //打开CAD数据集 pWorkspaceFactory = new CadWorkspaceFactoryClass(); pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(filePath, 0); //打开一个要素集 pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(fileName); //IFeaturClassContainer可以管理IFeatureDataset中的每个要素类 IFeatureClassContainer pFeatClassContainer = (IFeatureClassContainer)pFeatureDataset; //对CAD文件中的要素进行遍历处理 for (int i = 0; i < pFeatClassContainer.ClassCount - 1; i++) { IFeatureClass pFeatClass = pFeatClassContainer.get_Class(i); if (pFeatClass.FeatureType == esriFeatureType.esriFTCoverageAnnotation) //如果是注记,则添加注记层 pFeatureLayer = new CadAnnotationLayerClass(); else //如果是点、线、面,则添加要素层 pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.Name = pFeatClass.AliasName; pFeatureLayer.FeatureClass = pFeatClass; axMapControl1.Map.AddLayer(pFeatureLayer); axMapControl1.ActiveView.Refresh(); } ILayer layer = axMapControl1.get_Layer(0); axMapControl1.Extent = layer.AreaOfInterest; } }
public IFeatureLayer OracleQueryLayer() { // 创建SqlWorkspaceFactory的对象 Type pFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SqlWorkspaceFactory"); IWorkspaceFactory pWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(pFactoryType); // 构造连接数据库的参数 IPropertySet pConnectionProps = new PropertySetClass(); pConnectionProps.SetProperty("dbclient", "Oracle11g"); pConnectionProps.SetProperty("serverinstance", "esri"); pConnectionProps.SetProperty("authentication_mode", "DBMS"); pConnectionProps.SetProperty("user", "scott"); pConnectionProps.SetProperty("password", "arcgis"); // 打开工作空间 IWorkspace workspace = pWorkspaceFactory.Open(pConnectionProps, 0); ISqlWorkspace pSQLWorkspace = workspace as ISqlWorkspace; //获取数据库中的所有表的名称 //IStringArray pStringArray= pSQLWorkspace.GetTables(); //for (int i = 0; i < pStringArray.Count; i++) //{ // MessageBox.Show(pStringArray.get_Element(i)); //} // 构造过滤条件 SELECT * FROM PointQueryLayer IQueryDescription queryDescription = pSQLWorkspace.GetQueryDescription("SELECT * FROM TEST"); ITable pTable = pSQLWorkspace.OpenQueryClass("QueryLayerTest", queryDescription); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pTable as IFeatureClass; return pFeatureLayer; }
/// <summary> /// Removes a layer from the active view /// </summary> /// <param name="lyrName">layer name</param> /// <returns>bool expresing if it succeded</returns> public bool removeLayer(string lyrName) //Removes a layer from the map { bool x = true; IFeatureLayer ftrlyr = new FeatureLayerClass(); try { IMap map = acView as IMap; ftrlyr = getFeatureLayer(lyrName) as IFeatureLayer; map.DeleteLayer(ftrlyr); acView.Refresh(); } catch (Exception e) { MessageBox.Show("Error: " + e.ToString()); x = false; } return(x); }
/// <summary> /// 方法补充:使用工作空间打开一个Access库中的一个要素类 /// </summary> /// <param name="clsName">文件名</param> /// <param name="DBPath">文件路径</param> private void OpenWorkspaceFromFileAccess(string clsName, string DBPath) { //排除没有打开指定数据的情况 if (DBPath != m_Path + "\\Access.mdb") { MessageBox.Show("请打开指定数据库!"); return; } //新建一个Access的工作空间工厂 IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(DBPath, 0); IFeatureWorkspace pAccessWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass pFeatureClass = pAccessWorkspace.OpenFeatureClass(clsName); IFeatureLayer pFLayer = new FeatureLayerClass(); pFLayer.FeatureClass = pFeatureClass; pFLayer.Name = clsName; this.axMapControl1.AddLayer(pFLayer); this.axMapControl1.Refresh(); }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { // TODO: Add LHSBCreateFeature.OnClick implementation IWorkspaceFactory wsFactory = new SdeWorkspaceFactoryClass(); IPropertySet ps = new PropertySetClass(); //ps.SetProperty("SERVER", "admin");//计算机名 //ps.SetProperty("INSTANCE", "esri_sde");//服务名称 ps.SetProperty("INSTANCE", ""); //服务名称 ps.SetProperty("DATABASE", "LHSBDB"); //数据库名称 ps.SetProperty("USER", "sa"); //用户名 ps.SetProperty("PASSWORD", "lee123"); //用户名登陆密码 IWorkspace ws = wsFactory.Open(ps, 0); IFeatureClass fc = CreateFeatureClass(ws as IFeatureWorkspace); IFeatureLayer layer = new FeatureLayerClass(); layer.Name = fc.AliasName; layer.FeatureClass = fc; m_hookHelper.FocusMap.AddLayer(layer as ILayer); }
private void 叠加分析ToolStripMenuItem_Click(object sender, EventArgs e) { GDBInput pGDB = new GDBInput(); IWorkspace pWs = pGDB.GetWorkspace("D:\\第二次公开课\\IDW\\JiAn", GISDesign.GDBInput.GDBType.SHP); IFeatureClass pFeatureClass = pGDB.GetFeatureClass(pWs as IFeatureWorkspace, "BoundMask"); IFeatureClass pFt = pGDB.GetFeatureClass(pWs as IFeatureWorkspace, "Bound"); IFeatureClass pFt1 = new InterSect().Intsect(pFeatureClass, pFt, "D:\\第二次公开课\\IDW\\JiAn", "test11"); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFt1; axMapControl1.Map.AddLayer(pFeatureLayer as ILayer); axMapControl1.ActiveView.Refresh(); }
/// <summary> /// 加载CAD数据 /// </summary> /// <param name="fileData"></param> private void AddCADData(object fileData, IMap pMap) { //获取CAD文件 FileInfo file = (FileInfo)fileData; string dwgPath = file.FullName;//得到CAD文件的全路径 int indexdwg = dwgPath.LastIndexOf("\\"); string filedwgPath = dwgPath.Substring(0, indexdwg); string filedwgName = dwgPath.Substring(indexdwg + 1); //获取CAD文件的Workspace IWorkspace dwgWorkspace = GetWorkspace(filedwgPath, "dwg"); IFeatureWorkspace pFeatureWorkspace = dwgWorkspace as IFeatureWorkspace; IFeatureDataset pFeatureDataset; IFeatureLayer pFeatureLayer = null; //得到CAD文件的FeatureDataset pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(filedwgName); IFeatureClassContainer pFeatureClassContainer = null; pFeatureClassContainer = pFeatureDataset as IFeatureClassContainer; //遍历并打开CAD文件 for (int i = 0; i < pFeatureClassContainer.ClassCount - 1; i++) { IFeatureClass pFeatureClass; //得到FeatureClass pFeatureClass = pFeatureClassContainer.get_Class(i); if (pFeatureClass.FeatureType == esriFeatureType.esriFTCoverageAnnotation) { pFeatureLayer = new CadAnnotationLayerClass(); } else { pFeatureLayer = new FeatureLayerClass(); } pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pFeatureClass.AliasName; m_pFeaturelayer = pFeatureLayer; pMap.AddLayer(pFeatureLayer); m_pActiveView.Refresh(); } }
protected virtual IMap CreateMap() { if (_Map != null) { return(_Map); } _Map = new MapClass(); ComReleaser.ManageLifetime(_Map); foreach (var o in this.GetTestClasses()) { IFeatureLayer layer = new FeatureLayerClass(); layer.FeatureClass = o; layer.Name = o.AliasName; _Map.AddLayer(layer); } return(_Map); }
private void initialize() { if (strGeometryType == "") { return; } DeleteTempFeatureClass(); queryFeatureClass = CreateFeatureClass(strGeometryType, m_hookHelper.FocusMap.SpatialReference); if (queryFeatureClass == null) { return; } IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = queryFeatureClass; StopEditTempLayer(featureLayer, false); RemoveTempLayer(); AddTempFeatureLayer(); this.btnBuffer.Enabled = true; StartEditTempLayer(IsExistTempLayer());//启动临时要素编辑 }
private void KillExistingFeatureclass(string strFilename) { try { IGxCatalogDefaultDatabase Defaultgdb = ArcMap.Application as IGxCatalogDefaultDatabase; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace pWorkspace = workspaceFactory.OpenFromFile(Defaultgdb.DefaultDatabaseName.PathName, 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(strFilename); IDataset pDataset = pFeatureLayer.FeatureClass as IDataset; if (pDataset.CanDelete()) { pDataset.Delete(); } } catch { } }
private void button2_Click(object sender, EventArgs e) { string rasterSavePath = @"E:\GIS底层实验\WorkSpace\MyAddIn\result"; string filePath = textBox1.Text; string fileFolder = Path.GetDirectoryName(filePath); //shp文件所在的文件夹 string fileName = Path.GetFileName(filePath); //shp文件名 IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(fileFolder, 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; pFeatureWorkspace.OpenFeatureClass(fileName); IFeatureLayer pFLayer = new FeatureLayerClass(); IFeatureClass pFC = pFeatureWorkspace.OpenFeatureClass(fileName); pFLayer.FeatureClass = pFC; pFLayer.Name = pFC.AliasName; IFeatureLayer featureLayer = pFLayer; ILayer rasterLayer = xjShpPointToRaster(featureLayer, rasterSavePath, Convert.ToDouble(textBox2.Text), comboBox1.SelectedText); MessageBox.Show("Successful!"); }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { IWorkspaceFactory wsFactory = new SdeWorkspaceFactoryClass(); IPropertySet ps = new PropertySetClass(); ps.SetProperty("SERVER", "DESKTOP-E7NJ8FE\\SQLEXPRESS"); ps.SetProperty("INSTANCE", ""); ps.SetProperty("DATABASE", "SDE"); ps.SetProperty("USER", "SDE"); ps.SetProperty("PASSWORD", "123"); IWorkspace ipWorkspace = wsFactory.Open(ps, 0); ISpatialReference ipSr = m_hookHelper.FocusMap.SpatialReference; IFeatureClass ipFeatCls = CreateFeatureClass( ipWorkspace as IFeatureWorkspace, ipSr); IFeatureLayer ipFeatLyr = new FeatureLayerClass(); ipFeatLyr.Name = "point"; ipFeatLyr.FeatureClass = ipFeatCls; m_hookHelper.FocusMap.AddLayer(ipFeatLyr); }
public IFeatureLayer AddFeatureClassToMap(string layerName) { IFeatureWorkspace feaWorkSpace = this.m_workSpace as IFeatureWorkspace; IFeatureClass featClass = feaWorkSpace.OpenFeatureClass(layerName); if (featClass.FeatureType == esriFeatureType.esriFTAnnotation) { IDataset dataSet = featClass as IDataset; IFDOGraphicsLayerFactory pGLF = new FDOGraphicsLayerFactoryClass(); IFDOGraphicsLayer pFDOGLayer = pGLF.OpenGraphicsLayer((IFeatureWorkspace)dataSet.Workspace, featClass.FeatureDataset, dataSet.Name) as IFDOGraphicsLayer; ((IFeatureLayer)pFDOGLayer).Name = layerName; return((IFeatureLayer)pFDOGLayer); } else { IFeatureLayer feaLyr = new FeatureLayerClass(); feaLyr.FeatureClass = featClass; feaLyr.Name = layerName; return(feaLyr); } }
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e) { this.axLicenseControl1.ContextMenuStrip = null; IBasicMap map = new MapClass(); object other = null; object index = null; ILayer layer = new FeatureLayerClass(); esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone; try { this.axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index); } catch (Exception ex) { throw ex; } switch (e.button) { case 1: if (item == esriTOCControlItem.esriTOCControlItemLayer) { if (layer is IAnnotationSublayer) { return; } else { pMovelayer = layer; } dataGridView1.DataSource = GetLayerData(layer as IFeatureLayer); } break; case 2: //右键 System.Drawing.Point pt = new System.Drawing.Point(MousePosition.X, MousePosition.Y); contextMenuStrip1.Show(pt); break; } }
protected override void OnClick() { try { string shpFilePath = string.Format(@"C:\temp\contour datas"); string shpFileName = "contour2.shp"; // height data IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(shpFilePath, 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; IFeatureClass pFeatureClass = featureWorkspace.OpenFeatureClass(shpFileName); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = ""; IEnvelope pEnv = pFeatureLayer.AreaOfInterest; IGeoDataset pGDS = (IGeoDataset)pFeatureLayer.FeatureClass; ISpatialReference pSR = pGDS.SpatialReference; IGeometry pGeom = pEnv; pGeom.Project(pSR); ITinEdit pTinEdit = new TinClass(); pTinEdit.InitNew(pEnv); IFields pFields = pFeatureClass.Fields; IField pFiled = pFields.get_Field(pFields.FindField("HSL")); object Missing = Type.Missing; esriTinSurfaceType pTinSurface = esriTinSurfaceType.esriTinHardLine; pTinEdit.AddFromFeatureClass(pFeatureClass, pQueryFilter, pFiled, pFiled, pTinSurface, ref Missing); string outputFolderPath = @"C:\temp\Output\"; string tinFolderName = "tin_data"; pTinEdit.SaveAs(outputFolderPath + tinFolderName, ref Missing); MessageBox.Show("end"); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } ArcMap.Application.CurrentTool = null; }
public override void OnClick() { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Title = "打开CAD文件"; openFileDialog1.Filter = "CAD图形文件(*.dwg)|*.DWG"; if (openFileDialog1.ShowDialog() == DialogResult.OK && m_hookHelper.Hook is IMapControlDefault) { FileInfo fileinfo = new FileInfo(openFileDialog1.FileName); string path = fileinfo.DirectoryName; string name = fileinfo.Name; IWorkspaceFactory cadWorkSpaceFactory = new CadWorkspaceFactoryClass(); IFeatureWorkspace workspace = cadWorkSpaceFactory.OpenFromFile(path, 0) as IFeatureWorkspace; IFeatureDataset featDataset = workspace.OpenFeatureDataset(name); IFeatureClassContainer featClassContainer = featDataset as IFeatureClassContainer; IFeatureClass featClass; IFeatureLayer featLayer; for (int i = 0; i < featClassContainer.ClassCount; i++) { featClass = featClassContainer.get_Class(i); if (featClass.FeatureType == esriFeatureType.esriFTCoverageAnnotation) { //标注类型,必须设置为单位的标注图层 featLayer = new CadAnnotationLayerClass(); } else { //点线面类型 featLayer = new FeatureLayerClass(); } featLayer.Name = featClass.AliasName; featLayer.FeatureClass = featClass; ((IMapControlDefault)m_hookHelper.Hook).Map.AddLayer((ILayer)featLayer); } } }
/// <summary> /// add raster or featureclass to map as layer /// </summary> public static void AddDataToMapAsLayer(IGeoDataset RasterDSOrFeatureClass, string LayerName) { ILayer ThisLayer = null; if (RasterDSOrFeatureClass is IRasterDataset) { //add rasterdataset as raster layer ThisLayer = new RasterLayerClass() as ILayer; ((IRasterLayer)ThisLayer).CreateFromDataset(RasterDSOrFeatureClass as IRasterDataset); } if (RasterDSOrFeatureClass is IFeatureClass) { //add feature class to a feature layer ThisLayer = new FeatureLayerClass() as ILayer; ((IFeatureLayer)ThisLayer).FeatureClass = RasterDSOrFeatureClass as IFeatureClass; } ThisLayer.Name = LayerName; //Add the raster layer to ArcMap NPSGlobal.Instance.Document.FocusMap.AddLayer(ThisLayer); NPSGlobal.Instance.Document.ActiveView.Refresh(); }
private static void AddFeatureClassToMap(IFeatureClass gridFeatureClass) { IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = gridFeatureClass; featureLayer.Name = gridFeatureClass.AliasName; featureLayer.Visible = true; ArcMap.Document.ActiveView.FocusMap.AddLayer(featureLayer); FixSymbology(featureLayer); ArcMap.Document.UpdateContents(); //ArcMap.Document.ActiveView.Extent = ((IGeoDataset)featureLayer).Extent; ArcMap.Document.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); }
private void OpenDataset() { if (null == m_hookHelper || null == m_workspace) return; if (string.Empty == (string)lstFeatureClasses.SelectedItem) return; //get the selected item from the listbox string dataset = (string)lstFeatureClasses.SelectedItem; //cast the workspace into a feature workspace IFeatureWorkspace featureWorkspace = m_workspace as IFeatureWorkspace; if (null == featureWorkspace) return; //get a featureclass (or standalone table) from the workspace ITable table = featureWorkspace.OpenTable(dataset) as ITable; if (table == null) { System.Windows.Forms.MessageBox.Show("Failed to open " + dataset); return; } // figure out if it is a table or featureclass IFeatureClass featureClass = table as IFeatureClass; if (featureClass == null) { // add as table IStandaloneTableCollection tableCollection = m_hookHelper.FocusMap as IStandaloneTableCollection; IStandaloneTable standaloneTable = new StandaloneTableClass(); standaloneTable.Name = ((IDataset)table).Name; standaloneTable.Table = table; tableCollection.AddStandaloneTable(standaloneTable); m_hookHelper.ActiveView.ContentsChanged(); } else { // add as feature class IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = featureClass.AliasName; featureLayer.FeatureClass = featureClass; m_hookHelper.FocusMap.AddLayer((ILayer)featureLayer); } }
//初始化 private bool InitializeNetworkAndMap(IFeatureDataset Featuredataset,System.Collections.ArrayList array1,System.Collections.ArrayList array2,int flag) { IFeatureClassContainer ipFeatureClassContainer; IFeatureClass ipFeatureClass; IGeoDataset ipGeoDataset; ILayer ipLayer; IFeatureLayer ipFeatureLayer; IEnvelope ipEnvelope, ipMaxEnvelope; double dblSearchTol; INetworkCollection ipNetworkCollection = Featuredataset as INetworkCollection; int count = ipNetworkCollection.GeometricNetworkCount; barrierarray1 =(System.Collections.ArrayList)array1.Clone(); barrierarray2 = (System.Collections.ArrayList)array2.Clone(); barrierflag = flag; //获取几何网络工作空间 m_ipGeometricNetwork = ipNetworkCollection.get_GeometricNetwork(0); INetwork ipNetwork = m_ipGeometricNetwork.Network; if (m_ipMap != null) { m_ipMap = new MapClass(); ipFeatureClassContainer = m_ipGeometricNetwork as IFeatureClassContainer; count = ipFeatureClassContainer.ClassCount; for (int i = 0; i < count; i++) { ipFeatureClass = ipFeatureClassContainer.get_Class(i); ipFeatureLayer = new FeatureLayerClass(); ipFeatureLayer.FeatureClass = ipFeatureClass; m_ipMap.AddLayer(ipFeatureLayer); } } count = m_ipMap.LayerCount; ipMaxEnvelope = new EnvelopeClass(); for (int i = 0; i < count; i++) { ipLayer = m_ipMap.get_Layer(i); ipFeatureLayer = ipLayer as IFeatureLayer; ipGeoDataset = ipFeatureLayer as IGeoDataset; ipEnvelope = ipGeoDataset.Extent; ipMaxEnvelope.Union(ipEnvelope); } m_ipPointToEID = new PointToEIDClass(); m_ipPointToEID.SourceMap = m_ipMap; m_ipPointToEID.GeometricNetwork = m_ipGeometricNetwork; double dblWidth = ipMaxEnvelope.Width; double dblHeight = ipMaxEnvelope.Height; if (dblWidth > dblHeight) dblSearchTol = dblWidth / 100; else dblSearchTol = dblHeight / 100; m_ipPointToEID.SnapTolerance = dblSearchTol; return true; }
protected override void OnClick() { try { List<ESRI.ArcGIS.Geometry.IPoint> Flags; List<ESRI.ArcGIS.Geometry.IPoint> Barriers; IWorkspace pWS; IFields pFields; IPoint pNPt; Globals.getFlagsBarriers(ArcMap.Application, out Flags, out Barriers); // Open the Workspace if ((pWS = Globals.GetInMemoryWorkspaceFromTOC(ArcMap.Document.FocusMap)) == null) { pWS = Globals.CreateInMemoryWorkspace(); } pFields = Globals.createFeatureClassFields(ArcMap.Document.FocusMap.SpatialReference, esriGeometryType.esriGeometryPoint); IFeatureClass pFlagsFC = Globals.createFeatureClassInMemory(A4LGSharedFunctions.Localizer.GetString("ExportFlagsName"), pFields, pWS, esriFeatureType.esriFTSimpleJunction); IFeatureClass pBarriersFC = Globals.createFeatureClassInMemory(A4LGSharedFunctions.Localizer.GetString("ExportBarriersName"), pFields, pWS, esriFeatureType.esriFTSimpleJunction); IFeatureCursor pntInsertCurs = pFlagsFC.Insert(true); IFeatureBuffer pFBuf; IFeature pFeat; foreach (ESRI.ArcGIS.Geometry.IPoint pnt in Flags) // Loop through List with foreach { pFBuf = pFlagsFC.CreateFeatureBuffer(); pFeat = (IFeature)pFBuf; pNPt = new ESRI.ArcGIS.Geometry.PointClass(); pNPt.X = pnt.X; pNPt.Y = pnt.Y; pFeat.Shape = pNPt; pntInsertCurs.InsertFeature(pFBuf); } pntInsertCurs = pBarriersFC.Insert(true); foreach (ESRI.ArcGIS.Geometry.IPoint pnt in Barriers) // Loop through List with foreach { pFBuf = pBarriersFC.CreateFeatureBuffer(); pFeat = (IFeature)pFBuf; pNPt = new ESRI.ArcGIS.Geometry.PointClass(); pNPt.X = pnt.X; pNPt.Y = pnt.Y; pFeat.Shape = pNPt; pntInsertCurs.InsertFeature(pFBuf); } IFeatureLayer pFlagsLayer = new FeatureLayerClass(); pFlagsLayer.FeatureClass = pFlagsFC; pFlagsLayer.Name = A4LGSharedFunctions.Localizer.GetString("ExportFlagsName"); IFeatureLayer pBarriersLayer = new FeatureLayerClass(); pBarriersLayer.FeatureClass = pBarriersFC; pBarriersLayer.Name = A4LGSharedFunctions.Localizer.GetString("ExportBarriersName"); ArcMap.Document.FocusMap.AddLayer(pFlagsLayer); ArcMap.Document.FocusMap.AddLayer(pBarriersLayer); ArcMap.Document.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { } }
void IGMap.AddLayer(params string[] layer) { IFeatureClass fc = null; SdeConnection conn = new SdeConnection(); ISdeConnectionInfo sdeConn = (ISdeConnectionInfo)conn; IFeatureWorkspace fw = (IFeatureWorkspace)sdeConn.Workspace; for (int i = 0; i < layer.Length; i++) { fc = fw.OpenFeatureClass(layer[i]); IFeatureLayer fl=new FeatureLayerClass(); fl.FeatureClass = fc; fl.Name = fc.AliasName; ILayer l = (ILayer)fl; _mapHook.AddLayer(l, 0); } }
void IGMap.ZoomToSelectMa(string layerName, string fieldName, params object[] key) { bool hasLayer = false; int c = this._mapHook.LayerCount; if (c == 0) { return; } IFeatureClass fc = null; IFeatureLayer fl = null; SdeConnection conn = new SdeConnection(); ISdeConnectionInfo sdeConn = (ISdeConnectionInfo)conn; IFeatureWorkspace fw = (IFeatureWorkspace)sdeConn.Workspace; string name = ""; string queryString = QueryStringBuilder.CreateOrQueryString(fieldName, key); for (int i = 0; i < c; i++) { fl = (IFeatureLayer)this._mapHook.get_Layer(i); name = fl.FeatureClass.AliasName; //MessageBox.Show(string.Format("line 260 GMap name={0} - layername={1}", name,layerName)); if (Compare.Compare2SdeLayerName(name, layerName) == 0) { hasLayer = true; //MessageBox.Show(string.Format("line 261 GMap layername={0}", name)); fc = fl.FeatureClass; break; } } if (!hasLayer) { try { fc = fw.OpenFeatureClass(layerName); } catch (Exception) { return; } fl = new FeatureLayerClass(); fl.FeatureClass = fc; fl.Name = fc.AliasName; ILayer layer = (ILayer)fl; this._mapHook.AddLayer(layer, 0); } if (fl == null) { //MessageBox.Show(string.Format("line 285 GMap")); return; } IQueryFilter qrf = new QueryFilterClass(); qrf.WhereClause = queryString; //MessageBox.Show(string.Format("line 290 GMap, qrf={0}",queryString)); ISelectionSet sls = fc.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, sdeConn.Workspace); IFeatureSelection fts = (IFeatureSelection)fl; fts.SelectionSet = sls; //MessageBox.Show(string.Format("selection count={0}", sls.Count)); _mapHook.ActiveView.Refresh(); ((IGMap)this).ZoomToSelected(); }
private void 添加面形地物ToolStripMenuItem_Click(object sender, EventArgs e) { //创建要素类 #region 创建新的内存工作空间 IWorkspaceFactory pWSF = new InMemoryWorkspaceFactoryClass(); IWorkspaceName pWSName = pWSF.Create("", "Temp", null, 0); IName pName = (IName)pWSName; IWorkspace pMemoryWS = (IWorkspace)pName.Open(); #endregion IField oField = new FieldClass(); IFields oFields = new FieldsClass(); IFieldsEdit oFieldsEdit = null; IFieldEdit oFieldEdit = null; IFeatureClass oFeatureClass = null; IFeatureLayer oFeatureLayer = null; oFieldsEdit = oFields as IFieldsEdit; oFieldEdit = oField as IFieldEdit; oFieldEdit.Name_2 = "OBJECTID"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; oFieldEdit.IsNullable_2 = false; oFieldEdit.Required_2 = false; oFieldsEdit.AddField(oField); oField = new FieldClass(); oFieldEdit = oField as IFieldEdit; IGeometryDef pGeoDef = new GeometryDefClass(); IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.AvgNumPoints_2 = 5; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; pGeoDefEdit.GridCount_2 = 1; pGeoDefEdit.HasM_2 = false; pGeoDefEdit.HasZ_2 = false; pGeoDefEdit.SpatialReference_2 = axMapControl1.SpatialReference; oFieldEdit.Name_2 = "SHAPE"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; oFieldEdit.GeometryDef_2 = pGeoDef; oFieldEdit.IsNullable_2 = true; oFieldEdit.Required_2 = true; oFieldsEdit.AddField(oField); oField = new FieldClass(); oFieldEdit = oField as IFieldEdit; oFieldEdit.Name_2 = "Code"; oFieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; oFieldEdit.IsNullable_2 = true; oFieldsEdit.AddField(oField); //创建要素类 oFeatureClass = (pMemoryWS as IFeatureWorkspace).CreateFeatureClass("Temp", oFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); oFeatureLayer = new FeatureLayerClass(); oFeatureLayer.Name = "PolygonLayer"; oFeatureLayer.FeatureClass = oFeatureClass; //创建唯一值符号化对象 IUniqueValueRenderer pURender = new UniqueValueRendererClass(); pURender.FieldCount = 1; pURender.set_Field(0, "Code"); pURender.UseDefaultSymbol = false; ISimpleFillSymbol pFillSym = new SimpleFillSymbolClass(); pFillSym.Style = esriSimpleFillStyle.esriSFSSolid; //半透明颜色 IRgbColor pColor = new RgbColorClass(); pColor.Red = 255; pColor.Green = 255; pFillSym.Color = pColor; pURender.AddValue("1", "", pFillSym as ISymbol); pFillSym = new SimpleFillSymbolClass(); pFillSym.Style = esriSimpleFillStyle.esriSFSSolid; //唯一值符号化内存图层 (oFeatureLayer as IGeoFeatureLayer).Renderer = pURender as IFeatureRenderer; ILayerEffects pLyrEffect = oFeatureLayer as ILayerEffects; //透明度 pLyrEffect.Transparency = 0; this.axMapControl1.AddLayer(oFeatureLayer, axMapControl1.LayerCount); insertPolygon = true; }
protected override void calculate() { #region khoi dau base.calculate(); CalculationEventArg evt = new CalculationEventArg(); //evt.Type = EnumTypeOfLoopCalculation.InListCalculators; evt.CurrentIndexCalculator = this._index; evt.Log = string.Format("********** Bắt đầu tính cho thửa nông nghiệp ở vị trí {0} ********", vitri); onCalculating(evt); #endregion //[thaydoi] - them cac khai bao can thiet //************************************ #region khai bao cac bien //Lay connection info hien tai SdeConnection conn = new SdeConnection(); ISdeConnectionInfo sdeConn = conn as ISdeConnectionInfo; IWorkspaceEdit wspEdit = (IWorkspaceEdit)sdeConn.Workspace; this._fcName = new TnFeatureClassName(sdeConn.Workspace); this._tblName = new TnTableName(sdeConn.Workspace); IFeatureWorkspace fw = (IFeatureWorkspace)sdeConn.Workspace; ICopyFeatures copyTool = new DataManager(sdeConn.Workspace,sdeConn.Environment); #region thua string thuaName = string.Format("{0}_{1}", DataNameTemplate.Thua, this._currentConfig.NamApDung); _fcName.FC_THUA.NAME = thuaName; _fcName.FC_THUA.InitIndex(); IFeatureClass thuaFeatureClass = fw.OpenFeatureClass(thuaName); IFeatureLayer thuaFeatureLayer = new FeatureLayerClass(); thuaFeatureLayer.FeatureClass = thuaFeatureClass; IFeatureSelection thuaFeatureSelection; #endregion #region xa IFeatureClass xaFeatureClass = fw.OpenFeatureClass(DataNameTemplate.Ranh_Xa_Poly); IFeatureLayer xaFeatureLayer = new FeatureLayerClass(); xaFeatureLayer.FeatureClass = xaFeatureClass; IFeatureSelection xaFeatureSelection; #endregion #region duong IFeatureClass duongFeatureClass = fw.OpenFeatureClass(DataNameTemplate.Duong); IFeatureLayer duongFeatureLayer = new FeatureLayerClass(); duongFeatureLayer.FeatureClass = duongFeatureClass; IFeatureSelection duongFeatureSelection; //_fcName.FC_DUONG.InitIndex(); #endregion #region thua gia dat string tgd = string.Format("{0}_{1}", DataNameTemplate.Thua_Gia_Dat_Draft, this._currentConfig.NamApDung); _fcName.FC_THUA_GIADAT_DRAFT.NAME = tgd; _fcName.FC_THUA_GIADAT_DRAFT.InitIndex(); //_fcName.FC_THUA_GIADAT_DRAFT.NAME = tgd; //_fcName.FC_THUA_GIADAT_DRAFT.InitIndex(); IFeatureClass tgdFeatureClass=null; try { tgdFeatureClass = fw.OpenFeatureClass(tgd); } catch (Exception exc) { evt.Log = string.Format("Không tìm thấy lớp dữ liệu: {0}", tgd); onCalculating(evt); onFinished(evt); return; } ITable tblThuaGiaDat = (ITable)tgdFeatureClass; IFeatureLayer tgdFeatureLayer = new FeatureLayerClass(); ISDETableEditor sdeTblTgdEditor = new SDETable(tblThuaGiaDat, sdeConn.Workspace); #endregion #region gia dat duong //string gdd = string.Format("{0}_{1}", DataNameTemplate.Gia_Dat_Duong, this._currentConfig.NamApDung); //_tblName.GIA_DAT_DUONG.NAME = gdd; //_tblName.GIA_DAT_DUONG.InitIndex(); #endregion #region ten duong ITable tblTenDuong; try { tblTenDuong = fw.OpenTable(DataNameTemplate.Ten_Duong); } catch (Exception exc) { evt.Log = string.Format("Không tìm thấy lớp dữ liệu: {0}", DataNameTemplate.Ten_Duong); onCalculating(evt); onFinished(evt); return; } #endregion #region loai dat ITable tblLoaiDat; try { tblLoaiDat = fw.OpenTable(DataNameTemplate.Loai_Dat); } catch (Exception exc) { evt.Log = string.Format("Không tìm thấy lớp dữ liệu: {0}", DataNameTemplate.Loai_Dat); onCalculating(evt); onFinished(evt); return; } #endregion #region he so vi tri ITable tblHesoVitri; try { tblHesoVitri = fw.OpenTable(DataNameTemplate.He_So_K); } catch (Exception exc) { evt.Log = string.Format("Không tìm thấy lớp dữ liệu: {0}", DataNameTemplate.He_So_K); onCalculating(evt); onFinished(evt); return; } #endregion #region khac IQueryFilter qrf = new QueryFilterClass(); bool result = false; int sothuatimthay = 0; int sothuatinhduoc = 0; int sothuaKhongTinhDuoc = 0; #endregion #endregion //************************************ //******************************************* //=========================================== //=========================================== #region bat dau tinh //[thaydoi] - cac may tinh khac chi can thay dieu kien truy van he so vi tri //****************************************************************** #region lay cac quy tac tim vi tri #region log--- evt.Log = string.Format("\n----Lấy các quy tắc tìm vị trí thửa từ bảng {0}, ứng với hệ số {1} ...", DataNameTemplate.He_So_K, TnHeSoK.DatNongNghiepVt1); onCalculating(evt); #endregion qrf.WhereClause = string.Format("{0}='{1}'", "hesovitri", TnHeSoK.DatNongNghiepVt1); ICursor cur = tblHesoVitri.Search(qrf, false); string quytac = ""; string cachtinh = ""; string cachtinhdongia = ""; try { IRow row = cur.NextRow(); if (row != null) { quytac = row.get_Value(_tblName.HESO_VITRI.GetIndex(_tblName.HESO_VITRI.QUY_TAC)).ToString(); cachtinh = row.get_Value(_tblName.HESO_VITRI.GetIndex(_tblName.HESO_VITRI.CACH_TINH)).ToString(); cachtinhdongia = row.get_Value(_tblName.HESO_VITRI.GetIndex(_tblName.HESO_VITRI.CACH_TINH_DON_GIA)).ToString(); } } catch { } finally { Marshal.ReleaseComObject(cur); } #endregion #region tinh theo xa if (this._inputParams.MA_XA != "-1") { //[kodoi] //======================= #region chon xa co ma dang xet //neu dang tinh cho 1 xa if (_inputParams.MA_XA != "*") { qrf.WhereClause = string.Format("{0}='{1}'", _fcName.FC_RANH_XA_POLY.MA_XA, _inputParams.MA_XA); } else//neu dang tinh cho toan huyen { qrf.WhereClause = ""; } ISelectionSet xaSelectionSet = xaFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionOnlyOne, sdeConn.Workspace); xaFeatureSelection = (IFeatureSelection)xaFeatureLayer; xaFeatureSelection.SelectionSet = xaSelectionSet; #endregion //======================= #region vong lap tung xa //[thaydoi] - co the them bien chay //************************* #region khoi dau IEnumIDs xaIds = xaSelectionSet.IDs; int xaId = 0; IFeature xaFt = null; List<object> lstMaDuong = new List<object>(); #endregion //************************* while ((xaId = xaIds.Next()) != -1) { //[kodoi] //======================= #region lay thong tin xa xaFt = xaFeatureClass.GetFeature(xaId); string maxa = xaFt.get_Value(xaFt.Fields.FindField(_fcName.FC_RANH_XA_POLY.MA_XA)).ToString(); string tenxa = xaFt.get_Value(xaFt.Fields.FindField(_fcName.FC_RANH_XA_POLY.TEN_XA)).ToString(); string loaixa = xaFt.get_Value(xaFt.Fields.FindField(_fcName.FC_RANH_XA_POLY.MA_LOAI_XA)).ToString(); #endregion #region -----log evt.Log = string.Format("\n************************************************"); evt.Log += string.Format("\n****** Đang tính cho xã/phường: {0} ******", tenxa); evt.Log += string.Format("\n************************************************"); onCalculating(evt); #endregion #region tim duong trong khu vuc do thi bang qua xa //chon xa dang xet qrf.WhereClause = string.Format("{0}='{1}'", _fcName.FC_RANH_XA_POLY.OID, xaId); xaSelectionSet = xaFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionOnlyOne, sdeConn.Workspace); xaFeatureSelection = (IFeatureSelection)xaFeatureLayer; xaFeatureSelection.SelectionSet = xaSelectionSet; //Chon cac duong co do rong theo quy dinh qrf.WhereClause = "";//string.Format("{0}='{1}'", _fcName.FC_DUONG.PHAN_LOAI, _isDothi);// "maduong='2'"; ISelectionSet duongSelectionSet = duongFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, sdeConn.Workspace); duongFeatureSelection = (IFeatureSelection)duongFeatureLayer; duongFeatureSelection.SelectionSet = duongSelectionSet; //bat dau truy van khong gian _qrBl.FromLayer = duongFeatureLayer; _qrBl.ByLayer = xaFeatureLayer; _qrBl.LayerSelectionMethod = esriLayerSelectionMethod.esriLayerSelectIntersect; _qrBl.ResultType = esriSelectionResultEnum.esriSelectionResultAnd; _qrBl.UseSelectedFeatures = true; duongSelectionSet = _qrBl.Select(); #endregion //======================= #region vong lap xet tung duong //[thaydoi] - co the them bien chay //=============================== #region khoi dau IEnumIDs eIds = duongSelectionSet.IDs; int duongId; IFeature ftDuong; int iDuong = 0; int progressingTotalCount = 1; evt.Reset(); evt.ProgressingTotal = duongSelectionSet.Count; onCalculating(evt); #endregion //================================ while ((duongId = eIds.Next()) != -1) { //[kodoi] //====================== #region log----- evt.Reset(); evt.ProgressingTotalCount = progressingTotalCount; onCalculating(evt); progressingTotalCount++; #endregion //====================== //[capnhat] - lay ten duong tu bang ten duong //++++++++++++++++++++++++ #region lay thong tin cua duong dang xet ftDuong = duongFeatureClass.GetFeature(duongId); double dorongDuong; result = double.TryParse(ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.DO_RONG)).ToString(), out dorongDuong); if (!result) { dorongDuong = 0; } if (dorongDuong < _currentConfig.DRongDuongVitri1Nn) { continue; } string tenduong = "";//ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.TEN_DUONG)).ToString(); object maduong = ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.MA_DUONG)); lstMaDuong.Add(maduong); string batdau = "";// ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.BAT_DAU)).ToString(); string ketthuc = "";// ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.KET_THUC)).ToString(); #endregion //++++++++++++++++++++++++ //[kodoi] //Chon duong dang xet, buoc này de ra layer duong dung de truy van khong gian cac thua dat //==================== #region chon duong dang xet qrf.WhereClause = string.Format("{0}='{1}'", _fcName.FC_DUONG.OID, duongId); duongSelectionSet = duongFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionOnlyOne, sdeConn.Workspace); duongFeatureSelection = (IFeatureSelection)duongFeatureLayer; duongFeatureSelection.SelectionSet = duongSelectionSet; #endregion //==================== //tim cac thua theo dieu kien mat tien #region tinh vi tri cho cac thua //doc cach tim thua trong bang he so vi tri //lay cach tim cho dat o //truyen thong so cach tinh,thualayer,duonglayer,khoangcach //MessageBox.Show(func); //func = "ChongLop([INTERSECT],[NEW_SELECTION],1) Then ChongLop([CONTAINED_BY],[AND_SELECTION],50)"; //[kodoi] //============================ #region tim cac thua theo vi tri quy dinh thuaFeatureSelection = (IFeatureSelection)thuaFeatureLayer; thuaFeatureSelection.Clear(); Evaluation eval = new Evaluation(quytac); eval.ThuaLayer = thuaFeatureLayer; eval.DuongLayer = duongFeatureLayer; eval.EvaluateQuery(); //thuaFeatureSelection = (IFeatureSelection)thuaFeatureLayer; ISelectionSet thuaSelectionSet = thuaFeatureSelection.SelectionSet; #endregion //============================ //MessageBox.Show(thuaSelectionSet.Count.ToString()); #endregion //[kodoi] //============================ #region ----log if (thuaSelectionSet.Count == 0) { evt.Log = string.Format("\n !!! Không tìm thấy thửa nào tiếp giáp với đường {0} đoạn từ {1} đến {2} và nằm trong vùng buffer 50m", tenduong, batdau, ketthuc); onCalculating(evt); #region report progressing duong if (iDuong < duongSelectionSet.Count) { decimal i = (decimal)iDuong % (decimal)duongSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iDuong++; #endregion continue; } #endregion sothuatimthay += thuaSelectionSet.Count; //============================ #region xet tung thua //[thaydoi] - co the them bien chay //******************** #region khoi dau IEnumIDs thuaIds = thuaSelectionSet.IDs; int thuaId; IFeature thuaFt; int iThua = 0; List<object[,]> pairColValTgd = new List<object[,]>(); int rowTgdNnHandleUpdate = 0; List<object> newId = new List<object>(); #endregion //******************** while ((thuaId = thuaIds.Next()) != -1) { int hesoVitri = TnHeSoK.DatNongNghiepVt1; //[thaydoi] - co them them dieu kien de xac dinh vi tri cua thua //*********************************** #region lay thong tin thua dang xet //[kodoi] //============================ #region lay thong tin co ban thuaFt = thuaFeatureClass.GetFeature(thuaId); //neu thua bi khoa tim vi tri,bo qua,xet thua ke string lockTimVitri = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.LOCKED)).ToString(); if (lockTimVitri == "1") { sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } //neu thua ko thuoc xa dang xet thi ko tinh tiep object mathua = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.MA_THUA)); object maxaThua = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.MA_XA)); object dientichpl = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.DIEN_TICH)); #endregion //============================ //[kodoi] //============================ #region kiem tra maxa if (maxaThua.ToString() == "" || maxaThua == null) { maxaThua = "0"; #region ----log evt.Log = string.Format("Chưa xác định mã xã cho thửa {0}", mathua); #endregion sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } #region danh rieng khi tinh theo xa else if (maxaThua.ToString() != maxa) { #region ----log evt.Reset(); evt.Log = string.Format("thửa {0} không thuộc xã {1}", mathua, tenxa); onCalculating(evt); #endregion sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } #endregion #endregion //============================ #region lay loai dat //neu ko co dat phi nong nghiep thi bo qua,xet thua ke //neu co dat nong nghiep thi datnn=true //neu la dat hon hop, neu co dat sxkd thi datsxkd=true, //neu co dat o thi codato=true //cac truong hop he so vi tri: //o:3010, sxkd:4010, o+nn:5010, o+sxkd:6010 string loaidat = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.LOAI_DAT)).ToString(); //evt.Log = string.Format("\n loai dat cua thua {0} la {1}", thuaId, loaidat); //onCalculating(evt); //[thaydoi] - may tinh dat nong nghiep co the khac //*********************** #region kiem tra dat nong nghiep bool codatnn = false; object datnn = ""; foreach (string s in TnLoaiDats.NONG_NGHIEP) { if (loaidat == s) { codatnn = true; datnn = s; break; } else { codatnn = false; } } if (!codatnn) { sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } #endregion //*********************** #endregion #endregion //*********************************** //[thaydoi] - thay doi he so vi tri phu hop //*********************************** #region quyet dinh he so vi tri cho thua if (codatnn) { hesoVitri = TnHeSoK.DatNongNghiepVt1; } else { hesoVitri = TnHeSoK.KhongXacDinh; } #endregion //*********************************** //[thaydoi] - thay doi dieu kien truy van ung voi tung may tinh khac nhau //*********************************** #region kiem tra trong bang thua_giadat, voi dieu kien:mathua,maduong,hesovitri,khoagia=0 evt.Reset(); evt.Log = string.Format("\n[!]--- Kiểm tra các vị trí, cập nhật vị trí mới cho thửa {0} ...", mathua); onCalculating(evt); qrf.WhereClause = string.Format("({0}='{1}' or {2} is null) and {3}='{4}' and {5}='{6}' and {7}='{8}'", _fcName.FC_THUA_GIADAT_DRAFT.LOCKED, 0, _fcName.FC_THUA_GIADAT_DRAFT.LOCKED, _fcName.FC_THUA_GIADAT_DRAFT.MA_THUA, mathua, _fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG, maduong, _fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K, hesoVitri); ICursor tgdFcs = tblThuaGiaDat.Search(qrf, false); IRow tgdRow = null; //MessageBox.Show(string.Format("line 1401 CalcPosThuaMattien - bat dau try, query:\n{0}", qrf.WhereClause)); try { tgdRow = tgdFcs.NextRow();//dam bao la chi co 1 hang ket qua if (tgdRow != null) { //MessageBox.Show("co"); //kiem tra co cho phep tinh lai vi tri //neu co:xoa feater cu,them feature moi #region xet thua da co vi tri bool isOverWritePos = true; if (!isOverWritePos) { newId.Add(tgdRow.OID); //continue; } else { //[kodoi] //=================== #region xoa feature cu wspEdit.StartEditing(true); wspEdit.StartEditOperation(); //qrf.WhereClause = string.Format("{0}='{1}'", "OBJECTID", tgdRow.OID); //tblThuaGiaDat.DeleteSearchedRows(qrf); tgdRow.Delete(); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); #endregion //=================== //[thaydoi] - them gia tri //********************** #region them feature moi wspEdit.StartEditing(true); wspEdit.StartEditOperation(); object copiedId = copyTool.Copy(thuaFt, tgdFeatureClass); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); //them gia tri mathua,maduong,hesovitri pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.MA_THUA), mathua } }); pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG), maduong } }); pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K), hesoVitri } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.DIEN_TICH_PHAP_LY), dientichpl } }); sdeTblTgdEditor.CacheData(copiedId, rowTgdNnHandleUpdate, pairColValTgd, EnumTypeOfEdit.UPDATE); rowTgdNnHandleUpdate++; pairColValTgd.Clear(); newId.Add(copiedId); #endregion //********************** } #endregion } else { //MessageBox.Show("ko co"); //[thaydoi] - them cac gia tri thich hop vao thua_giadat //*********************************** #region them feature moi wspEdit.StartEditing(true); wspEdit.StartEditOperation(); object copiedId = copyTool.Copy(thuaFt, tgdFeatureClass); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); //them gia tri mathua,maduong,hesovitri pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.MA_THUA), mathua } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG), maduong } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K), hesoVitri } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.DIEN_TICH_PHAP_LY), dientichpl } }); sdeTblTgdEditor.CacheData(copiedId, rowTgdNnHandleUpdate, pairColValTgd, EnumTypeOfEdit.UPDATE); rowTgdNnHandleUpdate++; pairColValTgd.Clear(); newId.Add(copiedId); #endregion //*********************************** } //MessageBox.Show(newId.Count.ToString()); } catch (Exception e1) { MessageBox.Show(string.Format("CalcPosThuaMattien, line 1448-\n{0}", e1)); } finally { Marshal.ReleaseComObject(tgdFcs); } #endregion //*********************************** #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion } #endregion //[kodoi] //============================ #region luu thong tin vao bang gia dat if (!sdeTblTgdEditor.IsEditing()) { sdeTblTgdEditor.StartEditing(true); sdeTblTgdEditor.StartEditOperation(); } #region ----log evt.Log = string.Format("\n----||| Đang lưu vị trí các thửa vào bảng {0} |||---- ", tgd); onCalculating(evt); #endregion sdeTblTgdEditor.SaveEdit(); sdeTblTgdEditor.StopEditOperation(); sdeTblTgdEditor.StopEditing(true); #region ----log evt.Log = string.Format("\n----||| Đã lưu vị trí các thửa vào bảng {0} |||---- ", tgd); onCalculating(evt); #endregion #endregion #region tinh gia dat cho cac thua vua them vi tri CalcLandprice calc = new CalcLandprice(this); //MessageBox.Show(string.Format("final:{0}", newId.Count)); calc.Maduong = maduong; calc.Calculate(newId); newId.Clear(); #endregion //============================ } #endregion } #endregion } #endregion //===================================================================== //===================================================================== #region tinh theo duong,doan duong else { #region timduong co ten dang xet //tinh theo doan duong #region tinh theo doan duong if (_inputParams.MA_DUONG != "-1") { qrf.WhereClause = string.Format("{0}={1}", _fcName.FC_DUONG.MA_DUONG, _inputParams.MA_DUONG);// "maduong='2'"; #region ----log evt.Log = string.Format("\n************************************************"); evt.Log += string.Format("\n****** Đang tính cho đoạn đường có mã: {0} ******", _inputParams.MA_DUONG); evt.Log += string.Format("\n************************************************"); onCalculating(evt); #endregion } #endregion //tinh cho 1 duong #region tinh cho 1 duong else if (_inputParams.TEN_DUONG != "" && _inputParams.TEN_DUONG != "*") { //phai sua lai thiet ke //dung relationshipclass many to many gia duong va ten duong #region tim trong bang ten duong qrf.WhereClause = string.Format("{0}=N'{1}'", _tblName.TEN_DUONG.TEN_DUONG, _inputParams.TEN_DUONG); //MessageBox.Show(string.Format("line 908 CalPosThuaNnVt1, tenduong={0}", _inputParams.TEN_DUONG)); ICursor tenduongCur = tblTenDuong.Search(qrf, false); object idDuong; List<object> lstIdDuong=new List<object>(); try { IRow tenduongRow = null; while ((tenduongRow = tenduongCur.NextRow()) != null) { idDuong = tenduongRow.get_Value(tenduongRow.Fields.FindField(_tblName.TEN_DUONG.MA_DUONG)); lstIdDuong.Add(idDuong); } } catch { } finally{Marshal.ReleaseComObject(tenduongCur);} #endregion #region tim trong bang duong string q = ""; for (int i = 0; i < lstIdDuong.Count; i++) { if (i == lstIdDuong.Count - 1) { q +=string.Format("{0}='{1}'",_fcName.FC_DUONG.MA_DUONG,lstIdDuong[i]); } else { q += string.Format("{0}='{1}' or ", _fcName.FC_DUONG.MA_DUONG, lstIdDuong[i]); } } qrf.WhereClause = q;// "maduong='2'"; #region ----log evt.Log = string.Format("\n************************************************"); evt.Log += string.Format("\n****** Đang tính cho cả đường: {0} ******", _inputParams.TEN_DUONG); evt.Log += string.Format("\n************************************************"); onCalculating(evt); #endregion #endregion } #endregion //tinh cho ca duong else { qrf.WhereClause = ""; } //MessageBox.Show(string.Format("whereclause:{0}",duong.QueryFilter.WhereClause)); ISelectionSet duongSelectionSet = duongFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, sdeConn.Workspace); if (duongSelectionSet.Count == 0) { return; } duongFeatureSelection = (IFeatureSelection)duongFeatureLayer; duongFeatureSelection.SelectionSet = duongSelectionSet; #endregion #region vong lap xet tung duong //[thaydoi] - co the them bien chay //=============================== #region khoi dau IEnumIDs eIds = duongSelectionSet.IDs; int duongId; IFeature ftDuong; int iDuong = 0; int progressingTotalCount = 1; evt.Reset(); evt.ProgressingTotal = duongSelectionSet.Count; onCalculating(evt); List<object> lstMaDuong = new List<object>(); #endregion //================================ while ((duongId = eIds.Next()) != -1) { //[kodoi] //====================== #region log----- evt.Reset(); evt.ProgressingTotalCount = progressingTotalCount; onCalculating(evt); progressingTotalCount++; #endregion //====================== //[capnhat] - lay ten duong tu bang ten duong //++++++++++++++++++++++++ #region lay thong tin cua duong dang xet ftDuong = duongFeatureClass.GetFeature(duongId); double dorongDuong; result = double.TryParse(ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.DO_RONG)).ToString(), out dorongDuong); if (!result) { dorongDuong = 0; } if (dorongDuong < _currentConfig.DRongDuongVitri1Nn) { continue; } string tenduong = "";//ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.TEN_DUONG)).ToString(); object maduong = ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.MA_DUONG)); lstMaDuong.Add(maduong); string batdau = "";// ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.BAT_DAU)).ToString(); string ketthuc = "";// ftDuong.get_Value(_fcName.FC_DUONG.GetIndex(_fcName.FC_DUONG.KET_THUC)).ToString(); #endregion //++++++++++++++++++++++++ //[kodoi] //Chon duong dang xet, buoc này de ra layer duong dung de truy van khong gian cac thua dat //==================== #region chon duong dang xet qrf.WhereClause = string.Format("{0}='{1}'", _fcName.FC_DUONG.OID, duongId); duongSelectionSet = duongFeatureClass.Select(qrf, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionOnlyOne, sdeConn.Workspace); duongFeatureSelection = (IFeatureSelection)duongFeatureLayer; duongFeatureSelection.SelectionSet = duongSelectionSet; #endregion //==================== //tim cac thua theo dieu kien mat tien #region tinh vi tri cho cac thua //doc cach tim thua trong bang he so vi tri //lay cach tim cho dat o //truyen thong so cach tinh,thualayer,duonglayer,khoangcach //MessageBox.Show(func); //func = "ChongLop([INTERSECT],[NEW_SELECTION],1) Then ChongLop([CONTAINED_BY],[AND_SELECTION],50)"; //[kodoi] //============================ #region tim cac thua theo vi tri quy dinh thuaFeatureSelection = (IFeatureSelection)thuaFeatureLayer; thuaFeatureSelection.Clear(); Evaluation eval = new Evaluation(quytac); eval.ThuaLayer = thuaFeatureLayer; eval.DuongLayer = duongFeatureLayer; eval.EvaluateQuery(); //thuaFeatureSelection = (IFeatureSelection)thuaFeatureLayer; ISelectionSet thuaSelectionSet = thuaFeatureSelection.SelectionSet; #endregion //============================ //MessageBox.Show(thuaSelectionSet.Count.ToString()); #endregion //[kodoi] //============================ #region ----log if (thuaSelectionSet.Count == 0) { evt.Log = string.Format("\n !!! Không tìm thấy thửa nào tiếp giáp với đường {0} đoạn từ {1} đến {2} và nằm trong vùng buffer 50m", tenduong, batdau, ketthuc); onCalculating(evt); #region report progressing duong if (iDuong < duongSelectionSet.Count) { decimal i = (decimal)iDuong % (decimal)duongSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iDuong++; #endregion continue; } #endregion sothuatimthay += thuaSelectionSet.Count; //============================ #region xet tung thua //[thaydoi] - co the them bien chay //******************** #region khoi dau IEnumIDs thuaIds = thuaSelectionSet.IDs; int thuaId; IFeature thuaFt; int iThua = 0; List<object[,]> pairColValTgd = new List<object[,]>(); int rowTgdNnHandleUpdate = 0; List<object> newId = new List<object>(); #endregion //******************** while ((thuaId = thuaIds.Next()) != -1) { int hesoVitri = TnHeSoK.DatNongNghiepVt1; //[thaydoi] - co them them dieu kien de xac dinh vi tri cua thua //*********************************** #region lay thong tin thua dang xet //[kodoi] //============================ #region lay thong tin co ban thuaFt = thuaFeatureClass.GetFeature(thuaId); //neu thua bi khoa tim vi tri,bo qua,xet thua ke string lockTimVitri = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.LOCKED)).ToString(); if (lockTimVitri == "1") { sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } //neu thua ko thuoc xa dang xet thi ko tinh tiep object mathua = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.MA_THUA)); object maxaThua = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.MA_XA)); object dientichpl = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.DIEN_TICH)); #endregion //============================ //[kodoi] //============================ #region kiem tra maxa if (maxaThua.ToString() == "" || maxaThua==null) { maxaThua = "0"; #region ----log evt.Log = string.Format("Chưa xác định mã xã cho thửa {0}", mathua); #endregion sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } #endregion //============================ #region lay loai dat //neu ko co dat phi nong nghiep thi bo qua,xet thua ke //neu co dat nong nghiep thi datnn=true //neu la dat hon hop, neu co dat sxkd thi datsxkd=true, //neu co dat o thi codato=true //cac truong hop he so vi tri: //o:3010, sxkd:4010, o+nn:5010, o+sxkd:6010 string loaidat = thuaFt.get_Value(thuaFt.Fields.FindField(_fcName.FC_THUA.LOAI_DAT)).ToString(); //evt.Log = string.Format("\n loai dat cua thua {0} la {1}", thuaId, loaidat); //onCalculating(evt); //[thaydoi] - may tinh dat nong nghiep co the khac //*********************** #region kiem tra dat nong nghiep bool codatnn = false; object datnn=""; foreach (string s in TnLoaiDats.NONG_NGHIEP) { if (loaidat==s) { codatnn = true; datnn = s; break; } else { codatnn = false; } } if (!codatnn) { sothuaKhongTinhDuoc++; #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion continue; } #endregion //*********************** #endregion #endregion //*********************************** //[thaydoi] - thay doi he so vi tri phu hop //*********************************** #region quyet dinh he so vi tri cho thua if (codatnn) { hesoVitri = TnHeSoK.DatNongNghiepVt1; } else { hesoVitri = TnHeSoK.KhongXacDinh; } #endregion //*********************************** //[thaydoi] - thay doi dieu kien truy van ung voi tung may tinh khac nhau //*********************************** #region kiem tra trong bang thua_giadat, voi dieu kien:mathua,maduong,hesovitri,khoagia=0 evt.Reset(); evt.Log = string.Format("\n[!]--- Kiểm tra các vị trí, cập nhật vị trí mới cho thửa {0} ...", mathua); onCalculating(evt); qrf.WhereClause = string.Format("({0}='{1}' or {2} is null) and {3}='{4}' and {5}='{6}' and {7}='{8}'", _fcName.FC_THUA_GIADAT_DRAFT.LOCKED, 0, _fcName.FC_THUA_GIADAT_DRAFT.LOCKED, _fcName.FC_THUA_GIADAT_DRAFT.MA_THUA, mathua, _fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG, maduong, _fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K, hesoVitri); ICursor tgdFcs = tblThuaGiaDat.Search(qrf, false); IRow tgdRow = null; //MessageBox.Show(string.Format("line 1401 CalcPosThuaMattien - bat dau try, query:\n{0}", qrf.WhereClause)); try { tgdRow = tgdFcs.NextRow();//dam bao la chi co 1 hang ket qua if (tgdRow != null) { //MessageBox.Show("co"); //kiem tra co cho phep tinh lai vi tri //neu co:xoa feater cu,them feature moi #region xet thua da co vi tri bool isOverWritePos = true; if (!isOverWritePos) { newId.Add(tgdRow.OID); //continue; } else { //[kodoi] //=================== #region xoa feature cu wspEdit.StartEditing(true); wspEdit.StartEditOperation(); //qrf.WhereClause = string.Format("{0}='{1}'", "OBJECTID", tgdRow.OID); //tblThuaGiaDat.DeleteSearchedRows(qrf); tgdRow.Delete(); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); #endregion //=================== //[thaydoi] - them gia tri //********************** #region them feature moi wspEdit.StartEditing(true); wspEdit.StartEditOperation(); object copiedId = copyTool.Copy(thuaFt, tgdFeatureClass); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); //them gia tri mathua,maduong,hesovitri pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.MA_THUA), mathua } }); pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG), maduong } }); pairColValTgd.Add(new object[,] { { tgdRow.Fields.FindField(_fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K), hesoVitri } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.DIEN_TICH_PHAP_LY), dientichpl } }); sdeTblTgdEditor.CacheData(copiedId, rowTgdNnHandleUpdate, pairColValTgd, EnumTypeOfEdit.UPDATE); rowTgdNnHandleUpdate++; pairColValTgd.Clear(); newId.Add(copiedId); #endregion //********************** } #endregion } else { //MessageBox.Show("ko co"); //[thaydoi] - them cac gia tri thich hop vao thua_giadat //*********************************** #region them feature moi wspEdit.StartEditing(true); wspEdit.StartEditOperation(); object copiedId = copyTool.Copy(thuaFt, tgdFeatureClass); wspEdit.StopEditOperation(); wspEdit.StopEditing(true); //them gia tri mathua,maduong,hesovitri pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.MA_THUA), mathua } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.MA_DUONG), maduong } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.HE_SO_K), hesoVitri } }); pairColValTgd.Add(new object[,] { { _fcName.FC_THUA_GIADAT_DRAFT.GetIndex(_fcName.FC_THUA_GIADAT_DRAFT.DIEN_TICH_PHAP_LY), dientichpl } }); sdeTblTgdEditor.CacheData(copiedId, rowTgdNnHandleUpdate, pairColValTgd, EnumTypeOfEdit.UPDATE); rowTgdNnHandleUpdate++; pairColValTgd.Clear(); newId.Add(copiedId); #endregion //*********************************** } //MessageBox.Show(newId.Count.ToString()); } catch (Exception e1) { MessageBox.Show(string.Format("CalcPosThuaMattien, line 1448-\n{0}", e1)); } finally { Marshal.ReleaseComObject(tgdFcs); } #endregion //*********************************** #region report progressing thua if (iThua < thuaSelectionSet.Count) { decimal i = (decimal)iThua / (decimal)thuaSelectionSet.Count * 100; int i1 = Convert.ToInt32(i); this._bgwCalculating.ReportProgress(i1); //MessageBox.Show("log 009"); } else { this._bgwCalculating.ReportProgress(99); } iThua++; #endregion } #endregion //[kodoi] //============================ #region luu thong tin vao bang gia dat if (!sdeTblTgdEditor.IsEditing()) { sdeTblTgdEditor.StartEditing(true); sdeTblTgdEditor.StartEditOperation(); } #region ----log evt.Log = string.Format("\n----||| Đang lưu vị trí các thửa vào bảng {0} |||---- ", tgd); onCalculating(evt); #endregion sdeTblTgdEditor.SaveEdit(); sdeTblTgdEditor.StopEditOperation(); sdeTblTgdEditor.StopEditing(true); #region ----log evt.Log = string.Format("\n----||| Đã lưu vị trí các thửa vào bảng {0} |||---- ", tgd); onCalculating(evt); #endregion #endregion #region tinh gia dat cho cac thua vua them vi tri CalcLandprice calc = new CalcLandprice(this); //MessageBox.Show(string.Format("final:{0}", newId.Count)); calc.Maduong = maduong; calc.Calculate(newId); newId.Clear(); #endregion //============================ } #endregion } #endregion #endregion //=========================================== //=========================================== //******************************************* //[kodoi] //============== #region doan ket sothuatinhduoc = sothuatimthay - sothuaKhongTinhDuoc; #region ----log evt.Log = string.Format("\n\n**************************************\n******* Đã tính xong các thửa phi nông nghiệp tại đô thị vị trí mặt tiền*******\n**********************************"); //evt.Log += string.Format("\n Số thửa tìm thấy: {0}", sothuatimthay); //evt.Log += string.Format("\n Số thửa được tính: {0}", sothuatinhduoc); onCalculating(evt); #endregion evt.Reset(); evt.ProgressingTotalCount = "."; evt.ProgressingTotal = "."; onCalculating(evt); evt.CurrentIndexCalculator = this._index; onFinished(evt); #endregion //============== }
private void EngineEditingForm_Load(object sender, EventArgs e) { //Set buddy controls axTOCControl1.SetBuddyControl(axMapControl1); axEditorToolbar.SetBuddyControl(axMapControl1); axToolbarControl1.SetBuddyControl(axMapControl1); //Add items to the ToolbarControl axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //Add items to the custom editor toolbar axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); //Create a popup menu m_toolbarMenu = new ToolbarMenuClass(); m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly); //share the command pool axToolbarControl1.CommandPool = axEditorToolbar.CommandPool; m_toolbarMenu.CommandPool = axEditorToolbar.CommandPool; //Create an operation stack for the undo and redo commands to use IOperationStack operationStack = new ControlsOperationStackClass(); axEditorToolbar.OperationStack = operationStack; //add some sample line data to the map IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); //relative file path to the sample data from EXE location string filePath = @"..\..\..\..\data\USAMajorHighways"; IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Highways"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways"); axMapControl1.Map.AddLayer((ILayer)featureLayer); }
/// <summary> /// 储存点shp,聚类号在"index"字段中标注 /// </summary> public void CreatePointsShapefile() { string filePath = m_dataInfo.GetOutputFilePath(); string fileName = m_dataInfo.GetOutputFileName(); ISpatialReference spatialReference = m_dataInfo.GetSpatialReference(); int index = fileName.LastIndexOf("."); fileName = fileName.Substring(0, index); fileName = fileName + "_pts.shp"; //打开工作空间 const string strShapeFieldName = "shape"; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(filePath, 0); //设置字段集 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //设置字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; //创建类型为几何类型的字段 pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照 IGeometryDef pGeoDef = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE. IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGeoDefEdit.SpatialReference_2 = spatialReference; pFieldEdit.GeometryDef_2 = pGeoDef; pFieldsEdit.AddField(pField); pField = new FieldClass(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "index"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; pFieldEdit.Precision_2 = 7;//数值精度 // pFieldEdit.Scale_2 = 3;//小数点位数 pFieldsEdit.AddField(pField); //创建shapefile pWS.CreateFeatureClass(fileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); //在featureclass中创建feature IWorkspaceEdit workspaceEdit = pWS as IWorkspaceEdit; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureClass featureClass = pWS.OpenFeatureClass(fileName); IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer(); IFeatureCursor featureCursor = featureClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); while (feature != null) { feature.Delete(); feature = featureCursor.NextFeature(); } featureCursor = featureClass.Insert(true); int typeFieldIndex = featureClass.FindField("index"); //插入点,并写入聚类号 for (int i = 0; i < m_clusters.GetClusterCount(); i++) { Cluster currentCluster = m_clusters.GetCluster(i); List<IPoint> currentPoints = currentCluster.GetPointsList(); for (int j = 0; j < currentPoints.Count; j++) { featureBuffer.set_Value(typeFieldIndex, currentCluster.GetClusterIndex()); featureBuffer.Shape = currentPoints[j] as IGeometry; object featureOID = featureCursor.InsertFeature(featureBuffer); } } featureCursor.Flush(); workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); //将新创建的shapfile作为图层添加到map里 IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; m_pointLayer = featureLayer; ////设置渲染 //DefinePointUniqueValueRenderer(featureLayer as IGeoFeatureLayer, "Class"); //m_mapControl.AddLayer(featureLayer as ILayer); //this.m_mapControl.Refresh(); }
/// <summary> /// 储存凸包shp,聚类号在"index"字段中标注 /// </summary> public void CreatePolygonShapefile() { string filePath = m_dataInfo.GetOutputFilePath(); string fileName = m_dataInfo.GetOutputFileName(); ISpatialReference spatialReference = m_dataInfo.GetSpatialReference(); //打开工作空间 const string strShapeFieldName = "shape"; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(filePath, 0); //设置字段集 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //设置字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; //创建类型为几何类型的字段 pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照 IGeometryDef pGeoDef = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE. IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; pGeoDefEdit.SpatialReference_2 = spatialReference; pFieldEdit.GeometryDef_2 = pGeoDef; pFieldsEdit.AddField(pField); pField = new FieldClass(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "index"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; pFieldEdit.Precision_2 = 7;//数值精度 pFieldsEdit.AddField(pField); //创建shapefile pWS.CreateFeatureClass(fileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); //在featureclass中创建feature IWorkspaceEdit workspaceEdit = pWS as IWorkspaceEdit; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureClass featureClass = pWS.OpenFeatureClass(fileName); IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer(); IFeatureCursor featureCursor = featureClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); while (feature != null) { feature.Delete(); feature = featureCursor.NextFeature(); } featureCursor = featureClass.Insert(true); int typeFieldIndex = featureClass.FindField("index"); for (int i = 0; i < m_clusters.GetClusterCount(); i++) { Cluster currentCluster = m_clusters.GetCluster(i); IPolygon currentPolygon = currentCluster.GetConvexHull(); //we know that there are IPoints only in the Geometrycollection. //But this is the safe and recommended way if (currentPolygon != null) { featureBuffer.set_Value(typeFieldIndex, currentCluster.GetClusterIndex()); featureBuffer.Shape = currentPolygon as IGeometry; object featureOID = featureCursor.InsertFeature(featureBuffer); } } featureCursor.Flush(); workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); //将新创建的shapfile作为图层添加到map里 IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; m_polygonLayer = featureLayer; /* //提前设置渲染 DefinePolygonUniqueValueRenderer(featureLayer as IGeoFeatureLayer, "ClusterIndex"); m_mapControl.AddLayer(featureLayer as ILayer); this.m_mapControl.Refresh(); */ }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; object Missing = Type.Missing; //if (bFeatDataPath == true) //{ // fileName = comboBoxInData.Text; // shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); // startX = fileName.LastIndexOf("\\"); // endX = fileName.Length; // shpFile = fileName.Substring(startX + 1, endX - startX - 1); // pFClass = Utility.OpenFeatureClassFromShapefile(shpDir, shpFile); //} //else //{ // pFClass = GetFeatureFromMapLyr(comboBoxInData.Text); //} if (bRasterDataPath == true) { fileName = txtOutPath.Text; shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); } else { shpDir = txtOutPath.Text; shpFile = "դ��ת����"; } try { //ɾ����ʱ�����ļ� DelFeatFile(shpDir, shpFile); //���դ�����ݼ� IRasterDescriptor pRsDescriptor = new RasterDescriptorClass(); pRsDescriptor.Create(m_pInRaster, new QueryFilterClass(), comboBoxField.Text); //�����������ռ� IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IWorkspace pWS = pWSF.OpenFromFile(shpDir, 0); //ת��դ��Ϊ������ IConversionOp pConversionOp = new RasterConversionOpClass(); IFeatureClass pOutFeatCls = null; switch (comboBoxGeomeryType.Text) { case "��": pOutFeatCls = pConversionOp.RasterDataToPointFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile) as IFeatureClass; break; case "��": pOutFeatCls = pConversionOp.RasterDataToLineFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile, false, false, ref Missing) as IFeatureClass; break; case "��": pOutFeatCls = pConversionOp.RasterDataToPolygonFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile, false) as IFeatureClass; break; } IFeatureLayer pFeatLyr = new FeatureLayerClass(); pFeatLyr.FeatureClass = pOutFeatCls; pMap.AddLayer(pFeatLyr); } catch (Exception ex) { MessageBox.Show(ex.Message); } }