async public Task <bool> OnEvent(object MapEvent) { if (_module == null || _module.SelectedNetworkFeatureClass == null || !(MapEvent is MapEventClick)) { return(false); } MapEventClick ev = (MapEventClick)MapEvent; Point p = new Point(ev.x, ev.y); double tol = 5 * ((IDisplay)ev.Map).mapScale / (96 / 0.0254); // [m] Envelope env = new Envelope(ev.x - tol, ev.y - tol, ev.x + tol, ev.y + tol); SpatialFilter filter = new SpatialFilter(); filter.Geometry = env; filter.FeatureSpatialReference = ((IDisplay)ev.Map).SpatialReference; filter.FilterSpatialReference = ((IDisplay)ev.Map).SpatialReference; filter.AddField("FDB_SHAPE"); filter.AddField("FDB_OID"); double dist = double.MaxValue; int n1 = -1; IPoint p1 = null; IFeatureCursor cursor = await _module.SelectedNetworkFeatureClass.GetNodeFeatures(filter); IFeature feature; while ((feature = await cursor.NextFeature()) != null) { double d = p.Distance(feature.Shape as IPoint); if (d < dist) { dist = d; n1 = feature.OID; p1 = feature.Shape as IPoint; } } _module.RemoveNetworkStartGraphicElement((IDisplay)ev.Map); if (n1 != -1) { _module.StartNodeIndex = n1; } if (p1 != null) { ((IDisplay)ev.Map).GraphicsContainer.Elements.Add(new GraphicStartPoint(p1)); _module.StartPoint = p1; } ((MapEvent)MapEvent).drawPhase = DrawPhase.Graphics; ((MapEvent)MapEvent).refreshMap = true; return(true); }
async public Task <List <int> > QueryAllowedNodeIds(double minBufferDist, double maxBufferDist) { if (_nfc == null || _startPoint == null || _endPoint == null) { return(null); } Path path = new Path(); path.AddPoint(_startPoint); path.AddPoint(_endPoint); Polyline pLine = new Polyline(); pLine.AddPath(path); double bufferDist = Math.Min(Math.Max(path.Length * 0.1, minBufferDist), maxBufferDist); IPolygon polygon = pLine.Buffer(bufferDist); if (polygon == null) { return(null); } SpatialFilter filter = new SpatialFilter(); filter.Geometry = polygon; filter.AddField("FDB_NID"); IFeatureCursor cursor = await _nfc.GetNodeFeatures(filter); if (cursor == null) { return(null); } List <int> allowedNodeIds = new List <int>(); IFeature feature; while ((feature = await cursor.NextFeature()) != null) { allowedNodeIds.Add(feature.OID); } return(allowedNodeIds); }
internal void LoadGeometry(IMap map, ISnapSchema schema, IEnvelope envelope) { _snapGeometries.Clear(); IGUIApplication guiApp = (_doc != null) ? _doc.Application as IGUIApplication : null; if (map == null || schema == null || envelope == null || map.Display == null || map.Display.mapScale >= schema.MaxScale) { return; } foreach (ISnapLayer sLayer in schema) { if (sLayer == null || sLayer.FeatureLayer == null || sLayer.FeatureLayer.FeatureClass == null || _doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null) { continue; } if (sLayer.FeatureLayer.MinimumScale >= 1 && sLayer.FeatureLayer.MinimumScale > _doc.FocusMap.Display.mapScale) { continue; } if (sLayer.FeatureLayer.MaximumScale >= 1 && sLayer.FeatureLayer.MaximumScale < _doc.FocusMap.Display.mapScale) { continue; } SpatialFilter filter = new SpatialFilter(); filter.FeatureSpatialReference = map.Display.SpatialReference; filter.FilterSpatialReference = map.Display.SpatialReference; filter.Geometry = envelope; filter.SpatialRelation = spatialRelation.SpatialRelationIntersects; filter.AddField(sLayer.FeatureLayer.FeatureClass.ShapeFieldName); if (guiApp != null) { guiApp.StatusBar.Text = "Query Snaplayer: " + sLayer.FeatureLayer.Title; guiApp.StatusBar.Refresh(); } List <IGeometry> geometries = new List <IGeometry>(); using (IFeatureCursor cursor = sLayer.FeatureLayer.FeatureClass.GetFeatures(filter)) { IFeature feature; while ((feature = cursor.NextFeature) != null) { if (feature.Shape != null) { geometries.Add(feature.Shape); } } } _snapGeometries.Add(sLayer, geometries); } if (guiApp != null) { guiApp.StatusBar.Text = null; guiApp.StatusBar.Refresh(); } }
public bool CheckIn(IWorkspace store, string versionName, string dbpath, string gridFeatureClass, string gridCodeFieldName) { //创建子版本 IVersion ver_store = store as IVersion; IVersion new_version = ver_store.CreateVersion(versionName); new_version.Access = esriVersionAccess.esriVersionAccessPublic; IFeatureWorkspace target_ws = new_version as IFeatureWorkspace; IWorkspaceEdit2 wse = target_ws as IWorkspaceEdit2; //删除TaskGridLog ITable grid_tbl = target_ws.OpenTable("TaskGridLog"); IQueryFilter grid_filter = new QueryFilterClass(); grid_filter.WhereClause = "TaskName = '" + versionName + "'"; wse.StartEditing(false); grid_tbl.DeleteSearchedRows(grid_filter); wse.StopEditing(true); //删除CheckItem IQueryFilter checkItems_filter = new QueryFilterClass(); checkItems_filter.WhereClause = "versionName = '" + versionName + "'"; ITable checkItems = target_ws.OpenTable("CheckItemPtn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemLn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemPoly"); checkItems.DeleteSearchedRows(checkItems_filter); IFeatureClass grid_fc = target_ws.OpenFeatureClass(gridFeatureClass); int gridCodeFld_idx = grid_fc.FindField(gridCodeFieldName); Dictionary <string, int[]> updateGridCodes = new Dictionary <string, int[]>(); ISpatialFilter gridFilter = new SpatialFilter(); gridFilter.GeometryField = grid_fc.ShapeFieldName; gridFilter.AddField(gridCodeFieldName); gridFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //总更新网格面积 double totalUpdateGridsArea = 0; double totalUpdateGrids = 0; double totalUpdateItems = 0; double totalAddItems = 0; double totalDeleteItems = 0; wse.StartEditing(true); try { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspace source = workspaceFactory.OpenFromFile(dbpath, 0); IDataset ds = source as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace source_ws = source as IFeatureWorkspace; foreach (string fcname in fcNames) { IWorkspace2 target_ws2 = target_ws as IWorkspace2; if (!target_ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, fcname)) { continue; } IFeatureClass source_fc = source_ws.OpenFeatureClass(fcname); IFeatureClass target_fc = target_ws.OpenFeatureClass(fcname); int syncid_idx = source_fc.FindField("SyncID"); Dictionary <int, int> field_idxs = new Dictionary <int, int>(); for (int i = 0; i < source_fc.Fields.FieldCount; i++) { IField source_field = source_fc.Fields.get_Field(i); if (source_field.Name == "SyncID") { continue; } if (source_field.Name == "SyncTimeStamp") { continue; } if (source_field.Name == "SyncStatus") { continue; } if (source_field.Name == "SyncEditable") { continue; } if (source_field.Name == source_fc.OIDFieldName) { continue; } int j = target_fc.FindField(source_field.Name); if (j != -1) { field_idxs.Add(i, j); } } string checkItemName; switch (target_fc.ShapeType) { case esriGeometryType.esriGeometryPoint: checkItemName = "CheckItemPtn"; break; case esriGeometryType.esriGeometryPolyline: checkItemName = "CheckItemLn"; break; case esriGeometryType.esriGeometryPolygon: checkItemName = "CheckItemPoly"; break; default: checkItemName = "CheckItemPoly"; break; } IFeatureClass checkItem_fc = target_ws.OpenFeatureClass(checkItemName); int checkItem_f1 = checkItem_fc.FindField("FeatureClassName"); int checkItem_f2 = checkItem_fc.FindField("FeatureID"); int checkItem_f3 = checkItem_fc.FindField("VersionName"); int checkItem_f4 = checkItem_fc.FindField(checkItem_fc.ShapeFieldName); IGeoDataset checkItem_gds = checkItem_fc as IGeoDataset; //同步更新 wse.StartEditOperation(); IQueryFilter filter = new QueryFilterClass(); filter.WhereClause = "[SyncStatus]='U'"; IFeatureCursor source_cur = source_fc.Search(filter, false); IFeature source_fea = source_cur.NextFeature(); while (source_fea != null) { int id = Convert.ToInt32(source_fea.get_Value(syncid_idx)); IFeature target_fea = target_fc.GetFeature(id); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, id); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][0] += 1; } else { int[] c = new int[2] { 1, 0 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalUpdateItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); //同步删除 wse.StartEditOperation(); List <int> lst_del = new List <int>(); TaskManager tm = TaskManager.GetInstance(); ISpatialFilter target_filter = new SpatialFilterClass(); target_filter.Geometry = tm.GetTaskLocation(versionName); target_filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; target_filter.SubFields = ""; using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor target_fea_cur = target_fc.Search(target_filter, false); comReleaser.ManageLifetime(target_fea_cur); IFeature target_fea_del = target_fea_cur.NextFeature(); while (target_fea_del != null) { filter = new QueryFilterClass(); filter.WhereClause = "[SyncID]=" + target_fea_del.OID.ToString(); using (ComReleaser comReleaser2 = new ComReleaser()) { IFeatureCursor source_cur_del = source_fc.Search(filter, true); comReleaser2.ManageLifetime(source_cur_del); source_fea = source_cur_del.NextFeature(); if (source_fea == null) { lst_del.Add(target_fea_del.OID); totalDeleteItems += 1; } } target_fea_del = target_fea_cur.NextFeature(); } } foreach (int id in lst_del) { IFeature target_fea_del = target_fc.GetFeature(id); target_fea_del.Delete(); } wse.StopEditOperation(); //同步新建 wse.StartEditOperation(); filter = new QueryFilterClass(); filter.WhereClause = "[SyncID] is null"; source_cur = source_fc.Search(filter, false); source_fea = source_cur.NextFeature(); while (source_fea != null) { IFeature target_fea = target_fc.CreateFeature(); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, target_fea.OID); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][1] += 1; } else { int[] c = new int[2] { 0, 1 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalAddItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); } //添加TaskGridLog wse.StartEditOperation(); using (ComReleaser comR = new ComReleaser()) { ICursor tgl_cur = grid_tbl.Insert(true); IRowBuffer tgl_rowBF = grid_tbl.CreateRowBuffer(); comR.ManageLifetime(tgl_rowBF); comR.ManageLifetime(tgl_cur); foreach (string gridcode in updateGridCodes.Keys) { tgl_rowBF.set_Value(1, versionName); tgl_rowBF.set_Value(2, gridcode); tgl_rowBF.set_Value(4, updateGridCodes[gridcode][1]); tgl_rowBF.set_Value(5, updateGridCodes[gridcode][0]); tgl_cur.InsertRow(tgl_rowBF); } tgl_cur.Flush(); } wse.StopEditOperation(); //设置Task的内容更新信息 totalUpdateGrids = updateGridCodes.Keys.Count; wse.StartEditOperation(); IFeatureClass task_fc = target_ws.OpenFeatureClass("TaskLog"); IQueryFilter task_filter = new QueryFilterClass(); task_filter.WhereClause = "TaskName = '" + versionName + "'"; IFeatureCursor cur = task_fc.Update(task_filter, true); IFeature task_fea = cur.NextFeature(); if (task_fea != null) { task_fea.set_Value(task_fc.FindField("totalAddItems"), totalAddItems); task_fea.set_Value(task_fc.FindField("totalUpdateItems"), totalUpdateItems); task_fea.set_Value(task_fc.FindField("totalDeleteItems"), totalDeleteItems); task_fea.set_Value(task_fc.FindField("totalGrids"), totalUpdateGrids); task_fea.set_Value(task_fc.FindField("totalGridsArea"), totalUpdateGridsArea); task_fea.Store(); } wse.StopEditOperation(); } catch (Exception ex) { return(false); } finally { wse.StopEditing(true); } return(true); }
private void Run() { if (_targetDataset == null || _fdb == null || _sourceDataset == null) { return; } //if (_targetDataset[_name] != null) //{ // MessageBox.Show("Featureclass '" + _name + "' already exists!"); // return; //} bool succeeded = false; try { Envelope bounds = new Envelope(_spatialIndexDef.SpatialIndexBounds); Envelope iBounds = new Envelope(bounds.minx - _tileSizeX, bounds.miny - _tileSizeY, bounds.maxx + _tileSizeX, bounds.maxy + _tileSizeY); _cacheDirectory += @"\" + _name; if (!String.IsNullOrEmpty(_cacheDirectory)) { DirectoryInfo di = new DirectoryInfo(_cacheDirectory); if (!di.Exists) { di.Create(); } StringBuilder sb = new StringBuilder(); sb.Append("<TileCacheDefinition>\r\n"); sb.Append(" <General levels='" + _levels + "' origin='lowerleft' />\r\n"); sb.Append(" <Envelope minx='" + bounds.minx.ToString(_nhi) + "' miny='" + bounds.miny.ToString(_nhi) + "' maxx='" + bounds.maxx.ToString(_nhi) + "' maxy='" + bounds.maxy.ToString(_nhi) + "' />\r\n"); sb.Append(" <TileSize x='" + _tileSizeX.ToString(_nhi) + "' y='" + _tileSizeY.ToString(_nhi) + "' />\r\n"); sb.Append(" <TileResolution x='" + _resX.ToString(_nhi) + "' y='" + _resY.ToString(_nhi) + "' />\r\n"); sb.Append("</TileCacheDefinition>"); StreamWriter sw = new StreamWriter(di.FullName + @"\tilecache.xml"); sw.WriteLine(sb.ToString()); sw.Close(); } ProgressReport report = new ProgressReport(); int datasetId = _fdb.DatasetID(_targetDataset.DatasetName); if (datasetId == -1) { return; } IClass cls = null; try { cls = _sourceDataset.Elements[0].Class; } catch { cls = null; } IMultiGridIdentify gridClass = cls as IMultiGridIdentify; if (_gridType == TileGridType.binary_float && gridClass == null) { return; } IFeatureClass sourceFc = cls as IFeatureClass; Map map = null; if (_gridType == TileGridType.image_jpg || _gridType == TileGridType.image_png) { map = new Map(); ILayer layer = LayerFactory.Create(cls); map.AddLayer(layer); //map.iWidth = (int)(_tileSizeX / _resX); //map.iHeight = (int)(_tileSizeY / _resY); } #region Create Featureclass IFeatureClass fc = null; IDatasetElement element = _targetDataset[_name]; if (element != null && element.Class is IFeatureClass) { fc = (IFeatureClass)element.Class; if (fc.GeometryType == geometryType.Polygon && fc.FindField("GRID_LEVEL") != null && fc.FindField("GRID_ROW") != null && fc.FindField("GRID_COLUMN") != null && fc.FindField("FILE") != null) { if (MessageBox.Show("TileGridClass already exists. Do you wan't to append to this Grid?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes) { return; } } else { _fdb.DeleteFeatureClass(_name); fc = null; } } if (fc == null) { Fields fields = new Fields(); fields.Add(new Field("GRID_LEVEL", FieldType.integer)); fields.Add(new Field("GRID_ROW", FieldType.integer)); fields.Add(new Field("GRID_COLUMN", FieldType.integer)); fields.Add(new Field("FILE", FieldType.String, 512)); _fdb.CreateFeatureClass(_targetDataset.DatasetName, _name, new GeometryDef(geometryType.Polygon), fields); element = _targetDataset[_name]; if (element == null || !(element.Class is IFeatureClass)) { return; } _fdb.SetSpatialIndexBounds(_name, "BinaryTree2", iBounds, _spatialIndexDef.SplitRatio, _spatialIndexDef.MaxPerNode, _spatialIndexDef.Levels); fc = (IFeatureClass)element.Class; } #endregion #region Create Tiles #region Report double tx = _tileSizeX, ty = _tileSizeY; if (ReportProgress != null) { report.featureMax = 0; for (int i = 0; i < _levels; i++) { if (_createLevels.Contains(i)) { for (double y = bounds.miny; y < bounds.maxy; y += ty) { for (double x = bounds.minx; x < bounds.maxx; x += tx) { report.featureMax++; } } } if (_levelType == TileLevelType.ConstantImagesize) { tx *= 2; ty *= 2; } } report.Message = "Create Tiles"; report.featurePos = 0; ReportProgress(report); } int reportInterval = (_createTiles ? 10 : 1000); #endregion List <IFeature> features = new List <IFeature>(); for (int level = 0; level < _levels; level++) { if (map != null) { map.iWidth = (int)(_tileSizeX / _resX); map.iHeight = (int)(_tileSizeY / _resY); } if (_createLevels.Contains(level)) { int row = 0; for (double y = bounds.miny; y < bounds.maxy; y += _tileSizeY) { DirectoryInfo di = new DirectoryInfo(_cacheDirectory + @"\" + level + @"\" + row); if (!di.Exists) { di.Create(); } int column = 0; for (double x = bounds.minx; x < bounds.maxx; x += _tileSizeX) { #region Polygon Polygon polygon = new Polygon(); Ring ring = new Ring(); ring.AddPoint(new Point(x, y)); ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), y)); ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), Math.Min(y + _tileSizeY, bounds.maxy))); ring.AddPoint(new Point(x, Math.Min(y + _tileSizeY, bounds.maxy))); ring.Close(); polygon.AddRing(ring); #endregion if (sourceFc != null) { SpatialFilter filter = new SpatialFilter(); filter.AddField(sourceFc.IDFieldName); filter.Geometry = polygon; filter.FilterSpatialReference = fc.SpatialReference; using (IFeatureCursor cursor = sourceFc.GetFeatures(filter)) { if (cursor.NextFeature == null) { column++; report.featurePos++; if (ReportProgress != null && report.featurePos % reportInterval == 0) { ReportProgress(report); } continue; } } } string relFilename = level + "/" + row + "/" + column + ".bin"; if (_createTiles) { string filename = di.FullName + @"\" + column; if (_gridType == TileGridType.binary_float) { float[] vals = gridClass.MultiGridQuery( null, new IPoint[] { ring[0], ring[1], ring[3] }, _resX, _resY, fc.SpatialReference, null); if (!HasFloatArrayData(vals)) { column++; report.featurePos++; if (ReportProgress != null && report.featurePos % reportInterval == 0) { ReportProgress(report); } continue; } StoreFloatArray(filename + ".bin", x, y, _resX, _resY, vals); } else if (map != null) { map.ZoomTo(new Envelope(x, y, x + _tileSizeX, y + _tileSizeY)); map.RefreshMap(DrawPhase.All, _cancelTracker); if (_gridType == TileGridType.image_png) { map.Bitmap.Save(filename + ".png", System.Drawing.Imaging.ImageFormat.Png); } else if (_gridType == TileGridType.image_jpg) { map.Bitmap.Save(filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } } } Feature feature = new Feature(); feature.Shape = polygon; feature.Fields.Add(new FieldValue("GRID_LEVEL", level)); feature.Fields.Add(new FieldValue("GRID_ROW", row)); feature.Fields.Add(new FieldValue("GRID_COLUMN", column)); feature.Fields.Add(new FieldValue("FILE", relFilename)); features.Add(feature); column++; report.featurePos++; if (features.Count >= reportInterval) { if (ReportProgress != null) { ReportProgress(report); } if (!_fdb.Insert(fc, features)) { MessageBox.Show(_fdb.lastErrorMsg, "DB Insert Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } features.Clear(); if (!_cancelTracker.Continue) { succeeded = true; return; } } } row++; } } if (_levelType == TileLevelType.ConstantImagesize) { _tileSizeX *= 2; _tileSizeY *= 2; } _resX *= 2; _resY *= 2; } if (features.Count > 0) { if (ReportProgress != null) { ReportProgress(report); } _fdb.Insert(fc, features); } _fdb.CalculateExtent(fc); #endregion succeeded = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (!succeeded) { _fdb.DeleteFeatureClass(_name); } } }
async public Task <IGraphEdge> GetGraphEdge(IPoint point, double tolerance) { if (point == null) { return(null); } SpatialFilter filter = new SpatialFilter(); filter.Geometry = new Envelope(point.X - tolerance, point.Y - tolerance, point.X + tolerance, point.Y + tolerance); filter.AddField("FDB_SHAPE"); filter.AddField("FDB_OID"); using (IFeatureCursor cursor = await GetEdgeFeatures(filter)) { IFeature feature, selected = null; double selectedDist = double.MaxValue; int selectedFcId = int.MinValue; IPoint snappedPoint = null; while ((feature = await cursor.NextFeature()) != null) { if (!(feature.Shape is IPolyline) || feature.FindField("NETWORK#FCID") == null) { continue; } int fcid = (int)feature["NETWORK#FCID"]; double dist, stat; IPoint spoint = gView.Framework.SpatialAlgorithms.Algorithm.Point2PolylineDistance((IPolyline)feature.Shape, point, out dist, out stat); if (spoint == null) { continue; } if (selected == null || dist <= selectedDist) { if (fcid != -1) { #region Do complex Edge exists IFeatureClass complexEdgeFc = _edgeFcs[-1]; if (complexEdgeFc != null) { QueryFilter complexEdgeFilter = new QueryFilter(); complexEdgeFilter.WhereClause = "FCID=" + fcid + " AND OID=" + feature.OID; complexEdgeFilter.AddField("FDB_OID"); using (IFeatureCursor complexEdgeCursor = await complexEdgeFc.GetFeatures(complexEdgeFilter)) { if (await complexEdgeCursor.NextFeature() != null) { continue; } } } #endregion } selected = feature; selectedDist = dist; selectedFcId = fcid; snappedPoint = spoint; } } if (selected == null) { return(null); } int eid = -1; if (selectedFcId == -1) { #region Complex Edge object eidObj = await _fdb._conn.QuerySingleField("SELECT EID FROM " + _fdb.TableName("FC_" + _name + "_ComplexEdges") + " WHERE FDB_OID=" + selected.OID, "EID"); if (eidObj != null) { eid = (int)eidObj; } #endregion } else { object eidObj = await _fdb._conn.QuerySingleField("SELECT EID FROM " + _fdb.TableName(_name + "_EdgeIndex") + " WHERE FCID=" + selectedFcId + " AND OID=" + selected.OID, "EID"); if (eidObj != null) { eid = (int)eidObj; } } if (eid != -1) { point.X = snappedPoint.X; point.Y = snappedPoint.Y; IGraphTableAdapter gt = this.GraphTableAdapter(); return(gt.QueryEdge(eid)); } return(null); } }
async public Task <bool> OnInsert(IFeatureClass fc, IFeature feature) { if (fc == null || feature == null) { return(false); } if (feature.Shape == null) { return(true); } SpatialFilter filter = new SpatialFilter(); filter.Geometry = feature.Shape; filter.SpatialRelation = spatialRelation.SpatialRelationIntersects; filter.FilterSpatialReference = fc.SpatialReference; filter.AddField(this.name); using (IFeatureCursor cursor = await fc.Search(filter) as IFeatureCursor) { List <int> levels = new List <int>(); IFeature f; while (((f = await cursor.NextFeature()) != null)) { if (f[this.name] == null || f[this.name] == DBNull.Value) { continue; } int level = Convert.ToInt32(f[this.name]); int index = levels.BinarySearch(level); if (index >= 0) { continue; } levels.Insert(~index, level); } int Level = 0; if (levels.Count != 0) { int min = levels[0]; int max = levels[levels.Count - 1]; if (min == 0) { for (int i = 0; i < levels.Count; i++) { if (levels.BinarySearch(i) < 0) { Level = i; break; } } if (Level == 0) { Level = max + 1; } } } if (feature[this.name] != null) { feature[this.name] = Level; } else { feature.Fields.Add(new FieldValue(this.name, Level)); } } return(true); }
private void PerformQueryTilesRequest(IServiceRequestContext context, XmlNode rType) { if (context == null || context.ServiceRequest == null) { _mapServer.Log("PerformQueryTilesRequest", loggingMethod.error, "no context or servicerequest"); return; } ServiceRequest serviceRequest = context.ServiceRequest; _mapServer.Log("Service:" + serviceRequest.Service, loggingMethod.request, "TileService Request: QueryTiles"); try { int level = 0; if (rType.Attributes["level"] != null) { level = int.Parse(rType.Attributes["level"].Value); } IServiceMap map = _mapServer[context]; if (map == null) { serviceRequest.Response = CreateException("Service not found"); return; } #region QueryGeometry IGeometry queryGeometry = null; #region Envelope XmlNode envelopeNode = rType.SelectSingleNode("Envelope[@minx and @miny and @maxx and @maxy]"); if (envelopeNode != null) { Envelope queryEnvelope = new Envelope( double.Parse(envelopeNode.Attributes["minx"].Value, _nhi), double.Parse(envelopeNode.Attributes["miny"].Value, _nhi), double.Parse(envelopeNode.Attributes["maxx"].Value, _nhi), double.Parse(envelopeNode.Attributes["maxy"].Value, _nhi)); queryGeometry = queryEnvelope; } #endregion #region Polygon XmlNode polygonNode = rType.SelectSingleNode("Polygon"); if (polygonNode != null) { Polygon polygon = new Polygon(); foreach (XmlNode ringNode in polygonNode.SelectNodes("Ring")) { Ring ring = new Ring(); foreach (XmlNode pointNode in ringNode.SelectNodes("Point[@x and @y]")) { ring.AddPoint(new Point(double.Parse(pointNode.Attributes["x"].Value, _nhi), double.Parse(pointNode.Attributes["y"].Value, _nhi))); } if (ring.PointCount > 2) { polygon.AddRing(ring); } } if (polygon.RingCount == 0) { serviceRequest.Response = CreateException("Invalid Polygon definition node"); return; } queryGeometry = polygon; } #endregion if (queryGeometry == null) { serviceRequest.Response = CreateException("No geometry (Envelope,Polygon) definition node"); return; } #endregion #region Layer/Featureclass XmlNode layerNode = rType.SelectSingleNode("Layer[@id]"); if (layerNode == null) { serviceRequest.Response = CreateException("No layer definition node"); return; } string id = layerNode.Attributes["id"].Value; MapServerHelper.Layers layers = MapServerHelper.FindMapLayers(map, true, id); if (layers.Count != 1) { serviceRequest.Response = CreateException("Can't find layer with id='" + id + "'"); return; } IFeatureClass fc = layers[0].Class as IFeatureClass; if (fc == null || fc.FindField("GRID_LEVEL") == null || fc.FindField("GRID_ROW") == null || fc.FindField("GRID_COLUMN") == null || fc.FindField("FILE") == null) { serviceRequest.Response = CreateException("Featureclass is not a tilegrid"); return; } #endregion #region Query SpatialFilter filter = new SpatialFilter(); filter.AddField(fc.IDFieldName); filter.AddField(fc.ShapeFieldName); filter.AddField("GRID_LEVEL"); filter.AddField("GRID_ROW"); filter.AddField("GRID_COLUMN"); filter.AddField("FILE"); filter.Geometry = queryGeometry; filter.WhereClause = "GRID_LEVEL=" + level; StringBuilder sb = new StringBuilder(); sb.Append("<TileRequest><Tiles>"); using (IFeatureCursor cursor = fc.GetFeatures(filter)) { IFeature feature; while ((feature = cursor.NextFeature) != null) { sb.Append("<Tile"); #region Envelope IEnvelope env = feature.Shape.Envelope; sb.Append(" id='" + feature.OID + "'"); sb.Append(" minx='" + env.minx.ToString(_nhi) + "'"); sb.Append(" miny='" + env.miny.ToString(_nhi) + "'"); sb.Append(" maxx='" + env.maxx.ToString(_nhi) + "'"); sb.Append(" maxy='" + env.maxy.ToString(_nhi) + "'"); #endregion #region File FileInfo fi = new FileInfo(feature["FILE"].ToString()); sb.Append(" path='/" + feature["GRID_LEVEL"].ToString() + "/" + feature["GRID_ROW"].ToString() + "/" + feature["GRID_COLUMN"].ToString() + fi.Extension + "'"); #endregion sb.Append(" />"); } } sb.Append("</Tiles></TileRequest>"); #endregion serviceRequest.Response = sb.ToString(); } catch (Exception ex) { _mapServer.Log("Service:" + serviceRequest.Service, loggingMethod.error, ex.Message + "\r\n" + ex.StackTrace); serviceRequest.Response = CreateException(ex.Message); return; } }