protected override int CompleteTileCore(TileInfo args) { if (OnCachedRow != null) { if (args.CurrentEnvelope != null && args.State != TileState.Initial) { IEnvelope search = GeometryFactory.Clone(args.CurrentEnvelope); search.Expand(SearchDistance, SearchDistance, false); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = search; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; int tableIndex = 0; foreach (ITable table in InvolvedTables) { var filterHelper = new QueryFilterHelper(table, null, false); filterHelper.ForNetwork = true; foreach (IRow cachedRow in Search(table, filter, filterHelper)) { OnCachedRow(args, cachedRow, tableIndex); } tableIndex++; } } } return(OnCompleteTile == null ? NoError : OnCompleteTile(args)); }
private static IEnumerable <int> Intersect(IGeometry area, IFeatureClass featureClass) { if (featureClass == null) { throw new Exception("Cannot find Grid Feature class"); } ISpatialFilter spatialFilter = new SpatialFilterClass { Geometry = area, GeometryField = featureClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects }; IFeatureCursor cursor = featureClass.Search(spatialFilter, false); IFeature grid = null; var results = new List <int>(); while ((grid = cursor.NextFeature()) != null) { results.Add(Convert.ToInt32(grid.get_Value(0))); } // Discard the cursors as they are no longer needed. Marshal.ReleaseComObject(cursor); return(results); }
private int FindFeatureFID(IPoint pPoint) { try { double Tol = 4; IEnvelope pEnvelop = pPoint.Envelope; pEnvelop.Expand(Tol, Tol, false); ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pEnvelop; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; int intTLayerIdx = m_pSnippet.GetIndexNumberFromLayerName(m_mapControl.ActiveView, strTargetLayerName); ILayer pLayer = m_mapControl.get_Layer(intTLayerIdx); IFeatureLayer pFLayer = (IFeatureLayer)pLayer; string ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName; pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName; IFeatureClass pFeatureClass = pFLayer.FeatureClass; IFeatureCursor pFCursor = pFeatureClass.Search(pSpatialFilter, false); IFeature pFeature = pFCursor.NextFeature(); //int intFIDIdx = pFeatureClass.FindField("FID"); int intFID = Convert.ToInt32(pFeature.get_Value(0)); //Get FID Value return(intFID); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return(-1); } }
private byte[] FindNearFeatures(int layerID, IPoint location, double distance) { if (layerID < 0) { throw new ArgumentOutOfRangeException("layerID"); } if (distance <= 0.0) { throw new ArgumentOutOfRangeException("distance"); } IGeometry queryGeometry = ((ITopologicalOperator)location).Buffer(distance); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = queryGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IQueryResultOptions resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; AutoTimer timer = new AutoTimer(); //starts the timer IMapTableDescription tableDesc = GetTableDesc(layerID); this.serverLog.LogMessage(ServerLogger.msgType.infoDetailed, "FindNearFeatures", -1, timer.Elapsed, "Finding table description elapsed this much."); IQueryResult result = this.ms.QueryData(this.ms.DefaultMapName, tableDesc, filter, resultOptions); return(result.MimeData); }
private static void SelectByPoint(IFeatureLayer featureLayer, IPoint point, bool justOne = true) { IEnvelope pEnv = point.Envelope; double scale = m_pMapC2.MapScale / 1000; pEnv.XMin -= scale; pEnv.YMin -= scale; pEnv.XMax += scale; pEnv.YMax += scale; ISpatialFilter pSpatialFilter = new SpatialFilterClass() { Geometry = pEnv, SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects }; IFeatureCursor pFeatureCursor = featureLayer.FeatureClass.Search(pSpatialFilter as IQueryFilter, false); IFeature pFeature = pFeatureCursor.NextFeature(); if (justOne && pFeature != null) { m_pMapC2.Map.SelectFeature(featureLayer, pFeature); } else { while (pFeature != null) { m_pMapC2.Map.SelectFeature(featureLayer, pFeature); pFeature = pFeatureCursor.NextFeature(); } } m_pMapC2.Refresh(); }
public static List <IFeature> GetAllFeaturesFromPolygonInGeoFeatureLayer(IPolygon polygon, IGeoFeatureLayer geoFeatureLayer, IActiveView activeView) { List <IFeature> list = new List <IFeature>(); if (polygon == null || geoFeatureLayer == null || activeView == null) { return(list); } IMap pMap = activeView.FocusMap; ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = polygon; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.set_OutputSpatialReference(geoFeatureLayer.FeatureClass.ShapeFieldName, pMap.SpatialReference); pSpatialFilter.GeometryField = geoFeatureLayer.FeatureClass.ShapeFieldName; IFeatureCursor pFeatureCursor = geoFeatureLayer.Search(pSpatialFilter, false); IFeature pFeature; while ((pFeature = pFeatureCursor.NextFeature()) != null) { list.Add(pFeature); } Marshal.ReleaseComObject(pFeatureCursor); return(list); }
/// <summary> /// 根据已配置的查询条件来执行空间查询操作。 /// </summary> private void SelectFeaturesBySpatial() { //定义和创建用于空间查询的ISpatialFilter接口的对象 ISpatialFilter spatialFilter = new SpatialFilterClass(); //默认设定用于查询的空间几何体为当前地图源图层中所有要素几何体的集合 spatialFilter.Geometry = GetFeatureLayerGeometryUnion (GetFeatureLayerByName(currentMap, comboBoxSourceLayer.SelectedItem.ToString())); //根据对空间选择方法的选择采用相应的空间选择方法 switch (comboBoxMethods.SelectedIndex) { case 0: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; break; case 1: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin; break; case 2: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; break; case 3: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin; break; case 4: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelTouches; break; case 5: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; break; default: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; break; } //对所选择的目标图层进行遍历,并对每一个图层进行空间查询操作,查询结果将放在选择集中 IFeatureLayer featureLayer; //对所有被选择的目标图层进行遍历 for (int i = 0; i < checkedListBoxTargetLayers.CheckedItems.Count; i++) { //根据选择的目标图层名称获得对应的矢量图层 featureLayer = GetFeatureLayerByName(currentMap, (string)checkedListBoxTargetLayers.CheckedItems[i]); //进行接口转换,使用IFeatureSelection接口选择要素 IFeatureSelection featureSelection = featureLayer as IFeatureSelection; //使用IFeatureSelection接口的SelectFeatures方法根据空间查询过滤器选择要素,将其放在新的选择集中 featureSelection.SelectFeatures((IQueryFilter)spatialFilter, esriSelectionResultEnum.esriSelectionResultAdd, false); } //进行接口转换,使用IActiveView接口进行视图操作 IActiveView activeView = currentMap as IActiveView; //部分刷新操作,只刷新地理选择集的内容 activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeView.Extent); }
/// <summary> /// 根据范围查找数据填充窗体 /// </summary> /// <param name="pMap">被查询的地图对象</param> /// <param name="pGeometry">查询范围</param> public void FillData(IMap pMap, IGeometry pGeometry, esriSpatialRelEnum pesriSpatialRelEnum) { string strNodeKey = SysCommon.ModSysSetting.GetLinBanLayerNodeKey(Plugin.ModuleCommon.TmpWorkSpace); ILayer pLayer = SysCommon.ModuleMap.GetLayerByNodeKey(null, pMap, strNodeKey, null, true); IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer; if (pFeatureLayer != null) { ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pGeometry; pSpatialFilter.SpatialRel = pesriSpatialRelEnum; IFeatureCursor pFeatureCursor = pFeatureLayer.Search(pSpatialFilter, false); Application.DoEvents(); IFeature pFeat = pFeatureCursor.NextFeature(); if (pFeat != null) { m_pFeature = pFeat; } System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); pFeatureCursor = null; string strName = ""; try { strName = dataGridCategory.SelectedCells[0].Value.ToString(); } catch { } InitValueGrid(strName); } }
private IRecordSet FindNearFeatures(int layerID, IPoint location, double distance) { IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3; if (mapServer == null) { throw new Exception("Unable to access the map server."); } IGeometry queryGeometry = ((ITopologicalOperator)location).Buffer(distance); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = queryGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IQueryResultOptions resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject; IMapTableDescription tableDesc = GetTableDesc(mapServer, layerID); IQueryResult result = mapServer.QueryData(mapServer.DefaultMapName, tableDesc, filter, resultOptions); return((RecordSet)result.Object); }
private IQueryFilter GetCitiesQueryFilter(string areaName, string state, string cityClass, string isCapital, string pop2000) { ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.WhereClause = CitiesWhereBuilder(areaName, state, cityClass, isCapital, pop2000); return (QueryFilter)spatialFilter; }
public void GetFeatureOnMouseDown(int x, int y) { MyselectedFeature.Clear(); try { if (MyselectedLayer == null) { return; } IFeatureLayer featureLayer = MyselectedLayer as IFeatureLayer; if (featureLayer == null) { return; } IFeatureClass featureClass = featureLayer.FeatureClass; if (featureClass == null) { return; } IPoint point = MyMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y); IGeometry geometry = point as IGeometry; double length = ConvertPixelsToMapUnits(4); ITopologicalOperator pTopo = geometry as ITopologicalOperator; IGeometry buffer = pTopo.Buffer(length); geometry = buffer.Envelope as IGeometry; ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = geometry; switch (featureClass.ShapeType) { case esriGeometryType.esriGeometryPoint: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; break; case esriGeometryType.esriGeometryPolygon: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; break; case esriGeometryType.esriGeometryPolyline: spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; break; } spatialFilter.GeometryField = featureClass.ShapeFieldName; IQueryFilter filter = spatialFilter as IQueryFilter; IFeatureCursor cursor = featureClass.Search(filter, false); IFeature pfeature = cursor.NextFeature(); while (pfeature != null) { MyselectedFeature.Add(pfeature); pfeature = cursor.NextFeature(); } } catch { return; } }
private IQueryFilter GetStateQueryFilter(string stateName, string subRegion, string stateAbbr) { ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.WhereClause = StatesWhereBuilder(stateName, subRegion, stateAbbr); return (QueryFilter)spatialFilter; }
/// <summary> /// 计算每个数据点相邻的数据点,找出核心点 /// </summary> private void FindNeighborPoints() { for (int i = 0; i < m_DBSCANPnts.Count; i++) { List <DBSCANPoint> neighborPnts = new List <DBSCANPoint>(); IPoint point = m_DBSCANPnts[i].GetPoint(); ITopologicalOperator topologicalOperator = point as ITopologicalOperator; IGeometry pointBuffer = topologicalOperator.Buffer(m_dEps);//缓冲距离 topologicalOperator.Simplify(); ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = pointBuffer; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; IFeatureLayer featurelayer = m_dataInfo.GetInputLayer() as IFeatureLayer; IFeatureCursor featureCursor = featurelayer.FeatureClass.Search(spatialFilter, false); IFeature feature = featureCursor.NextFeature(); while (feature != null) { neighborPnts.Add(GetDBSCANPointByOID(feature.OID)); feature = featureCursor.NextFeature(); } m_DBSCANPnts[i].SetNeighborPoints(neighborPnts); //标记核心点 if (m_DBSCANPnts[i].GetNeighborPoints().Count >= m_nMinPts) { m_DBSCANPnts[i].SetPointType(1); } System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); } }
/// <summary> /// 获取查询要素 /// </summary> /// <param name="pFeatureLayer">要素图层</param> /// <param name="pGeometry">图形范围参数</param> /// <returns>符号条件要素集合</returns> public List <IFeature> GetSeartchFeatures(IFeatureLayer pFeatureLayer, IGeometry pGeometry) { try { List <IFeature> pList = new List <IFeature>(); //创建SpatialFilter空间过滤器对象 ISpatialFilter pSpatialFilter = new SpatialFilterClass(); IQueryFilter pQueryFilter = pSpatialFilter as ISpatialFilter; //设置过滤器的Geometry pSpatialFilter.Geometry = pGeometry; //设置空间关系类型 pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; //获取FeatureCursor游标 IFeatureCursor pFeatureCursor = pFeatureLayer.Search(pQueryFilter, false); //遍历FeatureCursor IFeature pFeature = pFeatureCursor.NextFeature(); while (pFeature != null) { //获取要素对象 pList.Add(pFeature); pFeature = pFeatureCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); return(pList); } catch (Exception Err) { MessageBox.Show(Err.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return(null); } }
public void SelectByLine(int IndexOfLayer, RubberLineClass Line) { int ConstantNum = 255; IActiveView CurrentView = axMapControl1.ActiveView; IScreenDisplay CurScreenDisplay = CurrentView.ScreenDisplay; CurScreenDisplay.StartDrawing(CurScreenDisplay.hDC, (System.Int16)esriScreenCache.esriNoScreenCache); IRgbColor RGBCOLORS = new ESRI.ArcGIS.Display.RgbColorClass(); RGBCOLORS.Red = ConstantNum; IColor MyColor = RGBCOLORS; ISimpleFillSymbol MySimpleFillSymbol = new SimpleFillSymbolClass(); MySimpleFillSymbol.Color = MyColor; ISymbol MySymbol = MySimpleFillSymbol as ISymbol; IRubberBand MyIRubberBand = Line; IGeometry MyGeometry = MyIRubberBand.TrackNew(CurScreenDisplay, MySymbol); CurScreenDisplay.SetSymbol(MySymbol); CurScreenDisplay.DrawPolygon(MyGeometry); CurScreenDisplay.FinishDrawing(); ISpatialFilter MySpatialFilter = new SpatialFilterClass(); MySpatialFilter.Geometry = MyGeometry; MySpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureLayer SelectedLayer = axMapControl1.ActiveView.FocusMap.get_Layer(IndexOfLayer) as IFeatureLayer; IFeatureSelection SelectedFeatures = SelectedLayer as IFeatureSelection; SelectedFeatures.SelectFeatures(MySpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false); ISelectionSet FinalSelection = SelectedFeatures.SelectionSet; axMapControl1.ActiveView.Refresh(); }
public static IFeatureCursor SearchFeatures(IFeatureLayer pFLayer, IGeometry pFilterGeometry, esriSpatialRelEnum enumSpatialRel) { if (pFLayer == null) { return(null); } IFeatureClass featureClass = pFLayer.FeatureClass; if (featureClass == null) { return(null); } try { if (pFilterGeometry == null) { return(null); } ISpatialFilter queryFilter = new SpatialFilterClass { Geometry = pFilterGeometry, GeometryField = featureClass.ShapeFieldName, SpatialRel = enumSpatialRel }; return(pFLayer.Search(queryFilter, false)); } catch (Exception) { return(null); } }
public static IFeatureCursor GetAllFeaturesFromPointSearchInGeoFeatureLayer(Double searchTolerance, IPoint point, IFeatureClass featureClass, IActiveView activeView) { if (searchTolerance < 0 || point == null || featureClass == null || activeView == null) { return(null); } IMap map = activeView.FocusMap; // Expand the points envelope to give better search results //IEnvelope envelope = point.Envelope; //envelope.Expand(searchTolerance, searchTolerance, false); ITopologicalOperator pTopologicalOperator = point as ITopologicalOperator; String shapeFieldName = featureClass.ShapeFieldName; // Create a new spatial filter and use the new envelope as the geometry ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = pTopologicalOperator.Buffer(searchTolerance); spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects; spatialFilter.set_OutputSpatialReference(shapeFieldName, map.SpatialReference); spatialFilter.GeometryField = shapeFieldName; // Do the search IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false); return(featureCursor); }
private bool IntersectAll(IFeatureClass lineLayer, IPolygon polygon2, List <ziduan> list) { try { if (radioBtnKJ.Checked && polygon2 != null) { // 根据组合成的面裁剪压力等值线 SpatialFilterClass qfilter = new SpatialFilterClass(); qfilter.Geometry = polygon2; qfilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor qfeatureCursor = lineLayer.Search(qfilter, false); if (qfeatureCursor != null) { IFeature feature = qfeatureCursor.NextFeature(); IGeometryArray geometryArray = new GeometryArrayClass(); while (feature != null) { geometryArray.Add(feature.Shape); feature = qfeatureCursor.NextFeature(); } IGeometryServer2 geometryServer2 = new GeometryServerClass(); IGeometryArray geometryArray2 = geometryServer2.Intersect(polygon2.SpatialReference, geometryArray, polygon2); //DataEditCommon.DeleteFeatureByWhereClause(lineLayer, ""); IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer; DataEditCommon.CreateFeature(pFeatureLayer.FeatureClass, geometryArray2, list); } } return(true); } catch { return(false); } }
public static List <IFeature> GetAllFeaturesFromPolygonInGeoFeatureLayer(IPolygon polygon, IFeatureLayer featureLayer, IMap map, double distance = 0) { List <IFeature> list = new List <IFeature>(); if (polygon == null || featureLayer == null || map == null) { return(list); } ITopologicalOperator pTopologicalOperator = polygon as ITopologicalOperator; if (pTopologicalOperator == null) { return(list); } ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pTopologicalOperator.Buffer(distance); pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.OutputSpatialReference[featureLayer.FeatureClass.ShapeFieldName] = map.SpatialReference; pSpatialFilter.GeometryField = featureLayer.FeatureClass.ShapeFieldName; IFeatureCursor pFeatureCursor = featureLayer.Search(pSpatialFilter, false); IFeature pFeature; while ((pFeature = pFeatureCursor.NextFeature()) != null) { list.Add(pFeature); } Marshal.ReleaseComObject(pFeatureCursor); return(list); }
/// <summary> /// 根据要素的缓冲距离查找要素 /// </summary> /// <param name="desFeaCls"></param> /// <param name="pointFeature"></param> /// <param name="dis"></param> /// <returns></returns> private List <IFeature> GetFeatureByDis(IFeatureClass desFeaCls, IFeature pointFeature, esriSpatialRelEnum spatialRelEnum, double dis) { List <IFeature> LstFeature = new List <IFeature>(); //根据源要素的缓冲半径得到缓冲范围 ITopologicalOperator pTopoOper = pointFeature.Shape as ITopologicalOperator; IGeometry pGeo = pTopoOper.Buffer(dis); //查找缓冲范围内的要素 ISpatialFilter pFilter = new SpatialFilterClass(); pFilter.GeometryField = "SHAPE"; pFilter.Geometry = pGeo; pFilter.SpatialRel = spatialRelEnum;// esriSpatialRelEnum.esriSpatialRelIntersects;//.esriSpatialRelWithin; IFeatureCursor pCursor = desFeaCls.Search(pFilter, false); if (pCursor == null) { return(null); } IFeature pFeature = pCursor.NextFeature(); while (pFeature != null) { LstFeature.Add(pFeature); pFeature = pCursor.NextFeature(); } //释放cursor System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor); return(LstFeature); }
public override void OnMouseDown(int Button, int Shift, int X, int Y) { // TODO: Add QueryTool.OnMouseDown implementation if (m_mapCtrl == null) { return; } IPoint pt = m_mapCtrl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y); ISpatialFilter sFilter = new SpatialFilterClass(); sFilter.Geometry = pt; sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin; IFeatureLayer lyr = Utilities.GetLayerByName("县区", m_mapCtrl.Map) as IFeatureLayer; IFeatureClass fCls = lyr.FeatureClass; IFeatureCursor featCursor = fCls.Search(sFilter, false); IFeature pFeat = featCursor.NextFeature(); if (pFeat != null) { IFields pFields = pFeat.Fields; int i = pFields.FindField("NAME99"); string cityName = pFeat.get_Value(i).ToString(); char[] c = new char[] { '县', '市', '区' }; int index = cityName.IndexOfAny(c, 2); if (index != -1) { cityName = cityName.Substring(0, index); } LabelEvent(cityName, pFeat); } }
/// <summary> /// 执行空间查询 /// </summary> private void SelectFeaturesBySpatial() { IActiveView pActView = mMap as IActiveView; IPoint pt = pActView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y); ITopologicalOperator pTopo = pt as ITopologicalOperator; IGeometry pGeo = pTopo.Buffer((double)NumericDistance.Value); //定义和创建用于查询的ISpatialFilter接口对象 ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; //对选择的目标图层进行遍历,并对每一个图层进行空间查询,查询结果将放在选择集中 IFeatureLayer featureLayer; //对所有选择的目标图层进行遍历 for (int i = 0; i < checkListLayer.CheckedItems.Count; i++) { //根据选择的目标图层名称获得对应的矢量图层 featureLayer = GetFeatureLayerByName(mMap, (string)checkListLayer.CheckedItems[i]); //进行接口转换,使用IFeatureSelection接口选择要素 IFeatureSelection featureSelection = featureLayer as IFeatureSelection; //使用IFeatureSelection接口的SelectFeature方法,根据空间查询过滤器选择要素,将其放在新的选择集中 featureSelection.SelectFeatures((IQueryFilter)spatialFilter, esriSelectionResultEnum.esriSelectionResultAdd, false); } //进行接口转换,使用IActiveView接口进行视图操作 IActiveView activeView = mMap as IActiveView; //进行部分刷新操作,只刷新选择集的内容 activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeView.Extent); }
//获取污染物名称并且在指定的pGeometry范围内的污染排放数据库的空间位置 public List <IFeature> GetPolygonContainPoint(IFeatureLayer pFeatureLayer, IGeometry pGeometry, string pollutiontypename) { try { List <IFeature> listFeature = new List <IFeature>(); ISpatialFilter spatialFiter = new SpatialFilterClass(); spatialFiter.Geometry = pGeometry; spatialFiter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor featureCursor = pFeatureLayer.Search(spatialFiter, false); IFeature pFeature; while ((pFeature = featureCursor.NextFeature()) != null) { string strName = Convert.ToString(pFeature.get_Value(pFeature.Fields.FindField("污染物"))); if (strName == pollutiontypename) { listFeature.Add(pFeature); } } return(listFeature); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.ToString(), "异常"); return(null); } }
private double GetDiameter(IPoint point, I3DItem item) { ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = point; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor featureCursor = item.LineLayerInfo.FeatureClass.Search(spatialFilter, false); IFeature lineFeature; double maxDiameter = 0; while ((lineFeature = featureCursor.NextFeature()) != null) { string gg = ConvertToString(lineFeature.Value[item.IdxGjField]); if (string.IsNullOrEmpty(gg) || gg == "<空>") gg = "50"; if (gg.Contains("*")) { gg = gg.Split('*')[0]; } double diameter; if (double.TryParse(gg, out diameter) == false) diameter = 0; diameter = diameter / 1000; if (maxDiameter < diameter) maxDiameter = diameter; } return maxDiameter; }
//通过intersect关系进行裁切 public void ClipByExtent(int groupNm, int extNum) { IGeometry extent = GetClipExtent(extNum); string findName = "grp" + groupNm.ToString() + "ext0"; IGroupLayer grpLy = avlbLayers.Find(item => item.Name == findName); ICompositeLayer comLy = grpLy as ICompositeLayer; IGroupLayer newGroupLayer = new GroupLayerClass(); newGroupLayer.Name = "grp" + groupNm.ToString() + "ext" + extNum.ToString(); for (int i = 0; i < comLy.Count; i++) { IFeatureLayer feaLy = comLy.get_Layer(i) as IFeatureLayer; IFeatureClass clipFC = feaLy.FeatureClass; IFields flds = clipFC.Fields; ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = extent; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor cursor = clipFC.Search(spatialFilter, false); IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass(); IWorkspaceName workspaceName = workspaceFactory.Create(null, "MyWorkspace", null, 0); IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); IFeatureWorkspace inmemFeaWksp = workspace as IFeatureWorkspace; if (clipFC.ShapeType == esriGeometryType.esriGeometryPoint) { IFeatureClass inmemPTFC = CreateWithoutDescription("inmemPTFC_" + groupNumber.ToString(), null, inmemFeaWksp, clipFC.ShapeType, flds); InsertFeaturesBoun(inmemPTFC, cursor, extent); IFeatureLayer inmemPTFCLayer = new FeatureLayerClass(); inmemPTFCLayer.FeatureClass = inmemPTFC; newGroupLayer.Add(inmemPTFCLayer); } else if (clipFC.ShapeType == esriGeometryType.esriGeometryPolyline) { IFeatureClass inmemLNFC = CreateWithoutDescription("inmemLNFC" + groupNumber.ToString(), null, inmemFeaWksp, clipFC.ShapeType, flds); InsertFeaturesBoun(inmemLNFC, cursor, extent); IFeatureLayer inmemLNFCLayer = new FeatureLayerClass(); inmemLNFCLayer.FeatureClass = inmemLNFC; newGroupLayer.Add(inmemLNFCLayer); } else if (clipFC.ShapeType == esriGeometryType.esriGeometryPolygon) { IFeatureClass inmemPLGFC = CreateWithoutDescription("inmemPLGFC" + groupNumber.ToString(), null, inmemFeaWksp, clipFC.ShapeType, flds); InsertFeaturesBoun(inmemPLGFC, cursor, extent); IFeatureLayer inmemPLGFCLayer = new FeatureLayerClass(); inmemPLGFCLayer.FeatureClass = inmemPLGFC; newGroupLayer.Add(inmemPLGFCLayer); } } avlbLayers.Add(newGroupLayer); }
public string CheckLine(string pipelineName, IPolyline polyline, IFeatureClass featureClass) { string message = ""; ITopologicalOperator topologicalOperator = polyline as ITopologicalOperator; IPolygon polygon = topologicalOperator.Buffer(_dataCheck.DataCheckConfig.LineMinimumSpacing) as IPolygon; ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = polygon; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; spatialFilter.GeometryField = featureClass.ShapeFieldName; IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false); IFeature feature; while ((feature = featureCursor.NextFeature()) != null) { IPolyline tempPolyline = feature.Shape as IPolyline; if (tempPolyline == null || tempPolyline.IsEmpty) { continue; } IProximityOperator proximityOperator = polyline as IProximityOperator; double d = proximityOperator.ReturnDistance(tempPolyline); if (d < _dataCheck.DataCheckConfig.LineMinimumSpacing) { message += $"{pipelineName}:与 {feature.OID} 的距离为 {d};"; } } Marshal.ReleaseComObject(featureCursor); return(message); }
/// <summary> /// 根据属性条件和空间条件获得查询结果游标 /// </summary> /// <param name="pFeatureClass"></param> /// <param name="pWhereClause"></param> /// <param name="pGeometry"></param> /// <param name="pesriSpatialRelEnum"></param> /// <returns></returns> private IFeatureCursor GetFeatureCursor(IFeatureClass pFeatureClass, string pWhereClause, IGeometry pGeometry, esriSpatialRelEnum pesriSpatialRelEnum) { IFeatureCursor pFeatureCursor = null; ISpatialFilter pSpatialFilter = new SpatialFilterClass(); try { if (pGeometry != null) { pSpatialFilter.Geometry = pGeometry; pSpatialFilter.GeometryField = pFeatureClass.ShapeFieldName; pSpatialFilter.SpatialRel = pesriSpatialRelEnum; } pSpatialFilter.WhereClause = pWhereClause; pFeatureCursor = pFeatureClass.Search(pSpatialFilter, false); return(pFeatureCursor); } catch { return(pFeatureCursor); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(pSpatialFilter); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); } }
private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { switch (_nSpatialSearchMode) { case 1: // 鼠标拖动创建矩形框 IEnvelope box = axMapControl1.TrackRectangle(); IFeatureLayer featureLayer = axMapControl1.get_Layer(0) as IFeatureLayer; if (featureLayer != null) { ISpatialFilter filter = new SpatialFilterClass(); filter.WhereClause = txtWhereClause.Text; filter.Geometry = box; ShowFeatures(featureLayer, filter, true); } break; } }
public IFeature GetNearToFeature() { if (Polyline == null || PointFeatureLayer == null) { return(null); } ITopologicalOperator pTopologicalOperator = Polyline.ToPoint as ITopologicalOperator; if (pTopologicalOperator == null) { return(null); } ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pTopologicalOperator.Buffer(Tolerance); pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects; pSpatialFilter.GeometryField = PointFeatureLayer.FeatureClass.ShapeFieldName; IFeatureCursor pFeatureCursor = PointFeatureLayer.Search(pSpatialFilter, false); IFeature pFeature = pFeatureCursor.NextFeature(); Marshal.ReleaseComObject(pFeatureCursor); return(pFeature); }
private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { // 为了程序的拓展性,选择 switch…case…结构判断操作模式 switch (nSpatialSearchMode) { case 1: // 矩形框选模式 , 通过鼠标拖动创建矩形框 IEnvelope box = axMapControl1.TrackRectangle(); // 获取空间查询的目标图层 IFeatureLayer fLayer = axMapControl1.get_Layer(0) as IFeatureLayer; if (fLayer != null) { // 创建一个 SpatialFilter 组件对象 ISpatialFilter filter = new SpatialFilterClass(); // 设置属性过滤条件 filter.WhereClause = txtWhereClause.Text; // 设置空间查询的参考几何体为鼠标拖出的矩形框 filter.Geometry = box; // 设置空间关系(本例中是相交关系) filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; // 利用 ShowFeatures 方法查询并显示矢量要素 ShowFeatures(fLayer, filter, true); } // 退出“框选”模式 nSpatialSearchMode = -1; break; } }
public void SelectByPolygon(int IndexOfLayer, RubberPolygonClass Polygon) { int ConstantNum = 255; IActiveView CurrentView = axMapControl1.ActiveView; IScreenDisplay MyScreenDispaly = CurrentView.ScreenDisplay; MyScreenDispaly.StartDrawing(MyScreenDispaly.hDC, (System.Int16)esriScreenCache.esriNoScreenCache); IRgbColor MYRGBCOLOR = new RgbColorClass(); MYRGBCOLOR.Red = ConstantNum; IColor MyColor = MYRGBCOLOR; ISimpleFillSymbol MySimpleFillPolygon = new SimpleFillSymbolClass(); MySimpleFillPolygon.Color = MyColor; ISymbol MySymbol = MySimpleFillPolygon as ISymbol; IRubberBand MyIRubberBand = Polygon; IGeometry MyGeometry = MyIRubberBand.TrackNew(MyScreenDispaly, MySymbol); MyScreenDispaly.SetSymbol(MySymbol); MyScreenDispaly.DrawPolygon(MyGeometry); MyScreenDispaly.FinishDrawing(); ISpatialFilter MyISpatialFilter = new SpatialFilterClass(); MyISpatialFilter.Geometry = MyGeometry; MyISpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureLayer SelectedLayer = axMapControl1.ActiveView.FocusMap.get_Layer(IndexOfLayer) as IFeatureLayer; IFeatureSelection SelectedFeature = SelectedLayer as IFeatureSelection; SelectedFeature.SelectFeatures(MyISpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false); ISelectionSet MyISelectionSet = SelectedFeature.SelectionSet; axMapControl1.ActiveView.Refresh(); }
public void SelectPoint(string X, string Y, int CheckIfMapLoaded) { if (CheckIfMapLoaded == 0) { toolStripStatusLabel1.Text = "Map X Y"; } else { toolStripStatusLabel1.Text = "X=" + X + "," + "Y=" + Y; int ConstantNum = 255; IMarkerElement MyIMarkerElement = new MarkerElementClass(); ISimpleMarkerSymbol MyISimpleMarkerSymbol = new SimpleMarkerSymbolClass(); IRgbColor MyIRGBColor = new RgbColorClass(); MyIRGBColor.Blue = ConstantNum; MyISimpleMarkerSymbol.Color = MyIRGBColor; MyISimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCross; MyIMarkerElement.Symbol = MyISimpleMarkerSymbol; IPoint MyIPoint = new PointClass(); MyIPoint.X = double.Parse(X); MyIPoint.Y = double.Parse(Y); IElement MyIElement = MyIMarkerElement as IElement; MyIElement.Geometry = MyIPoint; axMapControl1.ActiveView.GraphicsContainer.AddElement(MyIElement, 0); axMapControl1.ActiveView.Refresh(); ISpatialFilter MyISpatialFilter = new SpatialFilterClass(); MyISpatialFilter.Geometry = MyIPoint; MyISpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin; IFeatureLayer SelectedLayer = axMapControl1.ActiveView.FocusMap.get_Layer(comboBox13.SelectedIndex) as IFeatureLayer; IFeatureSelection MyIFeatureSelection = SelectedLayer as IFeatureSelection; MyIFeatureSelection.SelectFeatures(MyISpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false); axMapControl1.ActiveView.Refresh(); } }
public override bool Check(ref List<Error> checkResult) { IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = m_structPara.strWhereClause; //����������ѯ IFeatureCursor ipFeatCursor = pSrcFeatClass.Search(pQueryFilter, true); IFeature ipFeature = ipFeatCursor.NextFeature(); IGeometryCollection pGeometryCollection = new GeometryBagClass(); ///��ȡ�����������geometry while (ipFeature != null) { IGeometry ipGeometry = ipFeature.Shape; if (ipGeometry == null) { ipFeature = ipFeatCursor.NextFeature(); continue; } object Missing = Type.Missing; pGeometryCollection.AddGeometry(ipGeometry, ref Missing, ref Missing); ipFeature = ipFeatCursor.NextFeature(); } ISpatialIndex pSpatialIndex = (ISpatialIndex)pGeometryCollection; pSpatialIndex.AllowIndexing = true; pSpatialIndex.Invalidate(); ///��������ͼ������ص��Ŀռ��ѯ ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelOverlaps; ///�����GeometryCollection����spatialfilter pSpatialFilter.Geometry = (IGeometry)pGeometryCollection; string Fields = "OBJECTID,Shape"; pSpatialFilter.SubFields = Fields; IFeatureCursor ipResultFtCur = pRelFeatClass.Search(pSpatialFilter, true); //�������� List<Error> pRuleResult = new List<Error>(); AddResult(ref pRuleResult, ipResultFtCur); checkResult = pRuleResult; if (ipResultFtCur != null) { Marshal.ReleaseComObject(ipResultFtCur); ipResultFtCur = null; } if (pSrcFeatClass != null) { Marshal.ReleaseComObject(pSrcFeatClass); pSrcFeatClass = null; } if (pRelFeatClass != null) { Marshal.ReleaseComObject(pRelFeatClass); pRelFeatClass = null; } return true; }
/// <summary> /// ��������ͼ�������ڵ�Ҫ�� /// </summary> /// <param name="fc"></param> /// <param name="geo"></param> /// <returns></returns> public static IFeatureCursor SearchContainFeat(IFeatureClass fc, IGeometry geo) { ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = geo; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; IFeatureCursor pfeatCursor = fc.Search(pSpatialFilter, false); return pfeatCursor; }
/// <summary> /// ����Ҫ�ؼ����������ͼ���ཻ��Ҫ�أ��������α� /// </summary> /// <param name="LineFeatClass"></param> /// <param name="geo"></param> /// <returns></returns> public static IFeatureCursor SearchIntersectLineFeat(IFeatureClass LineFeatClass, IGeometry geo) { ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = geo; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; IFeatureCursor pfeatCursor = LineFeatClass.Search(pSpatialFilter, false); return pfeatCursor; }
private IQueryFilter GetQueryFilter(string stateAbbr) { IGeometry stateGeometry = getGeometry(stateAbbr); ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = stateGeometry; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; return (QueryFilter)spatialFilter; }
private static ISpatialFilter getSpatialFilter(double centerX, double centerY, double distance) { IPoint center = getCenter(centerX, centerY); IGeometry buffer = getBuffer(distance, center); ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = buffer; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; return spatialFilter; }
public List<City> SearchCities(string userName, string password, double centerX, double centerY, double distance) { IWorkspace workspace = null; IFeatureClass citiesClass = null; IFeatureCursor citiesCursor = null; try { workspace = Connect(userName, password); //IFeatureClass citiesClass = (workspace as IFeatureWorkspace).OpenFeatureClass("SDE.SDE.Cities"); citiesClass = (workspace as IFeatureWorkspace).OpenFeatureClass("Cities"); int areaNameIndex = citiesClass.FindField("AREANAME"); IPoint center = new Point(); center.PutCoords(centerX, centerY); IGeometry buffer = (center as ITopologicalOperator).Buffer(distance); ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = buffer; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor citiesCursor = citiesClass.Search(spatialFilter, true); List<City> resultCities = new List<City>(); IFeature capital = citiesCursor.NextFeature(); IPoint capitalShape = null; while (capital != null) { capitalShape = capital.Shape as IPoint; resultCities.Add(new City() { AreaName = capital.get_Value(areaNameIndex) as string, X = capitalShape.X, Y = capitalShape.Y }); capital = citiesCursor.NextFeature(); } return resultCities; } finally { if (citiesClass != null) { Marshal.ReleaseComObject(citiesClass); } } }
/// <summary> /// 参数说明,栅格面,写入这个面的字段名称,点要素,点要素的速度字段,计算平均速度 /// </summary> /// <param name="pPolygonFClass"></param> /// <param name="pFieldName"></param> /// <param name="pPointFClass"></param> /// <param name="FieldName"></param> public void Calculate(IFeatureClass pPolygonFClass, string pFieldName,IFeatureClass pPointFClass, string FieldName) { IFeatureCursor pPolyCursor = pPolygonFClass.Search(null, false); int pFieldIndex = pPointFClass.FindField(FieldName); IFeature pPolyFeature = pPolyCursor.NextFeature(); int pPolygonIndex = pPolygonFClass.FindField(pFieldName); while (pPolyFeature != null) { IGeometry pPolGeo = pPolyFeature.Shape; int Count = 0; ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = pPolGeo; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; IFeatureCursor pPointCur = pPointFClass.Search(spatialFilter, false); double TotalSpeed = 0; if (pPointCur != null) { IFeature pPointFeature = pPointCur.NextFeature(); while (pPointFeature != null) { pPointFeature = pPointCur.NextFeature(); TotalSpeed = TotalSpeed + (double)pPointFeature.get_Value(pFieldIndex); Count++; } } if (Count != 0) { pPolyFeature.set_Value(pPolygonIndex, TotalSpeed / Count); } pPolyFeature = pPolyCursor.NextFeature(); } }
protected override void OnMouseDown(MouseEventArgs arg) { // access display and IScreenDisplay display = (ArcMap.Document.FocusMap as IActiveView).ScreenDisplay; // transform from display coordinates to map coordinates IPoint point = display.DisplayTransformation.ToMapPoint(arg.X, arg.Y); // Buffer figure is ochertanie of other figure IGeometry region = (point as ITopologicalOperator).Buffer(display.DisplayTransformation.FromPoints(4)); // Buffer always return polygone IMap map = ArcMap.Document.FocusMap; for (int i = 0; i < map.LayerCount; i++) { if (map.get_Layer(i).Name == "Cities") { IFeatureLayer citiesLayer = map.get_Layer(i) as IFeatureLayer; IFeatureClass citiesClass = citiesLayer.FeatureClass; int cityNameIndex = citiesClass.FindField("AREANAME"); int stateIndex = citiesClass.FindField("ST"); ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = region; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor resCursor = citiesClass.Search(spatialFilter as IQueryFilter, true); IFeature cityFeature = resCursor.NextFeature(); while (cityFeature != null) { MessageBox.Show(String.Format("{0}, {1}", cityFeature.get_Value(cityNameIndex), cityFeature.get_Value(stateIndex))); cityFeature = resCursor.NextFeature(); } Marshal.ReleaseComObject(resCursor); break; } } base.OnMouseDown(arg); }
//otherPt is for line features to chck if it is not split public IFeature GetNearestEdge(IPoint point, IPoint otherPt, List<string> edgeSearchClasses) { IGeometry queryGeometry = point; IFeature nearestFeat = null; foreach (string edgeFeatClass in edgeSearchClasses) { IFeatureClass featClass = ((IFeatureWorkspace)ExtensionInfo.Editor.EditWorkspace).OpenFeatureClass(edgeFeatClass) as IFeatureClass; if (featClass != null) { ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = queryGeometry; spatialFilter.GeometryField = featClass.ShapeFieldName; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //esriSpatialRelEnum.esriSpatialRelTouches; // Execute the query and iterate through the cursor's results. IFeatureCursor featCursor = featClass.Search(spatialFilter, false); IFeature feat = featCursor.NextFeature(); double length = 0.0; while (feat != null) { ICurve curve = feat.ShapeCopy as ICurve; if ( curve.Length > length)//DisplayMap.AreGeometriesTheSame(point, curve.FromPoint, false) == false //&& DisplayMap.AreGeometriesTheSame(point, curve.ToPoint, false) == false //&& (otherPt == null || (DisplayMap.AreGeometriesTheSame(otherPt, curve.FromPoint, false) == false //&& DisplayMap.AreGeometriesTheSame(otherPt, curve.ToPoint, false) == false)) //&& { nearestFeat = feat; length = curve.Length; } feat = featCursor.NextFeature(); } // The cursors is no longer needed, so dispose of it. System.Runtime.InteropServices.Marshal.ReleaseComObject(featCursor); System.Runtime.InteropServices.Marshal.ReleaseComObject(featClass); } } return nearestFeat; }
private ISpatialFilter GenerateSpatialFilter() { frmPromptQuerying frmPrompt = new frmPromptQuerying(4);//��ʾ����������ͼ���� Ϊ�����쳣ʱ�ܽ�����ʾ���ڹرգ����Է���try���� try { frmPrompt.Show(); System.Windows.Forms.Application.DoEvents();//'ת�ÿ���Ȩ��û����һ��Ļ���ʾ���ڲ���������ʾ //����Ҫ�����spatialfilter //��ù���spatialfilter.geometry������feature //IMap pMap; //����QI��IEnumLayer //IEnumLayer pEnumLayer; //����������Ϊ��ѡ���layers //ILayer pLayer; IFeatureLayer pFeatureLayer = null; IGeometry pGeometry = null; IEnumFeature pEnumFeature = null; //�����зֱ�����ʹ�úͲ�ʹ�� IFeatureCursor pFeatureCursor = null; //�Ѿ�ѡ���Ԫ�����ɡ�ɸѡͼ�Ρ������ IFeatureClass pFeatureClass; IFeature pFeature; string strLayerName = comboBoxConditionLayer.Text; if (checkBoxUseSelectedOnly.Checked == false) //����û��Լ�ѡ������ͼ�㡱,��������ѡ�е�Ԫ�� { pFeatureLayer = GetLayerbyName(strLayerName) as IFeatureLayer; //���layer����������spatialfilter.geometry�� //���Ǹ�������ͼ�㡱 //���ﲻ��featureselection�����enumfeature,�Ӷ����������geometry�ϲ�������ȡfeaturecursor������Ϊ //��featureselection�Ļ�����ô��ϲ�������feature��һ�������ôд��featureselection=mainaxmapcontrol.map.featureselection //������ָ��featureselection��map�����һ���㣡���������featureselection=pfeaturelayer.featureselection�� //Ȼ��enumfeature=featureselection����ʱenumfeature����null�����е�pfeaturelayer�Ѿ���map���һ��ָ���IJ��ˣ� //�����featureselection=mainaxmapcontrol.map.featureselection���ͻ������⣺Ҳ��map�����Ѿ��б�ѡ�е�Ԫ���ˣ�����ʱ�����ַ��� //��õ�enumfeatureֻ������Щ�Ѿ�ѡ�е�Ԫ�أ�����Ӧ����������Ӧ�û�õ���ָ��Ϊ������ͼ�㡱������feature������ֻ����featurecursor //�����featureselection�Ļ���Ҫ��ôд�� //IFeatureSelection pFeatureSelection = MainaxMapControl.get_Layer(strLayerName) as IFeatureSelection; //pFeatureSelection.SelectFeatures(null, esriSelectionResultEnum.esriSelectionResultNew, false);//��ʹ���ѱ�ѡ�е�Ԫ��ʱ������仰Խ��ȥ //IEnumFeature pEnumFeature = MainaxMapControl.Map.FeatureSelection as IEnumFeature; pFeatureClass = pFeatureLayer.FeatureClass; pFeatureCursor = pFeatureClass.Search(null, true); pFeature = pFeatureCursor.NextFeature(); } else //���ʹ�õ�ͼ����ѡ�е�Ԫ����Ϊ��ɸѡͼ�㡱 { pEnumFeature = MainAxMapControl.Map.FeatureSelection as IEnumFeature; pFeature = pEnumFeature.Next(); } pGeometry = pFeature.Shape; ITopologicalOperator pTopologicalOperator; //�ϲ������Ե���ɸ�ӡ���geometry while (pFeature != null) { //�����һ���ǹؼ����������յ�pgeometry���Ի���������geometry //��ΪTopologicalOperator�������һ��shape��һ��geometry�����Խ����������������ĺϲ�. //ֻ����shapecopy���ܹ���ȷ����shape�Ļ����ļ��ͳ����Ϊ��������ⵢ����һ���ڣ����� //����һ��˼·Ҳ���ԡ������˼·����ѭ���ϲ�����geometry����һ��˼·����ѭ���õ�����ÿ�� //geometryȥɸѡͼ�����featuresȻ��ϲ���� pTopologicalOperator = pFeature.ShapeCopy as ITopologicalOperator; //if (checkBoxBuffer.Checked == true) //{ // double ddistance = Convert.ToDouble(textBoxBuffer.Text); // pGeometry = pTopologicalOperator.Buffer(ddistance); // //pTopologicalOperator.Simplify(); //ʹ���˹�ϵ�����ȷ //} pGeometry = pTopologicalOperator.Union(pGeometry as IGeometry); if (checkBoxUseSelectedOnly.Checked == false)//�õ���featurecursor pFeature = pFeatureCursor.NextFeature(); else pFeature = pEnumFeature.Next(); } //pFeatureSelection.Clear();//������������������geometry��������featureselection�Ļ�����Ҳ��һ��ؼ��� //�������յ���ʾҲ�������featureselection��ʾ���� //���ɻ����������������ѭ��֮��ִ�У������Ӹ���Ч�ʣ����Ҹ������׳��� if (checkBoxBuffer.Checked == true) { double ddistance = Convert.ToDouble(textBoxBuffer.Text); pTopologicalOperator = pGeometry as ITopologicalOperator; pGeometry = pTopologicalOperator.Buffer(ddistance); pTopologicalOperator.Simplify(); //ʹ���˹�ϵ�����ȷ //MainAxMapControl.FlashShape(pGeometry, 2, 500, null);//��˸����֤��������ȷ��� } frmPrompt.WindowState = FormWindowState.Minimized; frmPrompt.Dispose(); System.Windows.Forms.Application.DoEvents(); object m_fillsymbol; //�����drawshape�IJ���������object�� IRgbColor pRgb = new RgbColorClass(); // ��ȡIRGBColor�ӿ� pRgb.Red = 255; // ������ɫ���� ILineSymbol outline = new SimpleLineSymbolClass(); // ��ȡILine���Žӿ� outline.Width = 5; outline.Color = pRgb; ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass();// ��ȡIFillSymbol�ӿ� simpleFillSymbol.Outline = outline; simpleFillSymbol.Color = pRgb; simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSBackwardDiagonal; m_fillsymbol = simpleFillSymbol; //MainAxMapControl.DrawShape(pGeometry, ref m_fillsymbol); MainAxMapControl.FlashShape(pGeometry, 3, 500, m_fillsymbol);//��˸�����û�֪����ǰ��"����ͼ��"����״ ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pGeometry; pSpatialFilter.SpatialRel = pSpatialRel; //���Ǹ�ȫ�ֱ��� if (checkBoxUseSelectedOnly.Checked == true) pSpatialFilter.GeometryField = "Shape"; //��ʹ����ѡ�е�Ԫ����Ϊ��ɸѡͼ�㡱ʱ�� //�����������ȥ���geometryfield����Ϊpfeaturelayer(����ͼ��)Ϊ�� else pSpatialFilter.GeometryField = pFeatureLayer.FeatureClass.ShapeFieldName; return pSpatialFilter; } catch (Exception ex) { MessageBox.Show("���ɡ�����ͼ�㡱����!���� | " + ex.Message); frmPrompt.Dispose(); return null;//��������spatialfitler } }
private bool IntersectAll(IFeatureClass lineLayer, IPolygon polygon2, List<ziduan> list) { try { if (radioBtnKJ.Checked && polygon2 != null) { // 根据组合成的面裁剪压力等值线 SpatialFilterClass qfilter = new SpatialFilterClass(); qfilter.Geometry = polygon2; qfilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor qfeatureCursor = lineLayer.Search(qfilter, false); if (qfeatureCursor != null) { IFeature feature = qfeatureCursor.NextFeature(); IGeometryArray geometryArray = new GeometryArrayClass(); while (feature != null) { geometryArray.Add(feature.Shape); feature = qfeatureCursor.NextFeature(); } IGeometryServer2 geometryServer2 = new GeometryServerClass(); IGeometryArray geometryArray2 = geometryServer2.Intersect(polygon2.SpatialReference, geometryArray, polygon2); //DataEditCommon.DeleteFeatureByWhereClause(lineLayer, ""); IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer; DataEditCommon.CreateFeature(pFeatureLayer.FeatureClass, geometryArray2, list); } } return true; } catch { return false; } }
private void btnSelect_Click(object sender, EventArgs e) { ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null; ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null; ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null; // Create a CancelTracker ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null; ISpatialFilter pSpatFilt = null; IFeatureLayer pFL = null; IFeatureCursor pFCurs = null; IFeature pFeat = null; ISimpleJunctionFeature pSimpFeat = null; // Create an edit operation enabling undo/redo try { (_app.Document as IMxDocument).FocusMap.ClearSelection(); trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass(); // Set the properties of the Step Progressor System.Int32 int32_hWnd = _app.hWnd; progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass(); stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; stepProgressor.MaxRange = lstJunctionLayers.Items.Count; stepProgressor.StepValue = 1; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1"); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = true; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1"); progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe; progressDialog.ShowDialog(); for (int i = 0; i < lstJunctionLayers.Items.Count; i++) { bool boolean_Continue = trackCancel.Continue(); if (!boolean_Continue) { return; } progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_2") + lstJunctionLayers.Items[i].ToString(); if (lstJunctionLayers.GetItemCheckState(i) == CheckState.Checked) { bool FCorLayer = true; pFL = (IFeatureLayer)Globals.FindLayer(_app, lstJunctionLayers.Items[i].ToString(), ref FCorLayer); if (pFL != null) { pSpatFilt = new SpatialFilterClass(); pSpatFilt.Geometry = _env as IGeometry; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatFilt.GeometryField = pFL.FeatureClass.ShapeFieldName; int featCnt = pFL.FeatureClass.FeatureCount(pSpatFilt); if (featCnt > 0) { pFCurs = pFL.Search(pSpatFilt, true); pFeat = pFCurs.NextFeature(); int loopCnt = 1; while (pFeat != null) { boolean_Continue = trackCancel.Continue(); if (!boolean_Continue) { return; } stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_3") + loopCnt + A4LGSharedFunctions.Localizer.GetString("Of") + featCnt; if (pFeat is SimpleJunctionFeature) { pSimpFeat = (ISimpleJunctionFeature)pFeat; if (pSimpFeat.EdgeFeatureCount >= numMinEdge.Value && pSimpFeat.EdgeFeatureCount <= numMaxEdge.Value) { (_app.Document as IMxDocument).FocusMap.SelectFeature(pFL as ILayer, pFeat); } } loopCnt++; pFeat = pFCurs.NextFeature(); } } } } stepProgressor.Step(); } } catch (Exception Ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("SltByJctCountLbl_22") + "\r\n" + Ex.Message); } finally { if (progressDialog != null) { progressDialog.HideDialog(); } progressDialogFactory = null; stepProgressor = null; progressDialog = null; trackCancel = null; pSpatFilt = null; pFL = null; if (pFCurs != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pFCurs); } pFCurs = null; pFeat = null; pSimpFeat = null; this.Hide(); (_app.Document as IMxDocument).ActiveView.Refresh(); MessageBox.Show((_app.Document as IMxDocument).FocusMap.SelectionCount + A4LGSharedFunctions.Localizer.GetString("SltByJctCountMess_1")); } }
//////////////////////////////////////////////////////////////////////// // METHOD: PopulateAOIListUsingOverlapFeatureClass private bool PopulateAOIListUsingOverlapFeatureClass(IJTXJob2 pParentJob, ref IArray aoiList) { try { // Make sure all the information exists to get the data workspace if (pParentJob.ActiveDatabase == null) { MessageBox.Show("Unable to proceed: Please set the data workspace for this job."); return false; } if (pParentJob.AOIExtent == null) { MessageBox.Show("Unable to proceed: Please assign the AOI for this job."); return false; } // Get the feature workspace from the current data workspace IJTXDatabase2 pJTXDB = (IJTXDatabase2)m_ipDatabase; string activeDBID = pParentJob.ActiveDatabase.DatabaseID; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)pJTXDB.GetDataWorkspace(activeDBID, pParentJob.VersionExists() ? pParentJob.VersionName : ""); if (featureWorkspace == null) { MessageBox.Show("Unable to connect to Data Workspace"); return false; } IFeatureClass featureClass = null; try { featureClass = featureWorkspace.OpenFeatureClass(m_AOIOverlapFeatureClassName); } catch (Exception ex) { MessageBox.Show("Unable to connect to feature class to generate AOIs: " + m_AOIOverlapFeatureClassName + "\n Error: " + ex.ToString()); return false; } // Get all features that intersect the parent job's AOI // // Note: The parent job's AOI is shrunk very slightly so features that merely adjoin the parent's AOI // are *not* returned. Only features that have some part of their actual area intersecting the parent's // AOI are returned. ISpatialFilter spatialFilter = new SpatialFilterClass(); ITopologicalOperator topOp = (ITopologicalOperator)pParentJob.AOIExtent; IPolygon slightlySmallerExtent = (IPolygon)topOp.Buffer(-0.0001); spatialFilter.Geometry = slightlySmallerExtent; spatialFilter.GeometryField = featureClass.ShapeFieldName; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false); aoiList = new ArrayClass(); IFeature feature = null; while ((feature = featureCursor.NextFeature()) != null) { aoiList.Add(feature.Shape); } // Explicitly release the cursor. Marshal.ReleaseComObject(featureCursor); } catch (Exception ex) { throw new Exception("Unable to create AOIs based on feature class: " + m_AOIOverlapFeatureClassName + ". " + ex.ToString()); } return true; }
public static void SplitLines(IApplication app, string SplitSuspendAA, double SplitAtLocationSnap, double SkipDistance) { IProgressDialogFactory progressDialogFactory = null; ITrackCancel trackCancel = null; IStepProgressor stepProgressor = null; IProgressDialog2 progressDialog = null; ICommandItem pCmd = null; IEditLayers eLayers = null; IEditor editor = null; IMxDocument mxdoc = null; IMap map = null; IFeatureLayer fLayer = null; IFeatureSelection fSel = null; UID geoFeatureLayerID = null; IEnumLayer enumLayer = null; List<IFeatureLayer> pointLayers = null; ILayer layer = null; List<IFeatureLayer> lineLayers; List<MergeSplitGeoNetFeatures> m_Config = null; IPoint pSplitPnt = null; ISet pSet = null; IFeature pSplitResFeat = null; try { m_Config = ConfigUtil.GetMergeSplitConfig(); if (SplitSuspendAA.ToUpper() == "TRUE") { pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app); if (pCmd != null) { pCmd.Execute(); } } editor = Globals.getEditor(app); if (editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5")); return; } //Get enumeration of editable layers eLayers = (IEditLayers)editor; mxdoc = (IMxDocument)app.Document; map = editor.Map; int i = 0; int total = 0; //Get enumeration of feature layers geoFeatureLayerID = new UIDClass(); geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true); // Create list of visible point layers with selected feature(s) pointLayers = new List<IFeatureLayer>(); lineLayers = new List<IFeatureLayer>(); enumLayer.Reset(); layer = enumLayer.Next(); while (layer != null) { fLayer = (IFeatureLayer)layer; if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint) && (fLayer.Visible)) { fSel = fLayer as IFeatureSelection; if (fSel.SelectionSet.Count > 0) { total += fSel.SelectionSet.Count; pointLayers.Add(fLayer); } } else if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline) && (fLayer.Visible)) { if (eLayers.IsEditable(fLayer)) lineLayers.Add(fLayer); } layer = enumLayer.Next(); } //ProgressBar progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass(); // Create a CancelTracker trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass(); // Set the properties of the Step Progressor System.Int32 int32_hWnd = app.hWnd; stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; stepProgressor.MaxRange = total; stepProgressor.StepValue = 1; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_10"); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Set the properties of the ProgressDialog progressDialog.CancelEnabled = true; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "."; progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile; //Create an edit operation enabling undo/redo editor.StartOperation(); ICursor pointCursor = null; IFeatureSelection pointSel = null; IFeature pointFeature = null; ISpatialFilter sFilter = null; IFeatureSelection lineSel = null; IFeatureCursor lineCursor = null; IFeature lineFeature = null; //IFeatureEdit2 featureEdit = null; //Determine if point is at end of this line (if so skip) //ITopologicalOperator topoOp = null; //IPolygon poly = null; //IRelationalOperator relOp = null; //ICurve curve = null; try { // step through all points and split the lines that intersect them foreach (IFeatureLayer pointLayer in pointLayers) { pointSel = pointLayer as IFeatureSelection; pointSel.SelectionSet.Search(null, false, out pointCursor); pointFeature = pointCursor.NextRow() as IFeature; while (!(pointFeature == null)) { foreach (IFeatureLayer lineLayer in lineLayers) { sFilter = new SpatialFilterClass(); sFilter.Geometry = pointFeature.ShapeCopy; sFilter.GeometryField = lineLayer.FeatureClass.ShapeFieldName; sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; lineSel = lineLayer as IFeatureSelection; lineCursor = lineLayer.Search(sFilter, false); lineFeature = lineCursor.NextFeature(); IList<MergeSplitFlds> pFldsNames = new List<MergeSplitFlds>(); string strFormValu = "{0:0.##}"; if (m_Config.Count > 0) { foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields) { int idx = Globals.GetFieldIndex(lineLayer.FeatureClass.Fields, FldNam.Name); if (idx > -1) pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule, FldNam.SplitRule)); } strFormValu = m_Config[0].SplitFormatString; } while (!(lineFeature == null)) { Globals.splitLineWithPoint(lineFeature, pointFeature.Shape as IPoint, SplitAtLocationSnap, pFldsNames, strFormValu,app); //featureEdit = lineFeature as IFeatureEdit2; ////Determine if point is at end of this line (if so skip) //topoOp = pointFeature.Shape as ITopologicalOperator; //poly = topoOp.Buffer(SkipDistance) as IPolygon; //relOp = poly as IRelationalOperator; //curve = lineFeature.Shape as ICurve; //if (!(relOp.Contains(curve.FromPoint)) & // !(relOp.Contains(curve.ToPoint))) //{ // pSplitPnt = pointFeature.ShapeCopy as IPoint; // double dblHighVal = 0; // double dblLowVal = 0; // int intHighIdx = -1; // int intLowIdx = -1; // foreach (MergeSplitFlds FldNam in pFldsNames) // { // FldNam.Value= lineFeature.get_Value(FldNam.FieldIndex).ToString(); // if (FldNam.SplitType.ToUpper() == "MAX") // { // if (FldNam.Value != null) // { // if (FldNam.Value != "") // { // dblHighVal = Convert.ToDouble(FldNam.Value); // intHighIdx = FldNam.FieldIndex; // } // } // } // else if (FldNam.SplitType.ToUpper() == "MIN") // { // if (FldNam.Value != null) // { // if (FldNam.Value != "") // { // dblLowVal = Convert.ToDouble(FldNam.Value); // intLowIdx = FldNam.FieldIndex; // } // } // } // } // if (intHighIdx > -1 && intLowIdx > -1) // { // double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length; // double splitDist = Globals.PointDistanceOnLine(pSplitPnt, lineFeature.Shape as IPolyline, 2, out pSplitPnt); // double percentSplit = splitDist / len; // double dblMidVal; // if (m_Config[0].SplitFormatString == "") // { // dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit); // } // else // { // dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit))); // } // //Split feature // pSet = featureEdit.SplitWithUpdate(pSplitPnt); // if (pSet.Count == 1) // { // while ((pSplitResFeat = pSet.Next() as IFeature) != null) // { // if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y) // { // pSplitResFeat.set_Value(intHighIdx, dblMidVal); // } // else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y) // { // pSplitResFeat.set_Value(intLowIdx, dblMidVal); // } // } // } // if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y) // { // lineFeature.set_Value(intHighIdx, dblMidVal); // } // else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y) // { // lineFeature.set_Value(intLowIdx, dblMidVal); // } // }else // pSet = featureEdit.SplitWithUpdate(pSplitPnt); // pSplitPnt = null; //} lineFeature = lineCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(lineCursor); } //Update progress bar i += 1; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "."; stepProgressor.Step(); ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar; statusBar.set_Message(0, i.ToString()); //Check if the cancel button was pressed. If so, stop process if (!trackCancel.Continue()) { break; } pointFeature = (IFeature)pointCursor.NextRow(); } } } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5")); return; } finally { if (pointCursor != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pointCursor); } pointCursor = null; pointSel = null; pointFeature = null; sFilter = null; lineSel = null; lineCursor = null; lineFeature = null; //featureEdit = null; //topoOp = null; //poly = null; //relOp = null; //curve = null; } progressDialog.HideDialog(); //Stop the edit operation editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9")); } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5")); return; } finally { pSet = null; pSplitPnt = null; if (SplitSuspendAA.ToUpper() == "TRUE") { pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app); if (pCmd != null) { pCmd.Execute(); } pCmd = null; } if (progressDialog != null) progressDialog.HideDialog(); progressDialogFactory = null; trackCancel = null; stepProgressor = null; progressDialog = null; pCmd = null; eLayers = null; editor = null; mxdoc = null; map = null; fLayer = null; fSel = null; geoFeatureLayerID = null; enumLayer = null; pointLayers = null; layer = null; lineLayers = null; pSplitResFeat = null; } }
public static void CreateJumps(IApplication app, JumpTypes jumpType, double jumpDistance) { IProgressDialog2 progressDialog = default(IProgressDialog2); IProgressDialogFactory progressDialogFactory = null; ITrackCancel trackCancel = null; IStepProgressor stepProgressor = null; ICursor lineCursor = null; IEditor editor = null; IFeature lineFeature = null; IMxDocument mxdoc = null; IMap map = null; UID geoFeatureLayerID = null; IEnumLayer enumLayer = null; IEditLayers eLayers = null; List<IFeatureLayer> lineLayers = null; ILayer layer = null; IFeatureLayer fLayer = null; IFeatureSelection fSel = null; try { //Get editor editor = Globals.getEditor(app); if (editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6")); return; } //ProgressBar progressDialogFactory = new ProgressDialogFactoryClass(); // Create a CancelTracker trackCancel = new CancelTrackerClass(); // Set the properties of the Step Progressor Int32 int32_hWnd = editor.Parent.hWnd; stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; // stepProgressor.MaxRange = itotal stepProgressor.StepValue = 1; stepProgressor.Message = ""; stepProgressor.Hide(); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = false; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_12") +"..."; progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_12"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe; mxdoc = (IMxDocument)app.Document; map = editor.Map; //Get enumeration of feature layers geoFeatureLayerID = new UIDClass(); geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true); //Get enumeration of editable layers eLayers = (IEditLayers)editor; // Create list of visible line layers with selected feature(s) lineLayers = new List<IFeatureLayer>(); enumLayer.Reset(); layer = enumLayer.Next(); while (layer != null) { fLayer = (IFeatureLayer)layer; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_2") + fLayer.Name; if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline) && (fLayer.Visible)) { if (eLayers.IsEditable(fLayer)) { fSel = fLayer as IFeatureSelection; if (fSel.SelectionSet.Count > 0) { stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_3") + fLayer.Name; lineLayers.Add(fLayer); } } } layer = enumLayer.Next(); } if (lineLayers.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_7")); return; } // Create an edit operation enabling undo/redo editor.StartOperation(); IPointCollection linePointCollection = null; ISpatialFilter spatialFilter = null; IFeatureCursor featureCursor = null; IFeature crossFeature = null; ITopologicalOperator topologicalOP = null; ITopologicalOperator topologicalOP2 = null; IPointCollection intersectPointCollection = null; IPoint intersectPoint = null; IPoint outPoint = null; IPoint beginPoint = null; IPoint endPoint = null; IActiveView activeView = null; IInvalidArea invalid = null; IEnvelope ext = null; ISegmentCollection testSegmentColl = null; ISegment testSegment = null; ISegmentCollection segmentColl = null; ISegmentCollection segmentCollNew = null; IConstructCircularArc constructCircArc = null; ISegment curveSegment = null; //IProximityOperator proximityOP = null; IPolycurve3 selCurve = null; IPolycurve3 selCurveB = null; IPolycurve3 crossCurve = null; IPolycurve3 crossCurveB = null; IPolycurve3 testSelCurve = null; IPolycurve3 testSelCurveB = null; object _missing = null; IFeatureSelection lineSel = null; ISelectionSet2 sel = null; IZAware pZAware = null; ISegmentCollection testSegmentColl2 = null; ISegment testSegment2 = null; IGeometryDef pGeometryDefTest = null; IFields pFieldsTest = null; IField pFieldTest = null; IGeoDataset pDS = null; try { activeView = map as IActiveView; invalid = new InvalidAreaClass(); invalid.Display = editor.Display; linePointCollection = (IPointCollection)new PolylineClass(); spatialFilter = new SpatialFilterClass(); intersectPoint = new PointClass(); outPoint = new PointClass(); //used for curve test on cross feature bool testProjectOnto; bool testCreatePart; bool testSplitHappened; int testNewPartIndex; int testNewSegmentIndex; //used for curve test on selected feature bool testProjectOnto2; bool testCreatePart2; bool testSplitHappened2; int testNewPartIndex2; int testNewSegmentIndex2; //ICurve lineCurve; double totalDistance; double distAlongCurve = 0; double distFromCurve = 0; bool boolRightSide = false; //test the amount of needed space for the inserted curve double remainderDistance = 0; double pointDistance = 0; bool projectOnto; bool createPart; bool splitHappenedBefore; bool splitHappenedAfter; int newPartIndexBegin; int newSegmentIndexBegin; int newPartIndexEnd; int newSegmentIndexEnd; _missing = Type.Missing; // Step through all line layers with selection sets foreach (IFeatureLayer lineLayer in lineLayers) { stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4a") + lineLayer.Name; // Get cursor of selected lines lineSel = (IFeatureSelection)lineLayer; sel = lineSel.SelectionSet as ISelectionSet2; sel.Search(null, false, out lineCursor); // Process each selected line int idx = 0; while ((lineFeature = (IFeature)lineCursor.NextRow()) != null) { idx++; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4b") + idx + A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4c") + lineLayer.Name; if (lineFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline) { selCurve = (IPolycurve3)lineFeature.ShapeCopy; pZAware = selCurve as IZAware; if (pZAware.ZAware) { pZAware.ZAware = false; } // Get cursor of crossing features spatialFilter.Geometry = selCurve; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; featureCursor = lineLayer.Search(spatialFilter, false); // Process each crossing feature while ((crossFeature = (IFeature)featureCursor.NextFeature()) != null) { topologicalOP = (ITopologicalOperator)crossFeature.Shape; //topologicalOP2 = (ITopologicalOperator)polylinePointCollection; topologicalOP2 = (ITopologicalOperator)selCurve; topologicalOP2.Simplify(); topologicalOP.Simplify(); intersectPointCollection = (IPointCollection)topologicalOP.Intersect((IGeometry)selCurve, esriGeometryDimension.esriGeometry0Dimension); for (int i = 0; i < intersectPointCollection.PointCount; i++) { intersectPoint = intersectPointCollection.get_Point(i); //Determine if the crossing segement is an arc. //Continue if it is not. testProjectOnto = true; testCreatePart = false; crossCurve = (IPolycurve3)crossFeature.ShapeCopy; crossCurve.SplitAtPoint(intersectPoint, testProjectOnto, testCreatePart, out testSplitHappened, out testNewPartIndex, out testNewSegmentIndex); crossCurveB = (IPolycurve3)crossFeature.ShapeCopy; testSegmentColl = crossCurveB as ISegmentCollection; testSegment = testSegmentColl.get_Segment(testNewSegmentIndex - 1); if (testSegment.GeometryType != esriGeometryType.esriGeometryCircularArc) { //Determine if the current location of the selected line is an arc. //Continue if it is not. testProjectOnto2 = true; testCreatePart2 = false; testSelCurve = (IPolycurve3)lineFeature.ShapeCopy; testSelCurve.SplitAtPoint(intersectPoint, testProjectOnto2, testCreatePart2, out testSplitHappened2, out testNewPartIndex2, out testNewSegmentIndex2); testSelCurveB = (IPolycurve3)lineFeature.ShapeCopy; testSegmentColl2 = testSelCurveB as ISegmentCollection; testSegment2 = testSegmentColl2.get_Segment(testNewSegmentIndex2 - 1); if (testSegment2.GeometryType != esriGeometryType.esriGeometryCircularArc) { //Find distance along the original selected line //focusPolyline = (IPolyline)lineFeature.ShapeCopy; selCurveB = (IPolycurve3)lineFeature.ShapeCopy; selCurveB.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, intersectPoint, false, outPoint, ref distAlongCurve, ref distFromCurve, ref boolRightSide); remainderDistance = selCurveB.Length - distAlongCurve; totalDistance = distAlongCurve + jumpDistance; //Continue if there is enough room if ((selCurveB.Length >= (jumpDistance / 2)) && (remainderDistance >= (jumpDistance / 2))) { //find the points where the curve will begin and end beginPoint = new PointClass(); endPoint = new PointClass(); selCurveB.QueryPoint(esriSegmentExtension.esriNoExtension, (distAlongCurve - (jumpDistance / 2)), false, beginPoint); selCurveB.QueryPoint(esriSegmentExtension.esriNoExtension, (distAlongCurve + (jumpDistance / 2)), false, endPoint); //split the original line at the two points (vertices for begin and end of new curve) projectOnto = true; createPart = false; selCurveB.SplitAtPoint(beginPoint, projectOnto, createPart, out splitHappenedBefore, out newPartIndexBegin, out newSegmentIndexBegin); selCurveB.SplitAtPoint(endPoint, projectOnto, createPart, out splitHappenedAfter, out newPartIndexEnd, out newSegmentIndexEnd); if ((splitHappenedBefore = true) && (splitHappenedAfter = true)) { //Create the curve segment and add it to the polyline constructCircArc = new CircularArcClass(); // proximityOP = (IProximityOperator)intersectPoint; //pointDistance = proximityOP.ReturnDistance(beginPoint); pointDistance = jumpDistance; //check for direction of line to always make the jump on top if (jumpType == JumpTypes.Over) if (endPoint.X > beginPoint.X) { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, false, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, true, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { if (endPoint.X <= beginPoint.X) { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, false, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, true, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } } curveSegment = constructCircArc as ISegment; if (curveSegment != null & curveSegment.Length > 0) { segmentCollNew = (ISegmentCollection)new PolylineClass(); segmentCollNew.AddSegment(curveSegment, ref _missing, ref _missing); segmentColl = (ISegmentCollection)selCurveB; segmentColl.ReplaceSegmentCollection(newSegmentIndexBegin, 1, segmentCollNew); string sShpName = lineLayer.FeatureClass.ShapeFieldName; pFieldsTest = lineLayer.FeatureClass.Fields; int lGeomIndex = pFieldsTest.FindField(sShpName); pFieldTest = pFieldsTest.get_Field(lGeomIndex); pGeometryDefTest = pFieldTest.GeometryDef; bool bZAware; bool bMAware; //Determine if M or Z aware bZAware = pGeometryDefTest.HasZ; bMAware = pGeometryDefTest.HasM; if (bZAware) { // IGeometry pGeo = new PolylineClass(); pZAware = selCurveB as IZAware; if (pZAware.ZAware) { } else { pZAware.ZAware = true; //pZAware.DropZs(); } // pZAware.DropZs(); IZ pZ = selCurveB as IZ; pZ.SetConstantZ(0); } if (bMAware) { } pDS = lineLayer.FeatureClass as IGeoDataset; selCurveB.SpatialReference = pDS.SpatialReference; lineFeature.Shape = (IGeometry)selCurveB; lineFeature.Store(); //Prepare to redraw area around feature ext = curveSegment.Envelope; ext.Expand(2, 2, true); invalid.Add(ext); } } } else { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_9")); } } } } } } } } } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6") + "\n" + ex.Message, ex.Source); } finally { // Refresh if (invalid!= null) invalid.Invalidate((short)esriScreenCache.esriAllScreenCaches); linePointCollection = null; spatialFilter = null; if (featureCursor != null) Marshal.ReleaseComObject(featureCursor); featureCursor = null; crossFeature = null; topologicalOP = null; topologicalOP2 = null; intersectPointCollection = null; intersectPoint = null; outPoint = null; beginPoint = null; endPoint = null; activeView = null; invalid = null; ext = null; testSegmentColl = null; testSegment = null; segmentColl = null; segmentCollNew = null; constructCircArc = null; curveSegment = null; //proximityOP = null; selCurve = null; selCurveB = null; crossCurve = null; crossCurveB = null; testSelCurve = null; testSelCurveB = null; _missing = null; lineSel = null; sel = null; pZAware = null; testSegmentColl2 = null; testSegment2 = null; pGeometryDefTest = null; pFieldsTest = null; pFieldTest = null; pDS = null; } // Stop the edit operation editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6")); } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6") + "\n" + ex.Message, ex.Source); return; } finally { if (lineCursor != null) { Marshal.ReleaseComObject(lineCursor); } // Cleanup if (progressDialog != null) { progressDialog.HideDialog(); //progressDialog = null; Marshal.ReleaseComObject(progressDialog); //progressDialogFactory = null; //Marshal.ReleaseComObject(progressDialogFactory); //trackCancel = null; //Marshal.ReleaseComObject(trackCancel); //stepProgressor = null; //Marshal.ReleaseComObject(stepProgressor); //appCursor = null; } progressDialog = null; progressDialogFactory = null; trackCancel = null; stepProgressor = null; lineCursor = null; editor = null; lineFeature = null; mxdoc = null; map = null; geoFeatureLayerID = null; enumLayer = null; eLayers = null; lineLayers = null; layer = null; fLayer = null; fSel = null; } }
private void calcZoneValuesFtr() { //Console.WriteLine("made it to the feature calculations"); bool makeDic = (ZoneClassCount || ZoneTypes.Contains(rasterUtil.zoneType.VARIETY) || ZoneTypes.Contains(rasterUtil.zoneType.ENTROPY) || ZoneTypes.Contains(rasterUtil.zoneType.ASM) || ZoneTypes.Contains(rasterUtil.zoneType.MINORITY) || ZoneTypes.Contains(rasterUtil.zoneType.MODE) || ZoneTypes.Contains(rasterUtil.zoneType.MEDIAN)); // //HashSet<byte> hByt = new HashSet<byte>(); // ISpatialReference sr = vRs.RasterInfo.SpatialReference; IEnvelope vrsEnv = vRs.RasterInfo.Extent; ISpatialFilter spFilt = new SpatialFilterClass(); spFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; spFilt.Geometry = vrsEnv; spFilt.GeometryField = ftrCls.ShapeFieldName; IFeatureCursor fCur = ftrCls.Search(spFilt, true); int zoneIndex = fCur.FindField(InZoneField); IFeature ftr = fCur.NextFeature(); while (ftr != null) { IGeometry geo = ftr.Shape; double z = System.Convert.ToDouble(ftr.get_Value(zoneIndex)); IPolygon4 poly = (IPolygon4)geo; if (needToProject) { poly.Project(sr); } IGeometryBag geoBag = poly.ExteriorRingBag; IGeometryCollection geoColl = (IGeometryCollection)geoBag; for (int g = 0; g < geoColl.GeometryCount; g++) { IGeometry geo2 = geoColl.Geometry[g]; IFunctionRasterDataset rs = rsUtil.clipRasterFunction(vRs, geo2, esriRasterClippingType.esriRasterClippingOutside); IEnvelope rsEnv = rs.RasterInfo.Extent; IRasterFunctionHelper rsFHelper = new RasterFunctionHelperClass(); rsFHelper.Bind(rs); //Console.WriteLine((rsEnv.Width / 30).ToString() + ", " + (rsEnv.Height / 30).ToString()); IRasterCursor rsCur = ((IRaster2)rsFHelper.Raster).CreateCursorEx(null); do { IPixelBlock pb = rsCur.PixelBlock; for (int p = 0; p < pb.Planes; p++) { zoneValueDic = zoneValueDicArr[p]; object[] zoneValue; double cnt = 0; double maxVl = Double.MinValue; double minVl = Double.MaxValue; double s = 0; double s2 = 0; Dictionary<double, int> uDic = null; if (zoneValueDic.TryGetValue(z, out zoneValue)) { cnt = System.Convert.ToDouble(zoneValue[0]); maxVl = System.Convert.ToDouble(zoneValue[1]); minVl = System.Convert.ToDouble(zoneValue[2]); s = System.Convert.ToDouble(zoneValue[3]); s2 = System.Convert.ToDouble(zoneValue[4]); uDic = (Dictionary<double, int>)zoneValue[5]; } else { zoneValue = new object[6]; zoneValue[0] = cnt; zoneValue[1] = maxVl; zoneValue[2] = minVl; zoneValue[3] = s; zoneValue[4] = s2; uDic = null; if (makeDic) { uDic = new Dictionary<double, int>(); } zoneValue[5] = uDic; } for (int r = 0; r < pb.Height; r++) { for (int c = 0; c < pb.Width; c++) { object vlo = pb.GetVal(p, c, r); if (vlo == null) { continue; } else { double vl = System.Convert.ToDouble(vlo); cnt++; if (vl > maxVl) maxVl = vl; if (vl < minVl) minVl = vl; s += vl; s2 += vl * vl; if (makeDic) { int cntVl = 0; if (uDic.TryGetValue(vl, out cntVl)) { uDic[vl] = cntVl += 1; } else { uDic.Add(vl, 1); } } } } } zoneValue[0] = cnt; zoneValue[1] = maxVl; zoneValue[2] = minVl; zoneValue[3] = s; zoneValue[4] = s2; zoneValue[5] = uDic; zoneValueDic[z] = zoneValue; } } while (rsCur.Next()); System.Runtime.InteropServices.Marshal.ReleaseComObject(rsCur); } ftr = fCur.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(fCur); }
//��˷�ٲ��ҹ����漰�ĵؿ� public static void UpStreamFindParcels(AxMapControl ppAxMapControl, IEnumNetEID pEnumResultEdges, IGeometricNetwork pGeoNetwork) { try { IFeatureLayer pFeatLayerSewerLines = FindFeatLayer("Sewer Lines", ppAxMapControl); IFeatureLayer pFeatLayerParcels = FindFeatLayer("Parcels", ppAxMapControl); //����ѡ���Sewer�������д������ΰ� IGeometryCollection pGeomBag = new GeometryBagClass(); object missing = Type.Missing; int lEID; int iUserClassID; int iUserID; int iUserSubID; INetElements pNetElements = pGeoNetwork.Network as INetElements; pEnumResultEdges.Reset(); IFeature pFeature; for (int j = 0; j <= pEnumResultEdges.Count - 1; j++) { lEID = pEnumResultEdges.Next(); pNetElements.QueryIDs(lEID, esriElementType.esriETEdge, out iUserClassID, out iUserID, out iUserSubID); pFeature = pFeatLayerSewerLines.FeatureClass.GetFeature(iUserID); pGeomBag.AddGeometry(pFeature.Shape, ref missing, ref missing); // MessageBox.Show(iUserClassID.ToString()+","+iUserID.ToString()+","+iUserSubID.ToString()); } //���пռ����˵��Ӳ��������ڲ��ҵؿ���Ϣ ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pGeomBag as IGeometry; pSpatialFilter.GeometryField = "Shape"; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; //��ý��浽�ĵؿ���Ϣ IFeatureCursor pFeatCursor = pFeatLayerParcels.FeatureClass.Search(pSpatialFilter, false); //���ӱ�ѡ��ĵؿ����ݵ���ͼ��ͼ��ͼ�������� ICompositeGraphicsLayer pComGraphicLayer = new CompositeGraphicsLayerClass(); ILayer pLayer = pComGraphicLayer as ILayer; pLayer.Name = "��Ӱ��ĵؿ�"; IGraphicsContainer pGraphicContainer = pComGraphicLayer as IGraphicsContainer; //������ѡ��ĵؿ鵽ͼ�������� ISimpleFillSymbol pSymFill = new SimpleFillSymbolClass(); IFillSymbol pFillSymbol = pSymFill as IFillSymbol; IRgbColor pRgbColor = new RgbColorClass(); pRgbColor.Red = 0; pRgbColor.Green = 200; pRgbColor.Blue = 100; pFillSymbol.Color = pRgbColor as IColor; ICartographicLineSymbol pCartoLine = new CartographicLineSymbolClass(); IRgbColor pRgbColor2 = new RgbColorClass(); pRgbColor2.Red = 100; pRgbColor2.Green = 200; pRgbColor2.Blue = 100; pCartoLine.Width = 2; pCartoLine.Color = pRgbColor2 as IColor; pFillSymbol.Outline = pCartoLine; //����������еؿ����������� IArray pFeatArray = new ArrayClass(); pFeature = pFeatCursor.NextFeature(); while (pFeature != null) { IElement pPolyElement = new PolygonElementClass(); IFillShapeElement pFillShapeElement = pPolyElement as IFillShapeElement; pPolyElement.Geometry = pFeature.Shape; pFillShapeElement.Symbol = pFillSymbol; pGraphicContainer.AddElement(pPolyElement, 0); pFeatArray.Add(pFeature); pFeature = pFeatCursor.NextFeature(); } ppAxMapControl.AddLayer(pGraphicContainer as ILayer); ppAxMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); //ma //frmUpstreamCreateOwnerList frmUpstreamCreateOwnerList1 = new frmUpstreamCreateOwnerList(ppAxMapControl,pFeatLayerParcels, pFeatArray); //frmUpstreamCreateOwnerList1.Show(); } catch (Exception eX) { MessageBox.Show(eX.Message); } }
private static void DeleteFeaturesAtPoint(IFeatureLayer targetLineFLayer, IPoint point, IFeatureLayer targetPointFLayer, int targetLineSubtype, double tolerenceForDelete, bool searchOnLayer) { ITopologicalOperator topoOp = null; IPolygon poly = null; ISpatialFilter sFilter = null; INetworkClass netClass = null; IFeatureClass orphanFC = null; INetworkFeature netFeature = null; IFeatureCursor fCursor = null; IFeature feature = null; IPolyline line = null; IEdgeFeature edgeFeature = null; ISimpleJunctionFeature toJunctionFeature = null; ISimpleJunctionFeature fromJunctionFeature = null; ISubtypes subt = null; try { topoOp = point as ITopologicalOperator; poly = topoOp.Buffer(tolerenceForDelete) as IPolygon; sFilter = new SpatialFilterClass(); sFilter.Geometry = poly; sFilter.GeometryField = targetLineFLayer.FeatureClass.ShapeFieldName; sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; netClass = targetLineFLayer.FeatureClass as INetworkClass; orphanFC = netClass.GeometricNetwork.OrphanJunctionFeatureClass; if (searchOnLayer) fCursor = targetLineFLayer.Search(sFilter, false); else fCursor = targetLineFLayer.FeatureClass.Search(sFilter, false); while ((feature = fCursor.NextFeature()) != null) { //Find connecting junctions netFeature = feature as INetworkFeature; if (netFeature != null) { edgeFeature = netFeature as IEdgeFeature; if (edgeFeature != null) { toJunctionFeature = edgeFeature.ToJunctionFeature as ISimpleJunctionFeature; fromJunctionFeature = edgeFeature.ToJunctionFeature as ISimpleJunctionFeature; } } //If subtypes are specified for the new lateral lines, delete only existing laterals with that subtype subt = feature as ISubtypes; line = feature.ShapeCopy as IPolyline; if (targetLineSubtype > -1 && subt != null) { int? thisSubtype = feature.get_Value(subt.SubtypeFieldIndex) as int?; if (thisSubtype != null && thisSubtype == targetLineSubtype) { feature.Delete(); DeleteTargetPoints(targetPointFLayer.FeatureClass, line, tolerenceForDelete); DeleteExisitingJunction(toJunctionFeature, targetLineFLayer); DeleteOrphanJunctions(orphanFC, line, tolerenceForDelete); } } //Otherwise, just delete each feature else { feature.Delete(); DeleteTargetPoints(targetPointFLayer.FeatureClass, line, tolerenceForDelete); DeleteExisitingJunction(toJunctionFeature, targetLineFLayer); DeleteOrphanJunctions(orphanFC, line, tolerenceForDelete); } } } catch (Exception ex) { MessageBox.Show("DeleteFeatureAtPoint\r\n" + ex.Message); } finally { if (fCursor != null) Marshal.ReleaseComObject(fCursor); topoOp = null; poly = null; sFilter = null; netClass = null; orphanFC = null; netFeature = null; fCursor = null; feature = null; line = null; edgeFeature = null; toJunctionFeature = null; fromJunctionFeature = null; subt = null; } }
private void intersectLayerDetailsFunctions(ILayer pLay, List<IGeometry> pGeos, AAState.intersectOptions strOpt, ref bool found, ref List<Globals.OptionsToPresent> strFiles, ref ESRI.ArcGIS.Geodatabase.IObject inObject, int intFldIdx, List<string> MatchPattern) { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain194") + pLay.Name); IRasterLayer pRasLay = null; IEnvelope pEnv = null; IRelationalOperator pRel = null; IRelationalOperator2 pRel2 = null; ISpatialFilter pSpatFilt = null; IFeatureLayer pFLay = null; try { if (pLay is IRasterLayer) { pRasLay = pLay as IRasterLayer; AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain195") + pRasLay.Name); pEnv = pRasLay.AreaOfInterest; pRel = pEnv as IRelationalOperator; pRel2 = pEnv as IRelationalOperator2; foreach (IGeometry pGeo in pGeos) { if (pRel.Crosses(pGeo) || pRel.Touches(pGeo) || pRel.Overlaps(pGeo) || pRel2.ContainsEx(pGeo, esriSpatialRelationExEnum.esriSpatialRelationExClementini)) { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain196") + pRasLay.Name); string pathForLay = Globals.GetPathForALayer(pLay); switch (formatString) { case "P": if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; case "N": if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; default: if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; } } } } else if (pLay is IFeatureLayer) { pFLay = pLay as IFeatureLayer; if (pFLay.FeatureClass == inObject.Class) { } else { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain195") + pFLay.Name); foreach (IGeometry pGeo in pGeos) { pSpatFilt = new SpatialFilterClass(); pSpatFilt.GeometryField = pFLay.FeatureClass.ShapeFieldName; pSpatFilt.Geometry = pGeo as IGeometry; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; if (pFLay.FeatureClass.FeatureCount(pSpatFilt) > 0) { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain196") + pFLay.Name); string pathForLay = Globals.GetPathForALayer(pLay); switch (formatString) { case "P": if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; case "N": if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name))) { strFiles.Add(new Globals.OptionsToPresent(0, pLay.Name, pLay.Name, pLay.Name)); } } else { inObject.set_Value(intFldIdx, pLay.Name); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; default: if (MatchPattern == null) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else if (MatchPattern.Count == 0) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } else { foreach (string MatPat in MatchPattern) { if (pathForLay.ToUpper().Contains(MatPat.ToUpper()) || pLay.Name.ToUpper().Contains(MatPat.ToUpper())) { if (strOpt == AAState.intersectOptions.PromptMulti) { if (!strFiles.Contains(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay))) { strFiles.Add(new Globals.OptionsToPresent(0, pathForLay, pathForLay, pathForLay)); } } else { inObject.set_Value(intFldIdx, pathForLay); pRasLay = null; pEnv = null; pRel = null; pRel2 = null; found = true; return; } } } } break; } } else { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain197") + pFLay.Name); } } } } else { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorChain198")); } } catch (Exception ex) { AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorError_14a") + ex.Message); } finally { pRasLay = null; pEnv = null; pRel = null; pRel2 = null; pSpatFilt = null; pFLay = null; } }
private void nw_query(IMapControlEvents2_OnMouseDownEvent e) { //axMapControl1 ILayer layer = m_datasource.GetAdministrativeMap().get_Layer(m_query_area_detail); ILayer layer_shiyi =null;// = axMapControl1.Map.get_Layer (m_selectedLayer); ILayer layer_cishi = null;//= axMapControl1.Map.get_Layer(m_selectedLayer); getLayer(m_query_area_detail, ref layer_shiyi, ref layer_cishi); //resolveNameRate(layer.Name); //resolveNameRange(layer.Name); //layer_name[1]; // axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerCrosshair; ESRI.ArcGIS.Geometry.IGeometry geometry = null; ESRI.ArcGIS.Geometry.Point pt = new ESRI.ArcGIS.Geometry.Point(); pt.X = e.mapX; pt.Y = e.mapY; geometry = pt as ESRI.ArcGIS.Geometry.IGeometry; // geometry = axMapControl1.TrackRectangle(); ISpatialFilter pSpatialFilter = new SpatialFilterClass(); IQueryFilter pQueryFilter = pSpatialFilter as ISpatialFilter; //设置过滤器的Geometry pSpatialFilter.Geometry = geometry; //设置空间关系类型 pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;//esriSpatialRelContains; //获取FeatureCursor游标 IFeatureLayer featureLayer = layer as IFeatureLayer; //获取featureLayer的featureClass IFeatureClass featureClass = featureLayer.FeatureClass; IFeatureCursor pFeatureCursor = featureClass.Search(pQueryFilter, true); //遍历FeatureCursor IFeature pFeature = pFeatureCursor.NextFeature(); //获取FeatureCursor游标 IFeatureLayer featureLayer1 = layer_shiyi as IFeatureLayer; //获取featureLayer的featureClass IFeatureClass featureClass1 = featureLayer1.FeatureClass; IFeatureCursor pFeatureCursor1 = featureClass1.Search(pQueryFilter, true); //遍历FeatureCursor IFeature pFeature1 = pFeatureCursor1.NextFeature(); //获取FeatureCursor游标 IFeatureLayer featureLayer2 = layer_cishi as IFeatureLayer; //获取featureLayer的featureClass IFeatureClass featureClass2 = featureLayer2.FeatureClass; IFeatureCursor pFeatureCursor2 = featureClass2.Search(pQueryFilter, true); //遍历FeatureCursor IFeature pFeature2 = pFeatureCursor2.NextFeature(); //QueryForm qf =new QueryForm(m_bin_path); m_qf.m_mapControl = axMapControl1; m_qf.m_featureLayer = featureLayer; m_qf.m_query_name = m_range_en; m_qf.m_mucao = m_mucao; m_qf.QueryForm_SetText( m_mucao); //qf.m_layername = "当前图层:" + layer.Name; System.Windows.Forms.ListView listView_data = m_qf.nw_getListView(); listView_data.Items.Clear(); m_qf.m_range = m_range; listView_data.Columns.Clear(); listView_data.Columns.Add(m_range + "名", 120, HorizontalAlignment.Left);//省名,, listView_data.Columns.Add("适宜面积比", 120, HorizontalAlignment.Left); listView_data.Columns.Add("适宜面积", 120, HorizontalAlignment.Left); listView_data.Columns.Add("次适宜面积比", 120, HorizontalAlignment.Left); listView_data.Columns.Add("次适宜面积", 120, HorizontalAlignment.Left); string area1 = "area" + m_rate_en; string rate1 = "rate" + m_rate_en; string area2 = "area" + m_rate_en; string rate2 = "rate" + m_rate_en; if(pFeature1 != null) { for (int i = 0; i < pFeature1.Fields.FieldCount;++i ) { if (pFeature1.Fields.Field[i].Name.IndexOf("area_") > -1) { area1 = pFeature1.Fields.Field[i].Name; } else if(pFeature1.Fields.Field[i].Name.IndexOf("rate_")>-1) { rate1 = pFeature1.Fields.Field[i].Name; } } } if (pFeature2 != null) { for (int i = 0; i < pFeature2.Fields.FieldCount; ++i) { if (pFeature2.Fields.Field[i].Name.IndexOf("area_") > -1) { area2 = pFeature2.Fields.Field[i].Name; } else if (pFeature2.Fields.Field[i].Name.IndexOf("rate_") > -1) { rate2 = pFeature2.Fields.Field[i].Name; } } } System.Collections.Generic.List<IFeature> pList = new System.Collections.Generic.List<IFeature>(); while(pFeature != null) { // ESRI.ArcGIS.Geodatabase.IField filed = pFeature.Fields.FindField("rate_shiyi"); //ESRI.ArcGIS.Geodatabase.IRowBuffer buff = (IRowBuffer)pFeature; //string str = buff.Value[pFeature.Fields.FindField("NAME")].ToString(); //ESRI.ArcGIS.Geodatabase.IRow row = pFeature.Table.GetRow(pFeature.OID); //string str = row.Value[].ToString(); //double a = System.Convert.ToDouble(row.get_Value(pFeature.Fields.FindField(nw_getQueryFiledName()))); //pList.Add() //pList.Add(pFeature.); ListViewItem lvi = new ListViewItem(); // ESRI.ArcGIS.Geodatabase.IRowBuffer buff = (IRowBuffer)pFeature; m_nactcn= lvi.Text = pFeature.Value[pFeature.Fields.FindField(m_range_en)].ToString(); if (pFeature1!= null) { lvi.SubItems.Add(pFeature1.Value[pFeature1.Fields.FindField(rate1)].ToString());//rate_shiyi lvi.SubItems.Add(System.Convert.ToDecimal(pFeature1.Value[pFeature1.Fields.FindField(area1)]).ToString("N"));// } if (pFeature2 != null) { lvi.SubItems.Add(pFeature2.Value[pFeature2.Fields.FindField(rate2)].ToString());//rate_shiyi lvi.SubItems.Add(System.Convert.ToDecimal(pFeature2.Value[pFeature2.Fields.FindField(area2)]).ToString("N"));// } bool isNotAllNull = false; for (int i=1;i<lvi.SubItems.Count;++i) { if(lvi.SubItems[i].Text.Trim() != "") { //MessageBox.Show(lvi.SubItems[i].Text.Trim()); isNotAllNull = true; break; } } if(isNotAllNull) listView_data.Items.Add(lvi); pFeature = pFeatureCursor.NextFeature(); if(pFeature1 != null) pFeature1 = pFeatureCursor1.NextFeature(); if (pFeature2 != null) pFeature2 = pFeatureCursor2.NextFeature(); } if (listView_data.Items.Count == 0) { MessageBox.Show("暂无数据!"); return; } axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerDefault; m_qf.Show(); highLight(featureLayer); /* if (pFeature != null) { axMapControl1.Map.SelectFeature(axMapControl1.get_Layer(0), pFeature); axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null); } axMapControl1.Map.SelectByShape(geometry, null, false); axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);*/ }
private static void DeleteTargetPoints(IFeatureClass targetFC, IPolyline line, double tolerenceForDelete) { ITopologicalOperator topoOpLine = null; IPolygon poly2 = null; ISpatialFilter sFilter2 = null; IFeatureCursor fCursor2 = null; IFeature feature2 = null; try { if (targetFC != null && line != null) { //Buffer the line topoOpLine = line as ITopologicalOperator; poly2 = topoOpLine.Buffer(tolerenceForDelete) as IPolygon; sFilter2 = new SpatialFilterClass(); sFilter2.Geometry = poly2; sFilter2.GeometryField = targetFC.ShapeFieldName; sFilter2.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; fCursor2 = targetFC.Search(sFilter2, false); while ((feature2 = fCursor2.NextFeature()) != null) { feature2.Delete(); } } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "DeleteTargetPoints: " + ex.Message); } finally { if (fCursor2 != null) Marshal.ReleaseComObject(fCursor2); topoOpLine = null; poly2 = null; sFilter2 = null; fCursor2 = null; feature2 = null; } }
private void adjustXTableFtr(IGeometry iGeometry) { string clFldName = dgc.IndependentFieldNames[0]; ISpatialFilter sf = new SpatialFilterClass(); sf.Geometry = iGeometry; sf.GeometryField = ftrMap.ShapeFieldName; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; double tN = 0; IFeatureCursor ftrCur = ftrMap.Search(sf, false); IFeature ftr = ftrCur.NextFeature(); int fldIndex = ftrCur.FindField(clFldName); while (ftr != null) { object vlObj = ftr.get_Value(fldIndex); if (vlObj == null) { } else { string vl = vlObj.ToString(); int vlIndex = olabels.IndexOf(vl); nCnts[vlIndex] = nCnts[vlIndex] + 1; tN += 1; } ftr = ftrCur.NextFeature(); } updateXTable(tN); }
/// <summary> /// Queries the specified layer id. /// </summary> /// <param name="layerId">The layer id.</param> /// <param name="spatialFilter">The spatial filter.</param> /// <param name="attributeFilter">The attribute filter.</param> /// <param name="transformationId">The transformation id.</param> /// <returns></returns> public RecordSet Query(int layerId, IGeometry spatialFilter, string attributeFilter, string geometryFieldName, ExportOutputSpatialReference outputSr) { ISpatialFilter filter = new SpatialFilterClass(); RecordSet recordSet = null; IQueryResultOptions resultOptions; IMapTableDescription tableDesc; IQueryResult result; try { //set the filter properties filter.Geometry = spatialFilter; //todo //the geometry field name comes in via the request, but could we look at layerinfo from the map server? //the type of spatial reference systen should be passed in: i.e. geographic or projected //already implemented method: GetFeatureClassShapeFieldName which does this //create desired output spatial reference if (outputSr != null) { Type t = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment"); System.Object obj = Activator.CreateInstance(t); ISpatialReferenceFactory srFact = obj as ISpatialReferenceFactory; ISpatialReference sr; if (outputSr.CoordinateSystemType == "projected") { sr = srFact.CreateProjectedCoordinateSystem((int)outputSr.Wkid); } else sr = srFact.CreateGeographicCoordinateSystem((int)outputSr.Wkid); filter.GeometryField = geometryFieldName; filter.set_OutputSpatialReference(geometryFieldName, sr); } filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; if (!String.IsNullOrEmpty(attributeFilter)) filter.WhereClause = attributeFilter; //set the result options resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject; //apply transformation if required if (outputSr != null) { if (outputSr.TransformationId != null) { Type factoryType = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment"); ISpatialReferenceFactory3 srFactory = (ISpatialReferenceFactory3)Activator.CreateInstance(factoryType); IGeoTransformation gt; gt = srFactory.CreateGeoTransformation((int)outputSr.TransformationId) as IGeoTransformation; resultOptions.GeoTransformation = gt; } } tableDesc = GetTableDesc(_server, layerId); result = _server.QueryData(_server.DefaultMapName, tableDesc, filter, resultOptions); //IlayerDescription3 lyrDesc = GetLayerDesc(_server, layerId); //result = _server.QueryFeatureData2(_server.DefaultMapName, lyrDesc, filter, resultOptions); recordSet = result.Object as RecordSet; return recordSet; } catch (Exception ex) { throw ex; } finally { filter = null; resultOptions = null; tableDesc = null; result = null; } }
private bool BCGSCheck(string bcgsMapSheet, IPoint pPointToCheck,out string correctSheet) { bool retVal = false; correctSheet = string.Empty; try { ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pPointToCheck; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor pFeatureCursor = m_pFeatureLayerBCGS.FeatureClass.Search(pSpatialFilter,false); IFeature pFeature = pFeatureCursor.NextFeature(); if(pFeature != null) { for(int i = 0; i < m_BCGSFields.Length;i++) { int fieldInd = pFeature.Fields.FindField(m_BCGSFields[i]); if(fieldInd != -1) { string maptile = pFeature.get_Value(fieldInd).ToString(); // Issue 513 - reformat string without a leading zero if (bcgsMapSheet.Substring(0,1) == "0" && bcgsMapSheet.Substring(4,1) == ".") { bcgsMapSheet = bcgsMapSheet.Substring(1); } // Issue 513 - reformat 6 character string with period if (bcgsMapSheet.Length == 6) { bcgsMapSheet = bcgsMapSheet.Substring(0, 3) + "." + bcgsMapSheet.Substring(3, 3); } if (maptile.ToUpper() == bcgsMapSheet.ToUpper()) { retVal = true; break; } else { correctSheet = maptile; } } } //string maptile = pFeature.get_Value(pFeature.Fields.FindField("MAP_TILE")).ToString(); //string maptilename = pFeature.get_Value(pFeature.Fields.FindField("MAP_TILE_DISPLAY_NAME")).ToString(); } } catch(Exception ex) { Debug.WriteLine(ex.Message + "\n" + ex.StackTrace); util.Logger.Write(" Descrip : Checking to see if the user entered UTM point intersects the specifed map sheet polygon. " + "\n Message : " + ex.Message + "\n StackTrc : " + ex.StackTrace,util.Logger.LogLevel.Debug); } return retVal; }
public static string AddLaterals(IApplication app, List<AddLateralDetails> addLateralsDetails, IFeature inFeatures, bool logOperation, bool suppressDialog, bool store, bool ForceSourcePointConnection, IFeatureLayer pEditLayer) { string resetFlow = ""; bool useDefaultTemplate; List<IFeature> ComplFeat = new List<IFeature>(); IMap map = null; IEditor editor = null; IMouseCursor appCursor = null; IMxDocument mxdoc = null; IFeatureLayer pointFLayer = null; IFeatureLayer matchLineFLayer = null; IFeatureLayer targetLineFLayer = null; IEditLayers eLayers = null; ISelectionSet2 pointSelSet = null; IFeatureSelection pointFeatureSelection = null; IEditTemplate pLateralLineEditTemp = null; List<pointAlongSettings> pointAlongLayers = null; pointAlongSettings pointAlongLayer = null; ICursor pointCursor = null; IFeature pointFeature = null; //ProgressBar ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null; ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null; ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null; // Create a CancelTracker ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null; try { if (Control.ModifierKeys == Keys.Control) { useDefaultTemplate = false; } else { useDefaultTemplate = true; } bool boolSelectedEdges = false; if (Control.ModifierKeys == Keys.Shift) { boolSelectedEdges = true; } else { boolSelectedEdges = false; } //Get edit session bool LatCreated = false; editor = Globals.getEditor(app); if (editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), _caption); editor = null; return ""; } //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only) appCursor = new MouseCursorClass(); appCursor.SetCursor(2); mxdoc = (IMxDocument)app.Document; map = editor.Map; for (int k = 0; k < addLateralsDetails.Count; k++) { bool FCorLayerPoint = true; if (pEditLayer != null) { if (pEditLayer.Name == addLateralsDetails[k].Point_LayerName) { pointFLayer = pEditLayer; } else { continue; } } else { pointFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].Point_LayerName, ref FCorLayerPoint); } if (inFeatures != null) { if (pointFLayer == null) continue; if (pointFLayer.FeatureClass == null) continue; if (inFeatures.Class.CLSID.ToString() != pointFLayer.FeatureClass.CLSID.ToString()) continue; if (inFeatures.Class.ObjectClassID.ToString() != pointFLayer.FeatureClass.ObjectClassID.ToString()) continue; if (inFeatures.Class.AliasName.ToString() != pointFLayer.FeatureClass.AliasName.ToString()) continue; } //Report any problems before exiting if (pointFLayer == null) { continue; } bool FCorLayerMatch = true; bool FCorLayerTarget = true; matchLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].MainLine_LayerName, ref FCorLayerMatch); targetLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].LateralLine_LayerName, ref FCorLayerTarget); // IFeatureLayerDefinition2 pFeatLayerdef = matchLineFLayer as IFeatureLayerDefinition2; if (matchLineFLayer == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption); return ""; } if (matchLineFLayer.FeatureClass == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption); return ""; } if (matchLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_2") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption); return ""; } if (targetLineFLayer == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption); return ""; } if (targetLineFLayer.FeatureClass == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption); return ""; } if (targetLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_4") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption); return ""; } //Confirm the other layers are the correct shape type if (pointFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint || matchLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline) return ""; //Confirm that target layer is editable and is a line layer eLayers = (IEditLayers)editor; if (!(eLayers.IsEditable(targetLineFLayer)) || (targetLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)) return ""; //Confirm that the two line layers are different Feature classes if ((matchLineFLayer.FeatureClass.CLSID == targetLineFLayer.FeatureClass.CLSID) && (matchLineFLayer.FeatureClass.AliasName == targetLineFLayer.FeatureClass.AliasName)) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_1") , A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_2") ); return ""; } //Verify that some points are selected pointFeatureSelection = (IFeatureSelection)pointFLayer; if (pointFeatureSelection.SelectionSet.Count == 0) continue; pointSelSet = pointFeatureSelection.SelectionSet as ISelectionSet2; if (useDefaultTemplate) { //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate); pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate); } else { pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, ""); //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, ""); } if (addLateralsDetails[k].PointAlong != null) { if (addLateralsDetails[k].PointAlong.Length > 0) { pointAlongLayers = new List<pointAlongSettings>(); // IEditTemplate pPointAlongEditTemp; for (int j = 0; j < addLateralsDetails[k].PointAlong.Length; j++) { pointAlongLayer = new pointAlongSettings(); bool FCorLayerPointsAlong = true; pointAlongLayer.PointAlongLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].LayerName, ref FCorLayerPointsAlong); if (pointAlongLayer == null) { if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return ""; } else if (pointAlongLayer.PointAlongLayer == null) { if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return ""; } else if (pointAlongLayer.PointAlongLayer.FeatureClass == null) { if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_2") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return ""; } else if (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint) { MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_3") , A4LGSharedFunctions.Localizer.GetString("Warning") ); return ""; } pointAlongLayer.PolygonIntersectSide = addLateralsDetails[k].PointAlong[j].PolygonOffsetSide; if (pointAlongLayer.PolygonIntersectSide == null) { pointAlongLayer.PolygonIntersectSide = "TO"; } bool FCorLayerTemp = true; pointAlongLayer.PolygonIntersectLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName, ref FCorLayerTemp); pointAlongLayer.FoundAsLayer = FCorLayerTemp; if (pointAlongLayer == null) { if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return ""; } else if (pointAlongLayer.PolygonIntersectLayer != null) { if (pointAlongLayer.PolygonIntersectLayer.FeatureClass != null) { //Confirm that target layer is editable and is a line layer if (pointAlongLayer.PolygonIntersectLayer != null) { if (pointAlongLayer.PolygonIntersectLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon) { MessageBox.Show(addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_3")); return ""; } } } } //Confirm that target layer is editable and is a line layer if (pointAlongLayer.PointAlongLayer != null) { if (!(eLayers.IsEditable(pointAlongLayer.PointAlongLayer)) || (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)) { MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_4")); return ""; } if (useDefaultTemplate) { pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate); //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate); } else { pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, ""); //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, ""); } } //if (addLateralsDetails[k].PointAlong[j].Distance < 0) // pointAlongLayer.PointAlongDistance = 0; //else pointAlongLayer.PointAlongDistance = (double)addLateralsDetails[k].PointAlong[j].Distance; //if (addLateralsDetails[k].PointAlong[j].DistanceIsPercent != null) pointAlongLayer.DistanceIsPercent = (bool)addLateralsDetails[k].PointAlong[j].DistanceIsPercent; //else // pointAlongLayer.DistanceIsPercent =false; pointAlongLayers.Add(pointAlongLayer); //Verify subtype is valid for target point //if (targetPointFLayer != null) //{ // ISubtypes targetPointSubtypes = targetPointFLayer[j].FeatureClass as ISubtypes; // //string targetPointSubtypeName = targetPointSubtypes.get_SubtypeName(_targetPointSubtype); // if ((targetPointSubtypes == null) || (!targetPointSubtypes.HasSubtype))// || (String.IsNullOrEmpty(targetPointSubtypeName))) // addLateralsDetails[k].PointAlong[j].Subtype = -1; // else // { // try // { // string SubVal = targetPointSubtypes.get_SubtypeName(addLateralsDetails[k].PointAlong[j].Subtype); // // addLateralsDetails[k].PointAlong[j].Subtype = SubVal // //targetPointSubtype[k] = addLateralsDetails[k].PointAlong[j].Subtype; // } // catch // { // addLateralsDetails[k].PointAlong[j].Subtype = targetPointSubtypes.DefaultSubtypeCode; // } // } //} //else //{ // addLateralsDetails[k].PointAlong[j].Subtype = -1; //} //addLateralsDetails[k].PointAlong[j].Distance // addLateralsDetails[k].PointAlong[j].DistanceIsPercent // addLateralsDetails[k].PointAlong[j].FieldToPopulate // addLateralsDetails[k].PointAlong[j].ValueToPopulate } } } //**************************************** int total; total = pointSelSet.Count; int i = 0; // Create a CancelTracker trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass(); // Set the properties of the Step Progressor System.Int32 int32_hWnd = app.hWnd; if (suppressDialog == false) { progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass(); stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; stepProgressor.MaxRange = total; stepProgressor.StepValue = 1; stepProgressor.Message = _caption; // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = true; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "."; progressDialog.Title = _caption; progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe; progressDialog.ShowDialog(); } // Create an edit operation enabling undo/redo if (logOperation) { try { editor.StartOperation(); } catch { logOperation = false; } } IPoint fromPoint = null; IPoint selPt1 = null; IPoint selPt2 = null; ILine distanceLine = null; object Missing = null; IEnvelope env = null; IEnumIDs selIds = null; IFeature pointFeature2 = null; List<int> completedOIDArrayList = null; ITopologicalOperator topoOp = null; IPolygon poly = null; ISpatialFilter sFilter = null; IFeatureCursor lineCursor = null; INetworkFeature pNF = null; IFeature testPointFeature = null; int featOID1, featOID2, nearbyCount; try { // ISelectionSet2 sel = pointSelSet as ISelectionSet2; pointSelSet.Update(null, false, out pointCursor); completedOIDArrayList = new List<int>(); while ((pointFeature = (IFeature)pointCursor.NextRow()) != null) { try { //if (inFeatures != null) //{ // if (pointFeature.OID != inFeatures.OID) // { // continue; // } //} i += 1; if (suppressDialog == false) { //Update progress bar progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID; stepProgressor.Step(); } ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar; statusBar.set_Message(0, i.ToString()); //Check if the cancel button was pressed. If so, stop process bool boolean_Continue = trackCancel.Continue(); if (!boolean_Continue) { break; } if (!ComplFeat.Contains(pointFeature)) { //Get the "from" point for new line (start from selected point) fromPoint = pointFeature.ShapeCopy as IPoint; //Create new feature(s) env = new EnvelopeClass(); //Dual Laterals When Two Selected if (total == 2 && addLateralsDetails[k].Dual_When_Two_Selected) { if (suppressDialog == false) { //Update progress bar progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID; stepProgressor.Step(); } //Obtain both starting points selIds = pointSelSet.IDs; selIds.Reset(); featOID1 = selIds.Next(); featOID2 = selIds.Next(); pointFeature2 = pointFLayer.FeatureClass.GetFeature(featOID2); selPt1 = pointFeature.ShapeCopy as IPoint; selPt2 = pointFeature2.ShapeCopy as IPoint; //Measure distance distanceLine = new LineClass(); distanceLine.PutCoords(selPt1, selPt2); if (distanceLine.Length <= addLateralsDetails[k].Dual_Max_Distance_When_Two_Selected) { LatCreated = CreateDual(ref app, ref editor, pointFeature, pointFeature2, distanceLine, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature2); if (LatCreated) ComplFeat.Add(pointFeature); //CreateDualOld(pointFeature, pointFeature2, distanceLine, matchLineFLayer, // lineFeature, targetLineFLayer, targetPointFLayer, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); //_targetPointDistance, _targetPointDistanceIsPercent, _targetPointSubtype, _targetPointValue, _targetPointFieldName); break; } //Create two single laterals if the duals are not created else { LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature); LatCreated = CreateSingle(ref app, ref editor, pointFeature2, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature2); //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); //CreateSingleOld(pointFeature2, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); break; } } //Dual Laterals when Nearby else if ((total != 1) & addLateralsDetails[k].Dual_When_Nearby) { //Check that this feature has not already been completed if (completedOIDArrayList.Contains(pointFeature.OID)) continue; selPt1 = pointFeature.ShapeCopy as IPoint; nearbyCount = 0; pointFeature2 = null; //Determine if extactly one other point is within the specified max distance topoOp = selPt1 as ITopologicalOperator; poly = topoOp.Buffer(addLateralsDetails[k].Dual_Max_Distance_When_Nearby / 2) as IPolygon; sFilter = new SpatialFilterClass(); sFilter.Geometry = poly; sFilter.GeometryField = pointFLayer.FeatureClass.ShapeFieldName; sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; if (addLateralsDetails[k].SearchOnLayer) lineCursor = pointFLayer.Search(sFilter, false); else lineCursor = pointFLayer.FeatureClass.Search(sFilter, false); while ((testPointFeature = lineCursor.NextFeature()) != null) { if (testPointFeature.OID != pointFeature.OID) { //Check that this nearby feature has not already been completed if (!completedOIDArrayList.Contains(pointFeature.OID)) { pointFeature2 = testPointFeature; nearbyCount += 1; } } if (nearbyCount > 1) break; } if (nearbyCount == 1) { selPt2 = pointFeature2.ShapeCopy as IPoint; //Measure distance distanceLine = new LineClass(); distanceLine.PutCoords(selPt1, selPt2); LatCreated = CreateDual(ref app, ref editor, pointFeature, pointFeature2, distanceLine, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature2); if (LatCreated) ComplFeat.Add(pointFeature); //CreateDualOld(pointFeature, pointFeature2, distanceLine, matchLineFLayer, // lineFeature, targetLineFLayer, targetPointFLayer, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); //Add 2nd OID to completed list completedOIDArrayList.Add(pointFeature2.OID); } //Create a single lateral if 1 nearby not found else { LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature); //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); } } //Single Laterals else { LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges); if (LatCreated) ComplFeat.Add(pointFeature); //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer, // addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines, // addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint, // addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate, // addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue, // addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, // addLateralsDetails[k].PointAlong); } } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source); } finally { } // addLateralsDetails[k].InitDefaults(); if (addLateralsDetails[k].Reset_Flow != null) { resetFlow = addLateralsDetails[k].Reset_Flow; if (resetFlow.ToUpper() == "DIGITIZED") { Globals.GetCommand("A4WaterUtilities_EstablishFlowDigitized", app).Execute(); } else if (resetFlow.ToUpper() == "ROLE") { Globals.GetCommand("A4WaterUtilities_EstablishFlowAncillary", app).Execute(); } else if (resetFlow.ToUpper() == "Ancillary".ToUpper()) { Globals.GetCommand("A4WaterUtilities_EstablishFlowAncillary", app).Execute(); } else { } } } if (ForceSourcePointConnection) { foreach (IFeature sourcePnt in ComplFeat) { if (sourcePnt != null) { if (sourcePnt.Shape.IsEmpty != true) { if (sourcePnt is INetworkFeature) { pNF = (INetworkFeature)sourcePnt; try { pNF.Connect(); } catch { } } } } } } } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source); } finally { // Cleanup if (progressDialog != null) progressDialog.HideDialog(); if (lineCursor != null) Marshal.ReleaseComObject(lineCursor); pNF = null; fromPoint = null; selPt1 = null; selPt2 = null; distanceLine = null; Missing = null; env = null; selIds = null; pointFeature2 = null; completedOIDArrayList = null; topoOp = null; poly = null; sFilter = null; lineCursor = null; testPointFeature = null; } if (logOperation) { try { // Stop the edit operation editor.StopOperation(_caption); } catch { logOperation = false; } } //88 } return resetFlow; } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source); return ""; } finally { ComplFeat.Clear(); if (map != null) { (map as IActiveView).Refresh(); } if (progressDialog != null) progressDialog.HideDialog(); ComplFeat = null; map = null; editor = null; appCursor = null; mxdoc = null; pointFLayer = null; matchLineFLayer = null; targetLineFLayer = null; eLayers = null; pointSelSet = null; pointFeatureSelection = null; pLateralLineEditTemp = null; pointAlongLayers = null; pointAlongLayer = null; pointCursor = null; pointFeature = null; //ProgressBar progressDialogFactory = null; stepProgressor = null; progressDialog = null; // Create a CancelTracker trackCancel = null; } }
private static void DeleteOrphanJunctions(IFeatureClass orphanFC, ICurve curve, double tolerenceForDelete) { ITopologicalOperator topoOpLine = null; IPolygon poly2 = null; ISpatialFilter sFilter2 = null; IFeatureCursor fCursor2 = null; IFeature feature2 = null; ISimpleJunctionFeature juncfeat = null; IRow row1 = null; IRow row2 = null; try { if (orphanFC != null && curve != null) { //Buffer the line topoOpLine = curve as ITopologicalOperator; poly2 = topoOpLine.Buffer(tolerenceForDelete) as IPolygon; sFilter2 = new SpatialFilterClass(); sFilter2.Geometry = poly2; sFilter2.GeometryField = orphanFC.ShapeFieldName; sFilter2.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; fCursor2 = orphanFC.Search(sFilter2, false); while ((feature2 = fCursor2.NextFeature()) != null) { juncfeat = feature2 as ISimpleJunctionFeature; if (juncfeat != null) { if (juncfeat.EdgeFeatureCount == 0) feature2.Delete(); else if (juncfeat.EdgeFeatureCount == 2) { row1 = juncfeat.get_EdgeFeature(0) as IRow; row2 = juncfeat.get_EdgeFeature(1) as IRow; if (row1.OID == row2.OID) feature2.Delete(); } } } } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "DeleteOrphanJunctions: " + ex.Message); } finally { if (fCursor2 != null) Marshal.ReleaseComObject(fCursor2); topoOpLine = null; poly2 = null; sFilter2 = null; fCursor2 = null; feature2 = null; juncfeat = null; row1 = null; row2 = null; } }
void m_editEvents_OnDeleteFeature(IObject obj) { // check if the deleted feature participates in a relation // applies to point, lines, and polygons // if it does participate in a relation ask the user if it is ok to delete IFeatureClass currentObjectFeatureClass = obj.Class as IFeatureClass; if ((currentObjectFeatureClass == null) || (currentObjectFeatureClass.EXTCLSID == null)) return; // check if the current feature class being edited is acutally an OpenStreetMap feature class // all other feature class should not be touched by this extension UID osmEditorExtensionCLSID = currentObjectFeatureClass.EXTCLSID; if (osmEditorExtensionCLSID.Value.ToString().Equals("{65CA4847-8661-45eb-8E1E-B2985CA17C78}", StringComparison.InvariantCultureIgnoreCase) == false) { return; } // at this point we are only handling geometry types // relation types are using a separate UI IFeature deletedFeature = obj as IFeature; if (deletedFeature == null) return; // block changing features that are supporting features for multi-part geometries (relations) if (deletedFeature.Shape is IPolygon || deletedFeature.Shape is IPolyline) { int memberOFFieldIndex = deletedFeature.Fields.FindField("osmMemberOf"); int membersFieldIndex = deletedFeature.Fields.FindField("osmMembers"); int osmIDFieldIndex = deletedFeature.Fields.FindField("OSMID"); int osmID = 0; if (osmIDFieldIndex > -1) { object osmIDValue = deletedFeature.get_Value(osmIDFieldIndex); if (osmIDValue != DBNull.Value) { osmID = Convert.ToInt32(osmIDValue); } } if (membersFieldIndex > -1) { ESRI.ArcGIS.OSM.OSMClassExtension.member[] relationMembers = _osmUtility.retrieveMembers(deletedFeature, membersFieldIndex); if (relationMembers != null) { if (relationMembers.Length > 0) { string abortMessage = String.Format(resourceManager.GetString("OSMEditor_FeatureInspector_multipartdeleteparentconflictmessage"), osmID); MessageBox.Show(abortMessage, resourceManager.GetString("OSMEditor_FeatureInspector_relationconflictcaption"), MessageBoxButtons.OK, MessageBoxIcon.Stop); m_editor3.AbortOperation(); } } } if (memberOFFieldIndex > -1) { List<string> isMemberOfList = _osmUtility.retrieveIsMemberOf(deletedFeature, memberOFFieldIndex); Dictionary<string, string> dictofParentsAndTypes = _osmUtility.parseIsMemberOfList(isMemberOfList); StringBuilder typeAndIDString = new StringBuilder(); foreach (var item in dictofParentsAndTypes) { switch (item.Value) { case "rel": typeAndIDString.Append(resourceManager.GetString("OSMEditor_FeatureInspector_relationidtext") + item.Key + ","); break; case "ply": typeAndIDString.Append(resourceManager.GetString("OSMEditor_FeatureInspector_polygonidtext") + item.Key + ","); break; case "ln": typeAndIDString.Append(resourceManager.GetString("OSMEditor_FeatureInspector_polylineidtext") + item.Key + ","); break; case "pt": typeAndIDString.Append(resourceManager.GetString("OSMEditor_FeatureInspector_pointidtext") + item.Key + ","); break; default: break; } } if (typeAndIDString.Length > 0) { string parentsString = typeAndIDString.ToString(0, typeAndIDString.Length - 1); string abortMessage = String.Format(resourceManager.GetString("OSMEditor_FeatureInspector_relationsconflictmessage"), osmID, parentsString); MessageBox.Show(abortMessage, resourceManager.GetString("OSMEditor_FeatureInspector_relationconflictcaption"), MessageBoxButtons.OK, MessageBoxIcon.Stop); m_editor3.AbortOperation(); return; } } } else if (deletedFeature.Shape is IPoint) { // if we are dealing with points to be deleted then we'll determine the connectedness via a spatial query and then the attributes indicating that // the higher order feature is part of a relation IFeatureClass lineFeatureClass = ESRI.ArcGIS.OSM.OSMClassExtension.OpenStreetMapClassExtension.findMatchingFeatureClass(deletedFeature, esriGeometryType.esriGeometryPolyline); ISpatialFilter searchPointFilter = new SpatialFilterClass(); searchPointFilter.Geometry = deletedFeature.Shape; searchPointFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelTouches; TestRelationMembership(deletedFeature, lineFeatureClass, searchPointFilter); IFeatureClass polygonFeatureClass = ESRI.ArcGIS.OSM.OSMClassExtension.OpenStreetMapClassExtension.findMatchingFeatureClass(deletedFeature, esriGeometryType.esriGeometryPolygon); TestRelationMembership(deletedFeature, polygonFeatureClass, searchPointFilter); } string featureClassName = ((IDataset)obj.Class).Name; // find the correspoding relation table int baseIndex = featureClassName.IndexOf("_osm_"); int deleteOSMIDFieldIndex = obj.Fields.FindField("OSMID"); int deleteIsMemberOfFieldIndex = obj.Fields.FindField("osmMemberOf"); if (baseIndex > -1) { string relationTableName = featureClassName.Substring(0, baseIndex) + "_osm_relation"; IFeatureWorkspace featureWorkspace = m_editor3.EditWorkspace as IFeatureWorkspace; ITable relationTable = featureWorkspace.OpenTable(relationTableName); int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); List<string> memberOfList = _osmUtility.retrieveIsMemberOf(deletedFeature, deleteIsMemberOfFieldIndex); Dictionary<string, string> isMemberOfIdsAndTypes = _osmUtility.parseIsMemberOfList(memberOfList); if (memberOfList.Count > 0) { // the deleted feature is referenced by a relation // check with the user if it is ok to delete // if OK then we are dealing with the delete upon stop editing, if cancel undo the delete string relationsString = String.Empty; int relationCount = 0; foreach (var memberOfItem in isMemberOfIdsAndTypes) { if (memberOfItem.Value == "rel") { relationCount = relationCount + 1; relationsString = relationsString + memberOfItem.Key + ","; } } string errorMessage = String.Empty; if (relationCount > 1) { errorMessage = string.Format(resourceManager.GetString("OSMEditor_FeatureInspector_relationsconflictmessage"), deletedFeature.get_Value(deleteOSMIDFieldIndex), relationsString.Substring(0, relationsString.Length - 1)); } else { errorMessage = string.Format(resourceManager.GetString("OSMEditor_FeatureInspector_relationconflictmessage"), deletedFeature.get_Value(deleteOSMIDFieldIndex), relationsString.Substring(0, relationsString.Length - 1)); } if (MessageBox.Show(errorMessage, resourceManager.GetString("OSMEditor_FeatureInspector_relationconflictcaption"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel) { m_editor3.AbortOperation(); } } } }
private static void ProfileGetRelatedElevData(IApplication app, List<ProfileGraphDetails> ProfileGraph, IGeometricNetwork pGeometricNet, IEnumNetEID pResultEdges, IEnumNetEID pResultJunctions, int CurrentDetail, ref IFeatureLayer pFLManhole, ref IFeatureLayer pFLMain, ref IFeatureLayer pFLTap) { List<mainDetails> SewerColMains = null; List<manholeDetails> SewerColManholes = null; List<tapDetails> SewerColTap = null; IEIDHelper pEIDHelperEdges = null; IEnumEIDInfo pEnumEIDInfoEdges = null; IEIDHelper pEIDHelperJunctions = null; IEnumEIDInfo pEnumEIDInfoJunctions = null; IPolyline pPolyline = null; IPointCollection pPtColl = null; IEIDInfo pEIDInfo = null; IPoint pNewPt = null; ISegmentCollection pSegColl = null; IMSegmentation pMSegmentation = null; IMAware pMAware = null; IPointCollection pPtCollection = null; IEnumVertex pEnumVertex; IHitTest pHtTest = null; IPoint pHitPntOne = null; IPoint pHitPntTwo = null; IFeature pFeature = null; Hashtable pFeatureAdded = null; mainDetails mainDet = null; IEdgeFeature pEdge = null; IPoint pGeoOne = null; IPoint pGeoTwo = null; IField pFld = null; IJunctionFeature pJunc = null; tapDetails tapDet = null; manholeDetails manDet = null; IFeatureLayer pFl = null; ISpatialFilter pSpatFilt = null; IFeatureCursor pFC = null; try { SewerColMains = new List<mainDetails>(); SewerColManholes = new List<manholeDetails>(); SewerColTap = new List<tapDetails>(); pEIDHelperEdges = new EIDHelper(); pEIDHelperEdges.GeometricNetwork = pGeometricNet; pEIDHelperEdges.ReturnFeatures = true; pEIDHelperEdges.ReturnGeometries = true; pEIDHelperEdges.PartialComplexEdgeGeometry = true; pEnumEIDInfoEdges = pEIDHelperEdges.CreateEnumEIDInfo(pResultEdges); pEnumEIDInfoEdges.Reset(); //edges pEIDHelperJunctions = new EIDHelperClass(); pEIDHelperJunctions.GeometricNetwork = pGeometricNet; pEIDHelperJunctions.ReturnFeatures = true; pEIDHelperJunctions.ReturnGeometries = true; pEIDHelperJunctions.PartialComplexEdgeGeometry = true; pEnumEIDInfoJunctions = pEIDHelperJunctions.CreateEnumEIDInfo(pResultJunctions); pEnumEIDInfoJunctions.Reset();// junctions pPolyline = new PolylineClass(); pPolyline.SpatialReference = (pFLMain as IGeoDataset).SpatialReference; pPtColl = (IPointCollection)pPolyline; //QI for (int i = 0; i < pEnumEIDInfoJunctions.Count; i++) { pEIDInfo = pEnumEIDInfoJunctions.Next(); pNewPt = (IPoint)pEIDInfo.Geometry; pPtColl.AddPoint(pNewPt); } pSegColl = (ISegmentCollection)pPolyline; pPolyline.Densify(50, 0.01); pMAware = (IMAware)pPolyline;//'QI pMAware.MAware = true; pMSegmentation = (IMSegmentation)pPolyline; // get the M values, put the distance in m, 0 to Length pMSegmentation.SetMsAsDistance(false); pPtCollection = (IPointCollection)pPolyline; pEnumVertex = pPtCollection.EnumVertices; pEnumVertex.Reset(); pHtTest = pPolyline as IHitTest; pHitPntOne = new PointClass(); pHitPntTwo = new PointClass(); double pHitDistOne = -1; double pHitDistTwo = -1; int pHitPrtOne = -1; int pHitPrtTwo = -1; int pHitSegOne = -1; int pHitSegTwo = -1; bool pHitSideOne = false; bool pHitSideTwo = false; pFeatureAdded = new Hashtable(); pEnumEIDInfoEdges.Reset(); //edges int intUpStreamFld = pFLMain.FeatureClass.Fields.FindField(ProfileGraph[CurrentDetail].Line_UpStreamElevationField); int intDownStreamFld = pFLMain.FeatureClass.Fields.FindField(ProfileGraph[CurrentDetail].Line_DownStreamElevationField); if (intDownStreamFld < 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19c") + ProfileGraph[CurrentDetail].Line_DownStreamElevationField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19b")); } if (intUpStreamFld < 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19d") + ProfileGraph[CurrentDetail].Line_UpStreamElevationField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19b")); } for (int i = 0; i < pResultEdges.Count; i++) { pEIDInfo = pEnumEIDInfoEdges.Next(); pFeature = pEIDInfo.Feature; if (((IDataset)pFeature.Class).Name != ((IDataset)pFLMain.FeatureClass).Name) continue; if (pFeatureAdded.ContainsValue(pFeature.OID)) continue; mainDet = new mainDetails(); pEdge = (IEdgeFeature)pFeature; pGeoOne = (IPoint)pEdge.FromJunctionFeature.get_OriginalGeometryForJunctionElement(0); pGeoTwo = (IPoint)pEdge.ToJunctionFeature.get_OriginalGeometryForJunctionElement(0); pFeature = ((IFeatureClass)pFeature.Class).GetFeature(pFeature.OID); bool bHitOne = pHtTest.HitTest(pGeoOne, .1, esriGeometryHitPartType.esriGeometryPartVertex, pHitPntOne, ref pHitDistOne, ref pHitPrtOne, ref pHitSegOne, ref pHitSideOne); bool bHitTwo = pHtTest.HitTest(pGeoTwo, .1, esriGeometryHitPartType.esriGeometryPartVertex, pHitPntTwo, ref pHitDistTwo, ref pHitPrtTwo, ref pHitSegTwo, ref pHitSideTwo); if (bHitOne && bHitTwo) { if (pHitPntOne.M < pHitPntTwo.M) { mainDet.UpM = pHitPntOne.M; mainDet.DownM = pHitPntTwo.M; if (intUpStreamFld > 0) { if (pFeature.get_Value(intUpStreamFld).ToString() != "") { mainDet.UpElev = Convert.ToDouble(pFeature.get_Value(intUpStreamFld)); } else mainDet.UpElev = -9999; } else mainDet.UpElev = -9999; if (intDownStreamFld > 0) { if (pFeature.get_Value(intDownStreamFld).ToString() != "") { mainDet.DownElev = Convert.ToDouble(pFeature.get_Value(intDownStreamFld)); } else mainDet.DownElev = -9999; } else mainDet.DownElev = -9999; } else { mainDet.DownM = pHitPntOne.M; mainDet.UpM = pHitPntTwo.M; if (intUpStreamFld > 0) { if (pFeature.get_Value(intUpStreamFld) != null && pFeature.get_Value(intUpStreamFld).ToString() != "") { mainDet.DownElev = Convert.ToDouble(pFeature.get_Value(intUpStreamFld)); } else mainDet.DownElev = -9999; } else mainDet.DownElev = -9999; if (intDownStreamFld > 0) { if (pFeature.get_Value(intDownStreamFld) != null && pFeature.get_Value(intDownStreamFld).ToString() != "") { mainDet.UpElev = Convert.ToDouble(pFeature.get_Value(intDownStreamFld)); } else mainDet.UpElev = -9999; } else mainDet.UpElev = -9999; } string label = ""; for (int l = 0; l < ProfileGraph[CurrentDetail].Line_Labels.Length; l++) { if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_Labels[l]) > 0) { int fldIdx = pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_Labels[l]); pFld = pFeature.Fields.get_Field(fldIdx); if (pFeature.get_Value(fldIdx) != null) { if (label == "") { label = Globals.GetDomainDisplay(pFeature.get_Value(fldIdx), pFeature, pFld); } else { label = label + "\r\n" + Globals.GetDomainDisplay(pFeature.get_Value(fldIdx), pFeature, pFld); } } } } mainDet.Label = label; } if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_IDField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_IDField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_IDField)).ToString() != "") { mainDet.MainID = Convert.ToString(pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Line_IDField))); } else mainDet.MainID = "Unk"; } else mainDet.MainID = "Unk"; pFeatureAdded.Add(pFeature.OID, pFeature.OID); SewerColMains.Add(mainDet); } pFeatureAdded = new Hashtable(); pEnumEIDInfoJunctions.Reset(); for (int i = 0; i < pEnumEIDInfoJunctions.Count; i++) { pEIDInfo = pEnumEIDInfoJunctions.Next(); pFeature = pEIDInfo.Feature; if (pFLTap != null) { if (((IDataset)pFeature.Class).Name == ((IDataset)pFLTap.FeatureClass).Name) { pJunc = (IJunctionFeature)pFeature; pFeature = ((IFeatureClass)pFeature.Class).GetFeature(pFeature.OID); pHitPntOne = new PointClass(); bool bHit = pHtTest.HitTest(pFeature.Shape as IPoint, .1, esriGeometryHitPartType.esriGeometryPartVertex, pHitPntOne, ref pHitDistOne, ref pHitPrtOne, ref pHitSegOne, ref pHitSideOne); if (bHit) { tapDet = new tapDetails(); tapDet.M = pHitPntOne.M; if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_IDField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_IDField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_IDField)).ToString() != "") { tapDet.tapID = pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_IDField)).ToString(); } else tapDet.tapID = "Unk"; } else tapDet.tapID = "Unk"; string label = ""; for (int l = 0; l < ProfileGraph[CurrentDetail].PointAlong_Labels.Length; l++) { if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_Labels[l]) > 0) { int fldIdx = pFeature.Fields.FindField(ProfileGraph[CurrentDetail].PointAlong_Labels[l]); pFld = pFeature.Fields.get_Field(fldIdx); if (pFeature.get_Value(fldIdx) != null) { if (label == "") { label = Globals.GetDomainDisplay(pFeature.get_Value(fldIdx), pFeature, pFld); } else { label = label + "\r\n" + Globals.GetDomainDisplay(pFeature.get_Value(fldIdx), pFeature, pFld); } } } } tapDet.tapLabel = label; SewerColTap.Add(tapDet); } } } if (((IDataset)pFeature.Class).Name == ((IDataset)pFLManhole.FeatureClass).Name) { if (pFeatureAdded.ContainsValue(pFeature.OID)) continue; pJunc = (IJunctionFeature)pFeature; pFeature = ((IFeatureClass)pFeature.Class).GetFeature(pFeature.OID); pHitPntOne = new PointClass(); bool bHit = pHtTest.HitTest(pFeature.Shape as IPoint, .1, esriGeometryHitPartType.esriGeometryPartVertex, pHitPntOne, ref pHitDistOne, ref pHitPrtOne, ref pHitSegOne, ref pHitSideOne); if (bHit) { manDet = new manholeDetails(); manDet.M = pHitPntOne.M; if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_TopElevationField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_TopElevationField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_TopElevationField)).ToString() != "") { manDet.Top = (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_TopElevationField)); } else manDet.Top = -9999; } else manDet.Top = -9999; if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationField)).ToString() != "") { manDet.Bottom = (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationField)); if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationTypeField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationTypeField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationTypeField)).ToString() != "") { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationTypeField)).ToString().ToUpper() == "INVERT") manDet.Bottom = manDet.Top - (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_BottomElevationTypeField)); } } } else manDet.Bottom = -9999; } else manDet.Bottom = -9999; //if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertElevationField) > 0) //{ // if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertElevationField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertElevationField)).ToString() != "") // { // manDet.InvertElev = (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertElevationField)); // } // else // manDet.InvertElev = -9999; //} //else // manDet.InvertElev = -9999; //if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertField) > 0) //{ // if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertField)).ToString() != "") // { // manDet.Invert = (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_InvertField)); // } // else // manDet.Invert = -9999; //} //else // manDet.Invert = -9999; //if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_RimElevationField) > 0) //{ // if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_RimElevationField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_RimElevationField)).ToString() != "") // { // manDet.Rim = (double)pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_RimElevationField)); // } // else // manDet.Rim = -9999; //} //else // manDet.Rim = -9999; if (pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_IDField) > 0) { if (pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_IDField)) != null && pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_IDField)).ToString() != "") { manDet.ManholeID = pFeature.get_Value(pFeature.Fields.FindField(ProfileGraph[CurrentDetail].Point_IDField)).ToString(); } else manDet.ManholeID = "UNK"; } else manDet.ManholeID = "UNK"; pFeatureAdded.Add(pFeature.OID, pFeature.OID); SewerColManholes.Add(manDet); } } } if (ProfileGraph[CurrentDetail].Lines_Along != null) { if (ProfileGraph[CurrentDetail].Lines_Along.Length > 0) { pSpatFilt = new SpatialFilterClass(); pSpatFilt.Geometry = pPolyline; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; for (int i = 0; i < ProfileGraph[CurrentDetail].Lines_Along.Length; i++) { bool FCorLayerTemp = true; pFl = (IFeatureLayer)Globals.FindLayer(app, ProfileGraph[CurrentDetail].Lines_Along[i].Layer_Name, ref FCorLayerTemp); if (pFl != null) { intUpStreamFld = pFl.FeatureClass.Fields.FindField(ProfileGraph[CurrentDetail].Lines_Along[i].Line_UpStreamElevationField); intDownStreamFld = pFl.FeatureClass.Fields.FindField(ProfileGraph[CurrentDetail].Lines_Along[i].Line_DownStreamElevationField); int intIdFld = pFl.FeatureClass.Fields.FindField(ProfileGraph[CurrentDetail].Lines_Along[i].Line_IDField); if (intIdFld < 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19f") + ProfileGraph[CurrentDetail].Lines_Along[i].Line_IDField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19e") + ProfileGraph[CurrentDetail].Lines_Along[i].Layer_Name); } if (intDownStreamFld < 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19c") + ProfileGraph[CurrentDetail].Lines_Along[i].Line_DownStreamElevationField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19e") + ProfileGraph[CurrentDetail].Lines_Along[i].Layer_Name); } if (intUpStreamFld < 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19d") + ProfileGraph[CurrentDetail].Lines_Along[i].Line_UpStreamElevationField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19e") + ProfileGraph[CurrentDetail].Lines_Along[i].Layer_Name); } pSpatFilt.GeometryField = pFl.FeatureClass.ShapeFieldName; pFC = pFl.Search(pSpatFilt, true); } } } } ProfileCreateGraph(app, ProfileGraph, pPolyline, SewerColMains, SewerColManholes, SewerColTap, CurrentDetail); } catch (Exception Ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "ProfileGetRelatedSewerElevData " + Ex.Message); } finally { SewerColMains = null; SewerColManholes = null; SewerColTap = null; pEIDHelperEdges = null; pEnumEIDInfoEdges = null; pEIDHelperJunctions = null; if (pEnumEIDInfoJunctions != null) Marshal.ReleaseComObject(pEnumEIDInfoJunctions); pEnumEIDInfoJunctions = null; pPolyline = null; pPtColl = null; pEIDInfo = null; pNewPt = null; pSegColl = null; pMSegmentation = null; pMAware = null; pPtCollection = null; pEnumVertex = null; pHtTest = null; pHitPntOne = null; pHitPntTwo = null; pFeature = null; pFeatureAdded = null; mainDet = null; pEdge = null; pGeoOne = null; pGeoTwo = null; pFld = null; pJunc = null; tapDet = null; manDet = null; pFl = null; pSpatFilt = null; if (pFC != null) Marshal.ReleaseComObject(pFC); pFC = null; } }