/// <summary>
        /// 获得选中的要素DataTable
        /// </summary>
        /// <param name="_featureLayer">IFeatureLayer</param>
        /// <returns>ICursor</returns>
        public static DataTable GetFeatureAttr(IFeatureLayer _featureLayer)
        {
            DataTable dt = new DataTable();
            IFeatureSelection featureSelection = _featureLayer as IFeatureSelection;
            ISelectionSet selectionSet = featureSelection.SelectionSet;

            ICursor cursor = null;
            try
            {
                selectionSet.Search(null, false, out cursor);

                //IRow row = cursor.NextRow();
                //while (row != null)
                //{
                //    IFeature feature = (IFeature)row;
                //    ITable table = row.Table;
                //    int nameIndex = table.FindField("PAC");
                //    if (nameIndex > 0)
                //    {
                //        string value = (string)feature.get_Value(nameIndex);
                //        MessageBox.Show(value);
                //        break;
                //    }
                //}
            }
            catch { }
            return dt;
        }
Example #2
0
 public frmSymbol(IFeatureLayer featLayer,AxMapControl mapcontrol,AxTOCControl toccontrol)
 {
     InitializeComponent();
     this.Layer = featLayer;
     axmapcontrol = mapcontrol;
     axtoccontrol = toccontrol;
 }
        /// <summary>
        ///  删除满足条件的停采线要素
        /// </summary>
        /// <params name="featureLayer">停采线图层</params>
        /// <params name="stopLineID">停采线ID</params>
        /// <returns>成功删除返回true</returns>
        public static bool DeleteLineFeature(IFeatureLayer featureLayer, string stopLineID)
        {
            try
            {
                IFeatureClass featureClass = featureLayer.FeatureClass;

                    IDataset dataset = (IDataset)featureClass;
                    IWorkspace workspace = dataset.Workspace;
                    IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;
                    workspaceEdit.StartEditing(false);
                    workspaceEdit.StartEditOperation();
                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = string.Format("BID='{0}'", stopLineID);
                //Get table and row
                ITable esriTable = (ITable)featureLayer.FeatureClass;
                esriTable.DeleteSearchedRows(queryFilter);
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);
                GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll|esriViewDrawPhase.esriViewGeoSelection, null, null);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("删除停采线要素出错:" + ex.Message);
                return false;
            }
        }
 /// <summary>
 /// Show the properties of a feature layer in the legend.
 /// </summary>
 /// <param name="e"></param>
 public void ShowProperties(IFeatureLayer e)
 {
     using (var dlg = new LayerDialog(e, new FeatureCategoryControl()))
     {
         ShowDialog(dlg);
     }
 }
        public static void AddFeaturesToSelection(IFeatureLayer featureLayer, string fldName, string[] values)
        {
            if (featureLayer != null && values != null)
            {
                try
                {
                    //  IFeatureClass featureClass = featureLayer.FeatureClass;
                    IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
                    if (featureSelection != null && values.Length > 0)
                    {
                        IQueryFilter qfilter = new QueryFilterClass();
                        string strGUIDs = string.Empty;
                        //construct Whereclause with OIDs
                        foreach (string guid in values)
                        {
                            if (string.IsNullOrEmpty(strGUIDs) == false)
                                strGUIDs += ",";

                            strGUIDs += string.Format("'{0}'", guid);
                        }

                        qfilter.WhereClause = string.Format("{0} IN ({1})", fldName, strGUIDs);

                        // ISelectionSet selectionSet = featureClass.Select(qfilter, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, workspace);

                        featureSelection.SelectFeatures(qfilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    }
                }
                catch { }
            }
        }
Example #6
0
 public void Add(IFeatureLayer featureLayer)
 {
     if (m_FeatureLayerList.Contains(featureLayer))
         return;
     else
         m_FeatureLayerList.Add(featureLayer);
 }
Example #7
0
        private void comboBoxDataList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sLayerName = comboBoxDataList.Text;
            AxMapControl axMap = pMainFrm.getMapControl();


            try
            {
                for (int i = 0; i <= axMap.LayerCount - 1; i++)
                {
                    ILayer pLyr = axMap.get_Layer(i);
                    if (pLyr.Name == sLayerName)
                    {
                        if (pLyr is IFeatureLayer)
                        {
                            m_pInFeatLyr = pLyr as IFeatureLayer;

                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
        /// <summary>
        /// ���ݵ㼯���������Ҫ��
        /// </summary>
        /// <params name="featureLayer"></params>
        /// <params name="lstPoint"></params>
        public void CreateLine(IFeatureLayer featureLayer, List<IPoint> lstPoint, int ID)
        {
            //try
            //{
            IFeatureClass featureClass = featureLayer.FeatureClass;
            if (featureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                IPointCollection multipoint = new MultipointClass();
                if (lstPoint.Count < 2)
                {
                    MessageBox.Show(@"��ѡ���������������ϵ�����", "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                ISegmentCollection pPath = new PathClass();
                ILine pLine;
                ISegment pSegment;
                object o = Type.Missing;
                for (int i = 0; i < lstPoint.Count - 1; i++)
                {
                    pLine = new LineClass();
                    pLine.PutCoords(lstPoint[i], lstPoint[i + 1]);
                    pSegment = pLine as ISegment;
                    pPath.AddSegment(pSegment, ref o, ref o);
                }
                IGeometryCollection pPolyline = new PolylineClass();
                pPolyline.AddGeometry(pPath as IGeometry, ref o, ref o);

                IDataset dataset = (IDataset)featureClass;
                IWorkspace workspace = dataset.Workspace;
                IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;

                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();

                IFeature feature = featureClass.CreateFeature();

                IGeometry geometry = pPolyline as IGeometry;
                DrawCommon.HandleZMValue(feature, geometry);//����ͼ��Zֵ����

                feature.Shape = pPolyline as PolylineClass;
                int iFieldID = feature.Fields.FindField(GIS_Const.FIELD_BID);
                feature.Value[iFieldID] = ID.ToString();
                feature.Store();
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(false);

                IEnvelope envelop = feature.Shape.Envelope;
                DataEditCommon.g_pMyMapCtrl.ActiveView.Extent = envelop;
                DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
            }
            else
            {
                MessageBox.Show(@"��ѡ����ͼ�㡣", "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //}
            //catch
            //{
            //    return;
            //}
        }
Example #9
0
    public bool joinTabletoFeatureLayer(IServerContext mapContext,
        ITable externalTable,
        IFeatureLayer featureLayer,
        string tableJoinField,
        string layerJoinField,
        esriJoinType joinType)
    {
        IDisplayTable pDispTable = featureLayer as IDisplayTable;

        IFeatureClass pFCLayer = pDispTable.DisplayTable as IFeatureClass;
        ITable pTLayer = (ITable)pFCLayer;

        string strJnFieldLayer = layerJoinField;
        string strJnFieldTable = tableJoinField;

        IMemoryRelationshipClassFactory pMemRelFact = (IMemoryRelationshipClassFactory)mapContext.CreateObject("esriGeoDatabase.MemoryRelationshipClassFactory");
        IRelationshipClass pRelClass = (IRelationshipClass)pMemRelFact.Open("Join",
                                                        (IObjectClass)externalTable, strJnFieldTable,
                                                        (IObjectClass)pTLayer, strJnFieldLayer,
                                                        "forward", "backward",
                                                        esriRelCardinality.esriRelCardinalityOneToOne);

        IDisplayRelationshipClass pDispRC = (IDisplayRelationshipClass)featureLayer;
        pDispRC.DisplayRelationshipClass(pRelClass, joinType);   //esriLeftOuterJoin
        IDisplayTable dt = (IDisplayTable)featureLayer;
        ITable jointable = dt.DisplayTable;

        bool retval = false;
        if (jointable is IRelQueryTable)
        {
            retval = true;
        }
        return retval;
    }
 public FormFieldCalculation(IFeatureLayer pFeatureLayer, DataGridView dataGridView, string strField)
 {
     InitializeComponent();
     _FeatureLayer = pFeatureLayer;
     Field = strField;
     Gridviwe = dataGridView; 
 }
        //执行计算,输出计算结果信息字符串
        private string FieldCal(IFeatureLayer pFtLayer, string strExpression)
        {
            txtMessage.Text = "正在计算请稍后……\r\n";
            try
            {
                Geoprocessor Gp = new Geoprocessor();
                Gp.OverwriteOutput = true;
                CalculateField calField = new CalculateField();
                
                calField.expression = strExpression;

                Gp.Execute(calField, null);

                for (int i = 0; i < Gp.MessageCount; i++)
                {
                    txtMessage.Text += Gp.GetMessage(i).ToString() + "\r\n";
                }
                return "计算成功";
            }
            catch (Exception e)
            {
                txtMessage.Text += e.Message;
                return "计算失败" + e.Message;
            }
        }
Example #12
0
 public static void AddFeaturesToSelection(IFeatureLayer featureLayer, int[] oids, string whereClause)
 {
     if (featureLayer != null && oids != null)
     {
         try
         {
             IFeatureClass featureClass = featureLayer.FeatureClass;
             IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
             if (featureSelection != null && featureClass != null && oids.Length > 0)
             {
                 IWorkspace workspace = DisplayMap.GetWorkspaceFromClass(featureClass);
                 if (workspace != null)
                 {
                     IQueryFilter2 queryFilter = new QueryFilterClass();
                     queryFilter.WhereClause = featureClass.OIDFieldName + " < 0";
                     ISelectionSet selectionSet = featureClass.Select(queryFilter, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, workspace);
                     selectionSet.AddList(oids.Length, ref oids[0]);
                     queryFilter = new QueryFilterClass();
                     if (string.IsNullOrEmpty(whereClause) == false)
                     {
                         queryFilter.WhereClause = whereClause;
                         selectionSet = selectionSet.Select(queryFilter, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, workspace);
                     }
                     featureSelection.SelectionSet = selectionSet;
                 }
             }
         }
         catch { }
     }
 }
 public frmUpstreamCreateOwnerList(MainFrm _pMainFrm,IFeatureLayer _pParcelFeatLayer, IArray _pFeatArray)
 {
     pParcelFeatLayer = _pParcelFeatLayer;
     pFeatArray = _pFeatArray;
     pMainFrm = _pMainFrm;
     InitializeComponent();
 }
        /// <summary>
        /// Creates a new instance of LayerDialog form to display the symbology and
        /// other properties of the specified feature layer
        /// </summary>
        /// <param name="selectedLayer">the specified feature layer that is
        /// modified using this form</param>
        public FeatureLayerDialog(IFeatureLayer selectedLayer)
        {
            InitializeComponent();

            _layer = selectedLayer;
            propertyGrid1.SelectedObject = _layer;
            Configure();
        }
 private void cbxLayers2Symbolize_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (cbxLayers2Symbolize.SelectedItem != null)
     {
         string strLayer2Symbolize = cbxLayers2Symbolize.SelectedItem.ToString();
         layer2Symbolize = GetFeatureLayer(strLayer2Symbolize);
     }
 }
Example #16
0
 public TextToShapefile(IMapControlDefault mapControl, UIStatusBar pStatusBar)
 {
     m_mapControl = mapControl;
     IMap pMap = m_mapControl.ActiveView.FocusMap;
     m_FeatureLayer = pMap.get_Layer(0) as IFeatureLayer;
     m_statusBar = pStatusBar;
     frmW = new frmWaiting();
 }
Example #17
0
 /// <summary>
 /// Creates a new instance of the attribute Table editor form
 /// <param name="featureLayer">The feature layer associated with
 /// this instance and displayed in the editor</param>
 /// </summary>
 public AttributeDialog(IFeatureLayer featureLayer)
 {
     InitializeComponent();
     if (featureLayer != null)
     {
         tableEditorControl1.FeatureLayer = featureLayer;
     }
 }
Example #18
0
 public AlgorithmTimDuong(IFeatureLayer fromLayer, IFeatureLayer byLayer)
 {
     this._queryByLayer = new QueryByLayerClass();
     this._queryByLayer.UseSelectedFeatures = true;
     this._queryByLayer.FromLayer = this._fromLayer;
     this._queryByLayer.ByLayer = this._byLayer;
     this._fromLayer = fromLayer;
     this._byLayer = byLayer;
 }
 public FormAttributeTable(AxMapControl pMapControl, IMapControl3 pMapCtrl)
 {
     InitializeComponent();
     _MapControl = pMapControl;
     m_mapControl = pMapCtrl;
     ILayer pLayer = (ILayer)m_mapControl.CustomProperty;
     pFLayer = pLayer as IFeatureLayer;
     pFClass = pFLayer.FeatureClass;
 }
        public PolygonsPartitionAggregation(IFeatureLayer feaLyr,string resultPath,string gradeField)
        {
            m_GP = new Geoprocessor();

            m_FeaLyr = feaLyr;
            m_FeaCls = feaLyr.FeatureClass;
            m_PartitionField = gradeField;

            m_WorkingPath = resultPath;
        }
Example #21
0
        public frmBurstReport(MainFrm _pMainFrm, IFeatureLayer _pFeatLayerValves, IFeatureLayer _pFeatLayerWaterLines, IArray  _pArrayValves, IFeature _pFeatureWaterLine)
        {
            pMainFrm = _pMainFrm;
            pFeatLayerValves = _pFeatLayerValves;
            pFeatLayerWaterLines = _pFeatLayerWaterLines;
            pArrayValves = _pArrayValves;
            pFeatureWaterLine = _pFeatureWaterLine;

            InitializeComponent();
        }
 public static void SelectLayerFeatures(IFeatureLayer fealyr,string whereclause)
 {
     IFeatureSelection feaSelection = fealyr as IFeatureSelection;
     if(feaSelection!=null)
     {
         IQueryFilter queryFilter = new QueryFilterClass();
         queryFilter.WhereClause = whereclause;
         feaSelection.CombinationMethod = esriSelectionResultEnum.esriSelectionResultNew;
         feaSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
     }
 }
    internal void AddItem(string itemName, IFeatureLayer layer)
    {
      if (s_comboBox.items.Count == 0)
      {
        m_selAllCookie = s_comboBox.Add("Select All");
        s_comboBox.Select(m_selAllCookie);
      }

      // Add each item to combo box.
      int cookie = s_comboBox.Add(itemName, layer);
    }
 public static bool isTypePolygon(IFeatureLayer layer)
 {
     try
     {
         return (layer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon);
     }
     catch
     {
         return false;
     }
 }
 public DisplayFlowDirections(IMap map, IActiveView actView)
 {
     if (map != null)
     {
         this._map = map;
         _activeView = actView;
         _primaryLyr = DisplayMap.GetMapLayerByLayerName(map, "PrimaryConductor", LayerType.FeatureLayer) as IFeatureLayer;
         _secondaryLyr = DisplayMap.GetMapLayerByLayerName(map, "SecondaryConductor", LayerType.FeatureLayer) as IFeatureLayer;
         //this.UpdateActiveViewEvents(actView);
         //((IMapControlEvents2_Event)mapControl).OnMapReplaced += new IMapControlEvents2_OnMapReplacedEventHandler(SourceTab_OnMapReplaced);
     }
 }
        public static bool CreateLineFeature(IFeatureLayer featureLayer, IPolyline pStopLine, LibEntity.StopLine stopLineEntity)
        {
            if (pStopLine == null || pStopLine.IsEmpty)
            {
                return false;
            }

            try
            {
                IFeatureClass featureClass = featureLayer.FeatureClass;
                if (featureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    IDataset dataset = (IDataset)featureClass;
                    IWorkspace workspace = dataset.Workspace;
                    IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;
                    workspaceEdit.StartEditing(false);
                    workspaceEdit.StartEditOperation();
                    IFeature feature = featureClass.CreateFeature();

                    Common.DataEditCommon.ZMValue(feature, pStopLine);  //几何图形Z值处理

                    feature.Shape = pStopLine;

                    //编号
                    int iFieldID = feature.Fields.FindField("BID");
                    if (iFieldID > -1)
                        feature.Value[iFieldID] = stopLineEntity.binding_id;

                    //名称
                    iFieldID = feature.Fields.FindField("NAME");
                    if (iFieldID > -1)
                        feature.Value[iFieldID] = stopLineEntity.stop_line_name;

                    feature.Store();
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(true);
                    //GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent = pStopLine.Envelope;
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent.Expand(1.5, 1.5, true);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.Map.SelectFeature(featureLayer, feature);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);

                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("创建停采线要素出错:" + ex.Message);
                return false;
            }
        }
 private void CbxFieldAdditems(IFeatureLayer featureLayer)
 {
     IFields fields = featureLayer.FeatureClass.Fields;
     IField field = null;
     cbxFields.Items.Clear();
     for (int i = 0; i < fields.FieldCount; i++)
     {
         field = fields.get_Field(i);
         if (field.Type != esriFieldType.esriFieldTypeGeometry)
             cbxFields.Items.Add(field.Name);
     }
 }
 public SelectTemplateFormGraphic(IFeatureLayer featLayer)
 {
     InitializeComponent();
     try{
     this.Text = A4LGSharedFunctions.Localizer.GetString("AAOptionDialogTemplate");
     }
     catch
     {
     }
     _featLayer = featLayer;
     LoadListView();
 }
        public ProPortialRender(AxMapControl pMapcontrol, IFeatureLayer pFtLayer,  string pFieldName)
        {
            IGeoFeatureLayer pGeo = pFtLayer as IGeoFeatureLayer;

            IProportionalSymbolRenderer pProRender = new ProportionalSymbolRendererClass();

            pProRender.Field = pFieldName;

            pProRender.ValueUnit = esriUnits.esriUnknownUnits;

            ISimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbolClass();

            pMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;

            pMarkerSymbol.Size = 2;

            pMarkerSymbol.Color = GetRGBColor(255, 0, 0);

            pProRender.MinSymbol = pMarkerSymbol as ISymbol;

            IDataStatistics pDataStat = new DataStatisticsClass();

            IFeatureCursor pFtCursor = pFtLayer.FeatureClass.Search(null, false);

            pDataStat.Cursor = pFtCursor as ICursor;

            pDataStat.Field = pFieldName;

            pProRender.MinDataValue = pDataStat.Statistics.Minimum;

            pProRender.MaxDataValue = pDataStat.Statistics.Maximum;

            IFillSymbol pFillS = new SimpleFillSymbolClass();

            pFillS.Color = GetRGBColor(239, 228, 190);

            ILineSymbol pLineS = new SimpleLineSymbolClass();

            pLineS.Width = 2;

            pFillS.Outline = pLineS;

            ISimpleFillSymbol pSFillS = pFillS as ISimpleFillSymbol;

            pSFillS.Color = GetRGBColor(100, 100, 253);

            pProRender.BackgroundSymbol = pFillS;

            pGeo.Renderer = pProRender as IFeatureRenderer;

            pMapcontrol.ActiveView.Refresh();
        }
Example #30
0
        /// <summary>
        /// 在掘进进尺图层创建掘进进尺线要素
        /// </summary>
        /// <params name="featureLayer">掘进进尺图层</params>
        /// <params name="pJjPolyline">掘进进尺线</params>
        /// <params name="tunnelID">对应的巷道ID</params>
        /// <returns>成功返回true</returns>
        public static bool CreateLineFeature(IFeatureLayer featureLayer, IPolyline pJjPolyline, string bindingID,  double distance)
        {
            if (pJjPolyline == null || pJjPolyline.IsEmpty)
            {
                return false;
            }

            try
            {
                IFeatureClass featureClass = featureLayer.FeatureClass;

                if (featureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    IDataset dataset = (IDataset)featureClass;
                    IWorkspace workspace = dataset.Workspace;
                    IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;
                    workspaceEdit.StartEditOperation();
                    IFeature feature = featureClass.CreateFeature();

                    Common.DataEditCommon.ZMValue(feature, pJjPolyline);  //几何图形Z值处理

                    feature.Shape = pJjPolyline;

                    //绑定编号
                    int iFieldID = feature.Fields.FindField("ID");
                    if (iFieldID > -1)
                        feature.Value[iFieldID] = bindingID;

                    //掘进距离
                    iFieldID = feature.Fields.FindField("Distance");
                    if (iFieldID > -1)
                        feature.Value[iFieldID] = distance;

                    feature.Store();
                    workspaceEdit.StopEditOperation();

                    //缩放到新增的线要素,并高亮该要素
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent = pJjPolyline.Envelope;
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent.Expand(1.5, 1.5, false);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.Map.SelectFeature(featureLayer, feature);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);
                    return true;
                }

                return false;
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("创建掘进进尺线要素出错:" + ex.Message);
                return false;
            }
        }
Example #31
0
        /// <summary>
        /// 判断鼠标点击处有无巷道要素
        /// </summary>
        /// <params name="m_hookHelper"></params>
        /// <params name="pMousePoint">鼠标点</params>
        /// <params name="pFeatureLayer">导线点图层</params>
        /// <params name="theFeature">返回离鼠标最近的导线点</params>
        public void TestExistPointFeature(IHookHelper m_hookHelper, IPoint pMousePoint, IFeatureLayer pFeatureLayer, ref IFeature theFeature)
        {
            ArrayList             pSelected = new ArrayList();
            IFeatureClass         pFeatureClass;
            ISelectionEnvironment pSelectionEnvironment;
            IFeature             pFeature = null;
            IGeometry            pGeometry;
            ITopologicalOperator pTopolagicalOperator;
            double dLength;

            IEnvelope pSrchEnv;

            pSelectionEnvironment = new SelectionEnvironmentClass();
            dLength         = pSelectionEnvironment.SearchTolerance;
            pGeometry       = pMousePoint;
            dLength         = DataEditCommon.ConvertPixelDistanceToMapDistance(m_hookHelper.ActiveView, dLength);
            pSrchEnv        = pMousePoint.Envelope;
            pSrchEnv.Width  = dLength;
            pSrchEnv.Height = dLength;
            pSrchEnv.CenterAt(pMousePoint);

            pTopolagicalOperator = (ITopologicalOperator)pGeometry;
            IGeometry pBuffer = pTopolagicalOperator.Buffer(dLength);

            pGeometry = pBuffer;

            IFeature pFeat = null;
            IMap     pMap  = m_hookHelper.FocusMap;

            pFeatureClass = pFeatureLayer.FeatureClass;
            IIdentify2 pID = pFeatureLayer as IIdentify2;
            //IArray pArray = pID.Identify(pSrchEnv, null);
            IArray pArray = pID.Identify(pGeometry, null);
            IFeatureIdentifyObj pFeatIdObj;
            IRowIdentifyObject  pRowObj;

            if (pArray != null)
            {
                for (int j = 0; j < pArray.Count; j++)
                {
                    if (pArray.Element[j] is IFeatureIdentifyObj)
                    {
                        pFeatIdObj = pArray.Element[j] as IFeatureIdentifyObj;
                        pRowObj    = pFeatIdObj as IRowIdentifyObject;
                        pFeature   = pRowObj.Row as IFeature;
                        pSelected.Add(pFeature);
                    }
                }
                pArray.RemoveAll();
            }
            theFeature = pFeature;

            return;

            //GetClosestFeatureInCollection(m_hookHelper, dLength, pSelected, pMousePoint, ref pFeat);
            //if (pFeat != null)
            //    theFeature = pFeat;
            //else
            //    theFeature = null;
        }
Example #32
0
        async public Task <bool> Open()
        {
            try
            {
                _state = DatasetState.unknown;
                _elements.Clear();

                FileInfo fi_gml = new FileInfo(_connectionString);
                if (!fi_gml.Exists)
                {
                    return(false);
                }

                FileInfo fi_xsd = new FileInfo(fi_gml.FullName.Substring(0, fi_gml.FullName.Length - fi_gml.Extension.Length) + ".xsd");
                if (!fi_xsd.Exists)
                {
                    return(false);
                }

                _gml_file = fi_gml.FullName;
                _xsd_file = fi_xsd.FullName;

                XmlDocument schema = new XmlDocument();
                schema.LoadXml(System.IO.File.ReadAllText(fi_xsd.FullName));
                XmlSchemaReader schemaReader    = new XmlSchemaReader(schema);
                string          targetNamespace = schemaReader.TargetNamespaceURI;
                if (targetNamespace == String.Empty)
                {
                    return(false);
                }

                PlugInManager compMan = new PlugInManager();
                foreach (string elementName in schemaReader.ElementNames)
                {
                    string       shapeFieldName;
                    geometryType geomType;
                    Fields       fields = schemaReader.ElementFields(elementName, out shapeFieldName, out geomType);
                    FeatureClass fc     = await FeatureClass.CreateAsync(this, elementName, fields);

                    fc.ShapeFieldName = shapeFieldName;
                    fc.GeometryType   = geomType;
                    IFeatureLayer layer = LayerFactory.Create(fc) as IFeatureLayer;
                    if (layer == null)
                    {
                        continue;
                    }

                    //layer.FeatureRenderer = compMan.getComponent(KnownObjects.Carto_UniversalGeometryRenderer) as IFeatureRenderer;

                    _elements.Add(layer);
                }

                _doc = new XmlDocument();
                using (XmlTextReader xmlTextReader = new XmlTextReader(fi_gml.FullName))
                {
                    xmlTextReader.ReadToDescendant("boundedBy", "http://www.opengis.net/gml");
                    string boundedBy = xmlTextReader.ReadOuterXml();

                    _doc.LoadXml(boundedBy);
                }
                _ns = new XmlNamespaceManager(_doc.NameTable);
                _ns.AddNamespace("GML", "http://www.opengis.net/gml");
                _ns.AddNamespace("WFS", "http://www.opengis.net/wfs");
                _ns.AddNamespace("OGC", "http://www.opengis.net/ogc");
                _ns.AddNamespace("myns", targetNamespace);
                XmlNode boundedByNode = _doc.ChildNodes[0];

                if (boundedByNode != null)
                {
                    XmlNode geomNode = boundedByNode.SelectSingleNode("GML:*", _ns);
                    if (geomNode != null)
                    {
                        _envelope = GeometryTranslator.GML2Geometry(geomNode.OuterXml, _gmlVersion) as IEnvelope;
                        if (geomNode.Attributes["srsName"] != null)
                        {
                            _sRef = gView.Framework.Geometry.SpatialReference.FromID(geomNode.Attributes["srsName"].Value);
                        }
                    }
                }

                _state = DatasetState.opened;
                return(true);
            }
            catch (Exception ex)
            {
                _errMsg = ex.Message;
                return(false);
            }
        }
Example #33
0
        /// <summary>
        /// Export graphics to a shapefile
        /// </summary>
        /// <param name="fileNamePath">Path to shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <param name="polyLineFC">Is Polyline FC</param>
        /// <returns>Created featureclass</returns>
        private IFeatureClass ExportToShapefile(string fileNamePath, List <Graphic> graphicsList, ISpatialReference ipSpatialRef, bool polyLineFC)
        {
            int           index           = fileNamePath.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
            string        folder          = fileNamePath.Substring(0, index);
            string        nameOfShapeFile = fileNamePath.Substring(index + 1);
            string        shapeFieldName  = "Shape";
            IFeatureClass featClass       = null;

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                try
                {
                    IWorkspaceFactory workspaceFactory = null;
                    workspaceFactory = new ShapefileWorkspaceFactoryClass();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folder, 0);
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
                    if (featureWorkspace == null)
                    {
                        return(null);
                    }

                    IFields     fields     = null;
                    IFieldsEdit fieldsEdit = null;
                    fields     = new Fields();
                    fieldsEdit = (IFieldsEdit)fields;
                    IField     field     = null;
                    IFieldEdit fieldEdit = null;
                    field            = new FieldClass();
                    fieldEdit        = (IFieldEdit)field;
                    fieldEdit.Name_2 = "Shape";
                    fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry);
                    IGeometryDef     geomDef     = null;
                    IGeometryDefEdit geomDefEdit = null;
                    geomDef     = new GeometryDefClass();
                    geomDefEdit = (IGeometryDefEdit)geomDef;

                    if (polyLineFC)
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    }
                    else
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                    }

                    geomDefEdit.SpatialReference_2 = ipSpatialRef;

                    fieldEdit.GeometryDef_2 = geomDef;
                    fieldsEdit.AddField(field);
                    string graphicsType = graphicsList[0].GraphicType.ToString();
                    switch (graphicsType)
                    {
                    case "Line":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Geodetic Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "OriginX";
                        fieldEdit.AliasName_2 = "Origin X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "OriginY";
                        fieldEdit.AliasName_2 = "Origin Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DestX";
                        fieldEdit.AliasName_2 = "Dest X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DestY";
                        fieldEdit.AliasName_2 = "Dest Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Angle";
                        fieldEdit.AliasName_2 = "Angle";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "AngleUnit";
                        fieldEdit.AliasName_2 = "Angle Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "Circle":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistType";
                        fieldEdit.AliasName_2 = "Distance Type";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "Ellipse":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "MajAxis";
                        fieldEdit.AliasName_2 = "Major Axis";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "MinAxis";
                        fieldEdit.AliasName_2 = "Minor Axis";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Angle";
                        fieldEdit.AliasName_2 = "Angle";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "AngleUnit";
                        fieldEdit.AliasName_2 = "Angle Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "RangeRing":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Rings";
                        fieldEdit.AliasName_2 = "Rings";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeInteger;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Geodetic Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        break;
                    }
                    }

                    featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, "");

                    foreach (Graphic graphic in graphicsList)
                    {
                        if (graphic.Attributes == null)
                        {
                            continue;
                        }
                        IFeature feature = featClass.CreateFeature();

                        if (polyLineFC)
                        {
                            feature.Shape = graphic.Geometry;
                        }
                        else
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }
                        switch (graphic.GraphicType.ToString())
                        {
                        case "Line":
                        {
                            System.Object dist;
                            System.Object angle;
                            System.Object angleunit;
                            System.Object ox;
                            System.Object oy;
                            System.Object dx;
                            System.Object dy;
                            System.Object distunit;

                            graphic.Attributes.TryGetValue("distance", out dist);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("startx", out ox);
                            graphic.Attributes.TryGetValue("starty", out oy);
                            graphic.Attributes.TryGetValue("endx", out dx);
                            graphic.Attributes.TryGetValue("endy", out dy);
                            graphic.Attributes.TryGetValue("angle", out angle);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);
                            feature.set_Value(feature.Fields.FindField("Distance"), dist);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("OriginX"), ox);
                            feature.set_Value(feature.Fields.FindField("OriginY"), oy);
                            feature.set_Value(feature.Fields.FindField("DestX"), dx);
                            feature.set_Value(feature.Fields.FindField("DestY"), dy);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);
                            break;
                        }

                        case "Circle":
                        {
                            System.Object radius;
                            System.Object disttype;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("radius", out radius);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("disttype", out disttype);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Distance"), radius);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("DistType"), disttype);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);

                            break;
                        }

                        case "Ellipse":
                        {
                            System.Object majoraxis;
                            System.Object minoraxis;
                            System.Object angle;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;
                            System.Object angleunit;

                            graphic.Attributes.TryGetValue("majoraxis", out majoraxis);
                            graphic.Attributes.TryGetValue("minoraxis", out minoraxis);
                            graphic.Attributes.TryGetValue("azimuth", out angle);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);

                            feature.set_Value(feature.Fields.FindField("MajAxis"), majoraxis);
                            feature.set_Value(feature.Fields.FindField("MinAxis"), minoraxis);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);
                            break;
                        }

                        case "RangeRing":
                        {
                            System.Object rings;
                            System.Object distance;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("rings", out rings);
                            graphic.Attributes.TryGetValue("distance", out distance);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Rings"), rings);
                            feature.set_Value(feature.Fields.FindField("Distance"), distance);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            break;
                        }
                        }
                        feature.Store();
                    }

                    IFeatureLayer featurelayer = null;
                    featurelayer = new FeatureLayerClass();
                    featurelayer.FeatureClass = featClass;
                    featurelayer.Name         = featClass.AliasName;

                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                    workspace = null;
                    GC.Collect();

                    return(featClass);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return(featClass);
                }
            }
        }
        private void btOK_Click(object sender, EventArgs e)
        {
            string        pPointFileName   = cboBoxPointLayer.SelectedItem.ToString();
            string        pCenterlinName   = comboBoxExCenterlineLayer.SelectedItem.ToString();
            IFeatureLayer pPointLayer      = null;
            IFeatureLayer pCenterlineLayer = null;

            for (int i = 0; i < pMapcontrol.LayerCount; i++)
            {
                if (pPointFileName == pMapcontrol.get_Layer(i).Name)
                {
                    pPointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
                if (pCenterlinName == pMapcontrol.get_Layer(i).Name)
                {
                    pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
            }
            IFeatureClass  pLineFC      = pCenterlineLayer.FeatureClass;
            IFeatureClass  pPointFC     = pPointLayer.FeatureClass;
            IQueryFilter   pQF          = null;
            IFeatureCursor pLineCursor  = pLineFC.Search(null, false);
            IFeatureCursor pPointCursor = pPointFC.Search(null, false);
            IFeature       pLineFeature = pLineCursor.NextFeature();
            DataTable      ptTable      = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pPointFC as ITable, pQF);

            ptTable.Columns.Add("长度");
            ptTable.Columns.Add("距离");
            ptTable.Columns.Add("中间点坐标");
            if (pLineFeature != null)
            {
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                //wgs 84
                IGeographicCoordinateSystem wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326) as IGeographicCoordinateSystem;
                IUnit     meterUnit = spatialReferenceFactory.CreateUnit((int)ESRI.ArcGIS.Geometry.esriSRUnitType.esriSRUnit_Meter);
                IPolyline pline     = pLineFeature.Shape as IPolyline;
                pline.SpatialReference = wgs84;

                IProximityOperator pPO       = pline as IProximityOperator;
                IFeature           ptFeature = pPointCursor.NextFeature();
                int idx = 0;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialReferenceFactory);
                while (ptFeature != null)
                {
                    DataRow row = ptTable.Rows[idx];
                    IPoint  pt  = ptFeature.Shape as IPoint;
                    pt.SpatialReference = wgs84;
                    IPoint nearestpt = pPO.ReturnNearestPoint(pt, esriSegmentExtension.esriNoExtension);
                    double distance  = DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pt, nearestpt);
                    // = pPO.ReturnDistance(pt);

                    row["距离"] = distance;
                    if (idx == 0)
                    {
                        row["长度"] = 0;
                    }
                    else
                    {
                        DataRow preRow = ptTable.Rows[idx - 1];
                        row["长度"] = Convert.ToDouble(row[EvConfig.IMUMoveDistanceField]) - Convert.ToDouble(preRow[EvConfig.IMUMoveDistanceField]);
                    }
                    ptFeature = pPointCursor.NextFeature();
                    idx++;
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialReferenceFactory);
            }


            DataTable dt2 = new DataTable();

            dt2.Columns.Add("名称");
            dt2.Columns.Add("长度");
            dt2.Columns.Add("比例");

            //  List<DataRow> rowlist = (dt2.Rows.Where(e => Convert.ToDouble(e["距离"]) <= 2)).ToList();

            List <DataRow> less1 = (from DataRow r in ptTable.Rows
                                    where Convert.ToDouble(r["距离"]) <= 1
                                    select r).ToList();
            double length1 = less1.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum1    = less1.Count;

            List <DataRow> Great2 = (from DataRow r in ptTable.Rows
                                     where Convert.ToDouble(r["距离"]) > 2
                                     select r).ToList();
            double length2 = Great2.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum2    = Great2.Count;

            List <DataRow> Medium2 = (from DataRow r in ptTable.Rows
                                      where Convert.ToDouble(r["距离"]) > 1 && Convert.ToDouble(r["距离"]) <= 2
                                      select r).ToList();
            double length3 = Medium2.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum3    = Medium2.Count;

            DataRow r1;

            r1    = dt2.Rows.Add();
            r1[0] = "≤1米";
            r1[1] = length1;
            r1[2] = 1.0 * sum1 / (sum1 + sum2 + sum3);

            r1    = dt2.Rows.Add();
            r1[0] = ">1米且≤2米";
            r1[1] = length3;
            r1[2] = 1.0 * sum3 / (sum1 + sum2 + sum3);


            r1    = dt2.Rows.Add();
            r1[0] = "大于2米";
            r1[1] = length2;
            r1[2] = 1.0 * sum2 / (sum1 + sum2 + sum3);


            List <DataTable> tablelist = new List <DataTable>();

            tablelist.Add(ptTable);
            tablelist.Add(dt2);

            FRMInsideInspectionReport frm = new FRMInsideInspectionReport(tablelist);

            frm.ShowDialog();
        }
Example #35
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
                {
                    MessageBox.Show("Please select target field");
                    return;
                }

                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                REngine pEngine = m_pForm.pEngine;
                // Creates the input and output matrices from the shapefile//
                string strLayerName = cboTargetLayer.Text;

                int    intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName);
                ILayer pLayer    = m_pForm.axMapControl1.get_Layer(intLIndex);

                IFeatureLayer pFLayer  = pLayer as IFeatureLayer;
                IFeatureClass pFClass  = pFLayer.FeatureClass;
                int           nFeature = pFClass.FeatureCount(null);

                IFeatureCursor pFCursor = pFLayer.Search(null, true);
                IFeature       pFeature = pFCursor.NextFeature();

                //Get index for independent and dependent variables
                //Get variable index
                string strVarNM1  = (string)cboFldnm1.SelectedItem;
                string strVarNM2  = (string)cboFldnm2.SelectedItem;
                int    intVarIdx1 = pFClass.FindField(strVarNM1);
                int    intVarIdx2 = pFClass.FindField(strVarNM2);

                //Store Variable at Array
                double[] arrVar1 = new double[nFeature];
                double[] arrVar2 = new double[nFeature];

                int i = 0;

                while (pFeature != null)
                {
                    arrVar1[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx1));
                    arrVar2[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx2));
                    i++;
                    pFeature = pFCursor.NextFeature();
                }

                //Plot command for R
                StringBuilder plotCommmand = new StringBuilder();

                string strStartPath = m_pForm.strPath;
                string pathr        = strStartPath.Replace(@"\", @"/");
                pEngine.Evaluate("source('" + pathr + "/AllFunctions_LeeL.R')");

                //Get the file path and name to create spatial weight matrix
                string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer);

                if (strNameR == null)
                {
                    return;
                }

                //Create spatial weight matrix in R
                pEngine.Evaluate("library(spdep); library(maptools)");
                pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");

                if (txtSWM.Text == "Default")
                {
                    pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)");
                }
                else
                {
                    int intResult = m_pSnippet.SWMusingGAL(pEngine, pFClass, txtSWM.Text);
                    if (intResult == -1)
                    {
                        return;
                    }
                }

                NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);
                pEngine.SetSymbol("sample.v1", vecVar1);
                NumericVector vecVar2 = pEngine.CreateNumericVector(arrVar2);
                pEngine.SetSymbol("sample.v2", vecVar2);

                string strSigLv     = nudSigLv.Value.ToString();
                string strSigMethod = cboSigMethod.Text;

                if (cboSAM.Text == "Lee's L")
                {
                    #region Li
                    pEngine.Evaluate("sample.l <- L.local.test(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style='W', sig.levels=c(" + strSigLv + "), method='" + strSigMethod + "', alternative='two.sided', diag.zero=FALSE)");

                    double[] dblLValues = pEngine.Evaluate("sample.l$local.L").AsNumeric().ToArray();
                    double[] dblPvalues = pEngine.Evaluate("sample.l$pvalue").AsNumeric().ToArray();
                    string[] strFlgs    = pEngine.Evaluate("as.character(sample.l$sig)").AsCharacter().ToArray();

                    //Save Output on SHP
                    //Add Target fields to store results in the shapefile
                    for (int j = 0; j < 3; j++)
                    {
                        IField     newField  = new FieldClass();
                        IFieldEdit fieldEdit = (IFieldEdit)newField;
                        fieldEdit.Name_2 = lvFields.Items[j].SubItems[1].Text;
                        if (j == 2)
                        {
                            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                        }
                        else
                        {
                            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                        }
                        pFClass.AddField(newField);
                    }

                    //Update Field
                    pFCursor = pFClass.Update(null, false);
                    pFeature = pFCursor.NextFeature();

                    string strFlgFldNam  = lvFields.Items[2].SubItems[1].Text;
                    int    intStatFldIdx = pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
                    int    intPrFldIdx   = pFClass.FindField(lvFields.Items[1].SubItems[1].Text);
                    int    intFlgFldIdx  = pFClass.FindField(strFlgFldNam);

                    int featureIdx = 0;
                    while (pFeature != null)
                    {
                        pFeature.set_Value(intStatFldIdx, dblLValues[featureIdx]);
                        pFeature.set_Value(intPrFldIdx, dblPvalues[featureIdx]);
                        pFeature.set_Value(intFlgFldIdx, strFlgs[featureIdx]);

                        pFCursor.UpdateFeature(pFeature);

                        pFeature = pFCursor.NextFeature();
                        featureIdx++;
                    }
                    pFCursor.Flush();

                    pfrmProgress.Close();

                    if (chkMap.Checked)
                    {
                        double[,] adblMinMaxForLabel = new double[2, 4];
                        ITable pTable = (ITable)pFClass;

                        IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                        pUniqueValueRenderer.FieldCount = 1;
                        pUniqueValueRenderer.set_Field(0, strFlgFldNam);
                        IDataStatistics    pDataStat;
                        IStatisticsResults pStatResults;
                        ISimpleFillSymbol  pSymbol;
                        ICursor            pCursor;

                        IQueryFilter pQFilter = new QueryFilterClass();
                        pQFilter.WhereClause = strFlgFldNam + " = 'HH'";

                        int intCnt = pTable.RowCount(pQFilter);

                        pCursor                  = pTable.Search(pQFilter, true);
                        pDataStat                = new DataStatisticsClass();
                        pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                        pDataStat.Cursor         = pCursor;
                        pStatResults             = pDataStat.Statistics;
                        adblMinMaxForLabel[0, 0] = pStatResults.Minimum;
                        adblMinMaxForLabel[1, 0] = pStatResults.Maximum;
                        pCursor.Flush();

                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(255, 80, 80);
                        pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol);
                        if (intCnt == 1)
                        {
                            pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")");
                        }
                        else if (intCnt == 0)
                        {
                            pUniqueValueRenderer.set_Label("HH", "HH (no obs)");
                        }
                        else
                        {
                            pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")");
                        }


                        pQFilter.WhereClause = strFlgFldNam + " = 'LL'";
                        intCnt = pTable.RowCount(pQFilter);


                        pCursor                  = pTable.Search(pQFilter, true);
                        pDataStat                = new DataStatisticsClass();
                        pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                        pDataStat.Cursor         = pCursor;
                        pStatResults             = pDataStat.Statistics;
                        adblMinMaxForLabel[0, 1] = pStatResults.Minimum;
                        adblMinMaxForLabel[1, 1] = pStatResults.Maximum;
                        pCursor.Flush();

                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(50, 157, 194);
                        pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol);

                        if (intCnt == 1)
                        {
                            pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")");
                        }
                        else if (intCnt == 0)
                        {
                            pUniqueValueRenderer.set_Label("LL", "LL (no obs)");
                        }
                        else
                        {
                            pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")");
                        }


                        pQFilter.WhereClause = strFlgFldNam + " = 'HL'";
                        intCnt = pTable.RowCount(pQFilter);


                        pCursor                  = pTable.Search(pQFilter, true);
                        pDataStat                = new DataStatisticsClass();
                        pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                        pDataStat.Cursor         = pCursor;
                        pStatResults             = pDataStat.Statistics;
                        adblMinMaxForLabel[0, 2] = pStatResults.Minimum;
                        adblMinMaxForLabel[1, 2] = pStatResults.Maximum;
                        pCursor.Flush();

                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(244, 199, 0);
                        pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol);

                        if (intCnt == 1)
                        {
                            pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")");
                        }
                        else if (intCnt == 0)
                        {
                            pUniqueValueRenderer.set_Label("HL", "HL (no obs)");
                        }
                        else
                        {
                            pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")");
                        }


                        pQFilter.WhereClause = strFlgFldNam + " = 'LH'";
                        intCnt = pTable.RowCount(pQFilter);

                        pCursor                  = pTable.Search(pQFilter, true);
                        pDataStat                = new DataStatisticsClass();
                        pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                        pDataStat.Cursor         = pCursor;
                        pStatResults             = pDataStat.Statistics;
                        adblMinMaxForLabel[0, 3] = pStatResults.Minimum;
                        adblMinMaxForLabel[1, 3] = pStatResults.Maximum;
                        pCursor.Flush();

                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(173, 255, 179);
                        pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol);

                        if (intCnt == 1)
                        {
                            pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")");
                        }
                        else if (intCnt == 0)
                        {
                            pUniqueValueRenderer.set_Label("LH", "LH (no obs)");
                        }
                        else
                        {
                            pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")");
                        }



                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(200, 200, 200);
                        //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol);
                        //pUniqueValueRenderer.set_Label("", "Not significant");
                        pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol;
                        pUniqueValueRenderer.DefaultLabel  = "Not significant";

                        pUniqueValueRenderer.UseDefaultSymbol = true;

                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + pFLayer.Name;
                        IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                        pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                        m_pActiveView.FocusMap.AddLayer(pGFLayer);
                        m_pActiveView.Refresh();
                        m_pForm.axTOCControl1.Update();
                    }
                    else
                    {
                        MessageBox.Show("Complete. The results are stored in the shape file");
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #36
0
        private void button17_Click_1(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                MessageBox.Show("Please select a field firstly!");
            }
            else
            {
                listBox2.Items.Clear();

                ILayer layer  = axMapControl1.ActiveView.FocusMap.get_Layer(layerIndex);
                var    fields = layer as ILayerFields;

                IFeatureLayer pFeatureLayer = (IFeatureLayer)layer;
                IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                ITable        pTable        = (ITable)pFeatureClass;
                ICursor       pCursor       = pTable.Search(null, false);
                IRow          pRow          = pCursor.NextRow();
                int           fldIndex      = fields.FindField(listBox1.SelectedItem.ToString());

                List <string> uniqueVals = new List <string>();
                while (pRow != null)
                {
                    uniqueVals.Add(pRow.get_Value(fldIndex).ToString());
                    pRow = pCursor.NextRow();
                }
                uniqueVals = uniqueVals.Distinct().ToList();
                string[] sortedUniqueVals = uniqueVals.ToArray();
                System.Array.Sort(sortedUniqueVals);
                int[] intsrtdUniqueVals = new int[sortedUniqueVals.Count()];
                for (int i = 0; i < sortedUniqueVals.Count(); i++)
                {
                    int  n;
                    bool isNumeric = int.TryParse(sortedUniqueVals[i], out n);
                    if (isNumeric)
                    {
                        intsrtdUniqueVals[i] = int.Parse(sortedUniqueVals[i]);
                    }
                }
                System.Array.Sort(intsrtdUniqueVals);
                for (int i = 0; i < sortedUniqueVals.Count(); i++)
                {
                    int  n;
                    bool isNumeric = int.TryParse(sortedUniqueVals[i], out n);
                    if (isNumeric)
                    {
                        listBox2.Items.Add(intsrtdUniqueVals[i]);
                    }
                    else if (sortedUniqueVals[i] == "")
                    {
                        listBox2.Items.Add("NULL");
                    }
                    else
                    {
                        listBox2.Items.Add("'" + sortedUniqueVals[i] + "'");
                    }
                }
                textBox2.Enabled = true;
            }
            button17.Enabled = false;
        }
        private void miAddItem_Click(object sender, System.EventArgs e)
        {
            //可以双击该项来编辑属性
            //只为新项填充initDefaultValues方法中的默认值和自动生成的名称值。

            IMapControl3 mapControl = (IMapControl3)axMapControl1.Object;

            IEngineNAWindowCategory2 activeCategory = m_naWindow.ActiveCategory as IEngineNAWindowCategory2;
            IDataLayer pDataLayer = activeCategory.DataLayer;
            // 在类中创建一个新行并填充并初始默认值
            ITable       table       = pDataLayer as ITable;
            IRow         row         = table.CreateRow();
            IRowSubtypes rowSubtypes = row as IRowSubtypes;

            rowSubtypes.InitDefaultValues();
            // 自动生成显示名称
            IFeatureLayer    ipFeatureLayer    = activeCategory.Layer as IFeatureLayer;
            IStandaloneTable ipStandaloneTable = pDataLayer as IStandaloneTable;
            string           name = "";

            if (ipFeatureLayer != null)
            {
                name = ipFeatureLayer.DisplayField;
            }
            else if (ipStandaloneTable != null)
            {
                name = ipStandaloneTable.DisplayField;
            }
            //如果显示字段为空字符串或不代表NaClass上的实际字段,则跳过自动生成
            string currentName = "";
            int    fieldIndex  = row.Fields.FindField(name);

            if (fieldIndex >= 0)
            {
                currentName = row.get_Value(fieldIndex) as string;
                if (currentName.Length <= 0)
                {
                    row.set_Value(fieldIndex, "Item" + ++autogenInt);
                }
            }
            INAClassDefinition naClassDef = activeCategory.NAClass.ClassDefinition;

            if (naClassDef.Name == "OrderPairs")
            {
                fieldIndex = row.Fields.FindField("SecondOrderName");
                if (fieldIndex >= 0)
                {
                    string secondName = row.get_Value(fieldIndex) as string;
                    if (secondName.Length <= 0)
                    {
                        row.set_Value(fieldIndex, "Item" + ++autogenInt);
                    }
                }
            }
            row.Store();

            // 向naclass添加项
            INAContextEdit contextEdit = m_naEnv.NAWindow.ActiveAnalysis.Context as INAContextEdit;

            contextEdit.ContextChanged();

            // 刷新 NAWindow 和屏幕界面
            INALayer naLayer = m_naWindow.ActiveAnalysis;

            mapControl.Refresh(esriViewDrawPhase.esriViewGeography, naLayer, mapControl.Extent);
            m_naWindow.UpdateContent(m_naWindow.ActiveCategory);
        }
Example #38
0
        /// <summary>
        /// 双击节点,以定位到图层上的要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeview_Name_NodeDoubleClick(object sender, DevComponents.AdvTree.TreeNodeMouseEventArgs e)
        {
            AttributeShow_state.doubleclick = true;//确定这个操作是双击定位,不影响要素变更
            if (e.Node.Parent == null)
            {
                return;
            }
            else
            {
                layer_name = e.Node.Parent.Text;              //层名
                OID        = e.Node.Text;                     //OID

                int Count = myHook.MapControl.Map.LayerCount; //层的总数
                for (int n = 0; n < Count; n++)
                {
                    ILayer layer = myHook.MapControl.get_Layer(n);
                    if (layer is IGroupLayer)
                    {
                        if (layer.Name == "示意图")
                        {
                            continue;
                        }
                        #region 遍历组下面的普通层
                        ICompositeLayer pComLayer = layer as ICompositeLayer;
                        for (int j = 0; j < pComLayer.Count; j++)
                        {
                            ILayer mLayer = pComLayer.get_Layer(j);
                            if (mLayer.Name == layer_name)
                            {
                                IFeatureLayer     f_layer     = mLayer as IFeatureLayer;              //将层转成要素层
                                int               oid         = Convert.ToInt32(OID);                 //把OID转成整形
                                IFeature          feature     = f_layer.FeatureClass.GetFeature(oid); //得到对应的要素
                                IGeoDataset       pGeoDt      = f_layer.FeatureClass as IGeoDataset;
                                ISpatialReference pSpatialRef = null;
                                if (pGeoDt != null)
                                {
                                    pSpatialRef = pGeoDt.SpatialReference;
                                }

                                //myHook.MapControl.Map.ClearSelection();//清除已选择的要素
                                myHook.MapControl.Map.SelectFeature(mLayer, feature);
                                SysCommon.Gis.ModGisPub.ZoomToFeature(myHook.MapControl, feature, pSpatialRef);//定位到相应的层,中心放大
                                myHook.MapControl.ActiveView.Refresh();
                                Application.DoEvents();
                                myHook.MapControl.FlashShape(feature.Shape, 2, 500, null);
                                break;
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        if (layer.Name == layer_name)
                        {
                            IFeatureLayer f_layer = layer as IFeatureLayer;               //将层转成要素层
                            int           oid     = Convert.ToInt32(OID);                 //把OID转成整形
                            IFeature      feature = f_layer.FeatureClass.GetFeature(oid); //得到对应的要素
                            myHook.MapControl.Map.SelectFeature(layer, feature);

                            IGeoDataset       pGeoDt      = f_layer.FeatureClass as IGeoDataset;
                            ISpatialReference pSpatialRef = null;
                            if (pGeoDt != null)
                            {
                                pSpatialRef = pGeoDt.SpatialReference;
                            }

                            SysCommon.Gis.ModGisPub.ZoomToFeature(myHook.MapControl, feature, pSpatialRef);//定位到相应的层,中心放大
                            myHook.MapControl.ActiveView.Refresh();
                            Application.DoEvents();
                            myHook.MapControl.FlashShape(feature.Shape, 2, 500, null);
                            break;
                        }
                    }
                }
            }
        }
Example #39
0
        /*变量:
         * 1、图层
         * 2、距离
         * 3、单位
         * 4、保存路径
         */
        private void button1_Click(object sender, EventArgs e)
        {
            double bufferDistance, bufferDistance2, bufferDistance3;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            double.TryParse(txtBufferDistance2.Text, out bufferDistance2);
            double.TryParse(txtBufferDistance3.Text, out bufferDistance3);
            if (CNunit.SelectedIndex == 0)
            {
                DW = "Meters";
            }
            else if (CNunit.SelectedIndex == 1)
            {
                DW = "Kilometers";
            }
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("输入范围距离无效!");
                return;
            }
            if (CNunit.SelectedItem == null)
            {
                MessageBox.Show("请选择单位", "提示");
                return;
            }
            //判断输出路径是否合法
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出路径无效!");
                return;
            }
            IFeatureLayer layer = GetFeatureLayer((string)cboLayers.SelectedItem);

            if (null == layer)
            {
                MessageBox.Show("选中图层无效!");
                return;
            }
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            double[] dis      = { 0, bufferDistance, bufferDistance2, bufferDistance3 };
            double[] distance = { bufferDistance, bufferDistance2, bufferDistance3 };
            string[] level    = { "", "高级", "中级", "低级" };
            int      i        = 1;

            txtOutputPath.Text = System.IO.Path.Combine(SystemSet.Base_Map + "\\处理数据库\\实验数据", (level[i] + "_" + (string)cboLayers.SelectedItem + "_范围.shp"));
            int l1 = txtOutputPath.Text.LastIndexOf("\\");

            lab_message.Text = txtOutputPath.Text.Substring(l1 + 1) + "正在处理···";
            ESRI.ArcGIS.AnalysisTools.MultipleRingBuffer mulBuffer = new MultipleRingBuffer();
            mulBuffer.Input_Features        = layer;
            mulBuffer.Output_Feature_class  = txtOutputPath.Text;
            mulBuffer.Buffer_Unit           = "Meters";
            mulBuffer.Distances             = distance;//[bufferDistance, bufferDistance2, bufferDistance3];
            mulBuffer.Outside_Polygons_Only = "full";
            mulBuffer.Field_Name            = "分析半径";
            gp.Execute(mulBuffer, null);
            MessageBox.Show("成功");



            while (i < 4)
            {
                //修改当前指针样式
                this.Cursor = Cursors.WaitCursor;
                //调用缓冲去区处理工具buffer
                txtOutputPath.Text = System.IO.Path.Combine(SystemSet.Base_Map + "\\处理数据库\\实验数据", (level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp"));
                int l = txtOutputPath.Text.LastIndexOf("\\");
                lab_message.Text = txtOutputPath.Text.Substring(l + 1) + "正在处理···";
                ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(layer, txtOutputPath.Text, Convert.ToString(dis[i]) + " " + DW);//单级缓冲

                //gp.Execute(buffer, null);
                try
                {
                    IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);
                    if (results.Status != esriJobStatus.esriJobSucceeded)
                    {
                        MessageBox.Show("缓冲区失败的图层: " + layer.Name, "提示!");
                    }
                    this.Cursor = Cursors.Default;
                    MessageBox.Show(level[i] + "_" + layer.Name + "分析统计完成!", "提示!");
                    //将统计分析完成的图层添加到mapcontrol
                    IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();                                                                                                                                     //定义工作空间工厂接口
                    IWorkspace        pWorkSpace        = pWorkspaceFactory.OpenFromFile(txtOutputPath.Text.Substring(0, txtOutputPath.Text.Length - (level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp").Length), 0); //实例化工作空间
                    IFeatureWorkspace pFeatureWorkspace = pWorkSpace as IFeatureWorkspace;
                    IFeatureClass     pFeatureClass     = pFeatureWorkspace.OpenFeatureClass(level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp");                                                                      //
                    //以上得到的是featureclass。

                    IDataset      pDataset      = pFeatureClass as IDataset;
                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pFeatureClass;
                    pFeatureLayer.Name         = pDataset.Name;//图层名称
                    ILayer pLayer = pFeatureLayer as ILayer;

                    m_hookHelper.FocusMap.AddLayer(pLayer);
                    m_hookHelper.FocusMap.MoveLayer(pLayer, cboLayers.SelectedIndex + i);
                    i++;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.Cursor = Cursors.Default;
                    this.Close();
                    return;
                }
            }

            //GISHandler.GISTools.QueryByBuffer(m_hookHelper);
            this.Close();
            StasticResult SR = new StasticResult(this.mapContol);

            SR.Show();
            SR.StartPosition = FormStartPosition.CenterScreen;
            SR.TopMost       = true;

            //1、将结果图层添加到axmapcontrol中
            //2、多级缓冲 -->方法递归调用。/for循环三次  distance+=distance(图层叠加在一起  不好进行统计。)
            //3、将各级缓冲区中所叠置基图中的属性信息 自定义提取 装入 gridcontrol中。完成!
        }
Example #40
0
        /// <summary>
        /// 当单元格的值更改时,进行编辑修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DT_VIEW_Attriubte_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int count = myHook.MapControl.Map.LayerCount;

            for (int n = 0; n < count; n++)
            {
                ILayer layer = myHook.MapControl.Map.get_Layer(n);
                if (layer == null)
                {
                    continue;
                }
                //首先判别工程打开的数据是不是以组形式开展的
                if (layer is IGroupLayer)
                {
                    if (layer.Name == "示意图")
                    {
                        continue;
                    }
                    #region 遍历组下面的普通层
                    IWorkspace      space     = MoData.v_CurWorkspaceEdit as IWorkspace;//得到相应的操作空间
                    ICompositeLayer pComLayer = layer as ICompositeLayer;
                    for (int j = 0; j < pComLayer.Count; j++)
                    {
                        ILayer mLayer = pComLayer.get_Layer(j);
                        if (mLayer == null)
                        {
                            return;
                        }
                        IFeatureLayer layer_space   = mLayer as IFeatureLayer;              //得到要素层
                        IDataset      dataset_space = layer_space.FeatureClass as IDataset; //中转成一个要素集合

                        if (!space.Equals(dataset_space.Workspace))
                        {
                            SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "不在同一个操作空间下,不能编辑!");
                            return;//如果操作的空间不一样就进行下一个
                        }
                        //////////对SDE图层名称进行处理
                        string getname = string.Empty;
                        if (layer_space.DataSourceType == "SDE Feature Class")
                        {
                            getname = layer_name.Substring(layer_name.IndexOf('.') + 1);
                        }
                        else
                        {
                            getname = layer_name;
                        }

                        if (mLayer.Name == getname)
                        {
                            IFeatureLayer F_layer = mLayer as IFeatureLayer;//将图层转成要素层

                            try
                            {
                                MoData.v_CurWorkspaceEdit.StartEditOperation();                                                              //编辑操作开始
                                string temp  = DT_VIEW_Attriubte.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();                     //得到修改后的值
                                int    oid   = Convert.ToInt32(OID);                                                                         //得到要更新的OID
                                int    index = F_layer.FeatureClass.FindField(DT_VIEW_Attriubte.Rows[e.RowIndex].Cells[0].Value.ToString()); //得到所有的索引要素行
                                F_layer.FeatureClass.GetFeature(oid).set_Value(index, temp);                                                 //更新值
                                F_layer.FeatureClass.GetFeature(oid).Store();                                                                //更新到PDB里,存储
                                MoData.v_CurWorkspaceEdit.StopEditOperation();                                                               //结束编辑操作
                                UpdateHashTable(temp, e.ColumnIndex, e.RowIndex);
                            }
                            catch (Exception eError)
                            {
                                //******************************************
                                //guozheng added System Exception log
                                if (SysCommon.Log.Module.SysLog == null)
                                {
                                    SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                                }
                                SysCommon.Log.Module.SysLog.Write(eError);
                                //******************************************
                                Re_readValue();
                                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "您输入的内容类型不正确,请重新输入!");
                            }
                            //break;
                            return;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 如果不是组,直接遍历
                    if (layer.Name == layer_name)
                    {
                        IFeatureLayer F_layer = layer as IFeatureLayer;           //将图层转成要素层空间
                        IDataset      det     = F_layer.FeatureClass as IDataset; //转成数据集,用来得到编辑空间
                        try
                        {
                            MoData.v_CurWorkspaceEdit.StartEditOperation();                                         //编辑操作开始
                            string temp = DT_VIEW_Attriubte.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); //得到修改后的值
                            int    oid  = Convert.ToInt32(OID);                                                     //得到要更新的OID
                            F_layer.FeatureClass.GetFeature(oid).set_Value(e.RowIndex, temp);                       //更新值
                            F_layer.FeatureClass.GetFeature(oid).Store();                                           //更新到PDB里,存储
                            MoData.v_CurWorkspaceEdit.StopEditOperation();                                          //结束编辑操作
                            UpdateHashTable(temp, e.ColumnIndex, e.RowIndex);
                        }
                        catch (Exception eError)
                        {
                            //******************************************
                            //guozheng added System Exception log
                            if (SysCommon.Log.Module.SysLog == null)
                            {
                                SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                            }
                            SysCommon.Log.Module.SysLog.Write(eError);
                            //******************************************
                            Re_readValue();
                            SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "您输入的内容类型不正确,请重新输入!");
                        }
                        break;
                    }
                    #endregion
                }
            }
        }
Example #41
0
        public void Practice4Exercise()
        {
            IMxDocument pMxDoc;

            pMxDoc = (IMxDocument)ArcMap.Application.Document;

            IMap pMap;

            pMap = pMxDoc.FocusMap;

            ILayer        pLayer;
            IEnumLayer    pLayers;
            IFeatureLayer pStateLayer = null;
            IFeatureLayer pRoadLayer  = null;

            pLayers = pMap.Layers;
            pLayer  = pLayers.Next();

            while (pLayer != null)
            {
                if (pLayer.Name == "us_boundaries")
                {
                    pStateLayer = (IFeatureLayer)pLayer;
                }
                else if (pLayer.Name == "us_roads")
                {
                    pRoadLayer = (IFeatureLayer)pLayer;
                }
                pLayer = pLayers.Next();
            }

            IQueryFilter pQueryFilter;

            pQueryFilter             = new QueryFilter();
            pQueryFilter.WhereClause = "NAME = 'New York'";

            IFeatureClass pStateFClass;

            pStateFClass = pStateLayer.FeatureClass;

            IFeatureCursor pStateFCursor;

            pStateFCursor = pStateFClass.Search(pQueryFilter, true);

            IFeature pStateFeature;

            pStateFeature = pStateFCursor.NextFeature(); //** Moving to the NY feature

            IGeometry pGeom;

            pGeom = pStateFeature.Shape;   //** Getting the NY polygon geometry

            ISpatialFilter pSpatialFilter;

            pSpatialFilter = new SpatialFilterClass();

            pSpatialFilter.Geometry      = pGeom;                                       //** Setting equal to NY shape
            pSpatialFilter.GeometryField = "SHAPE";
            pSpatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects; //** Getting roads that intersect NY

            IFeatureSelection pFSel;

            pFSel = (IFeatureSelection)pRoadLayer;  //** QI
            pFSel.SelectFeatures(pSpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

            IActiveView pActiveView;

            pActiveView = (IActiveView)pMap;
            pActiveView.Refresh();
        }
        //从点图层中收集所有点
        public IPointCollection ReadPoint(IFeatureLayer pFeatureLayer)
        {
            IFeatureCursor pFeatureCursor = pFeatureLayer.Search(null, false);

            //获取数据库或者单个文件的第一个属性字段
            IFeature pFeature = pFeatureCursor.NextFeature();
            IField   pField   = null;

            if (pFeatureLayer.FeatureClass.Fields.FindField("FID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("FID"));
            }
            else if (pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID"));
            }

            //第一个属性字段名称
            string FirstFieldName = pField.AliasName;

            IQueryFilter pQueryFilter = new QueryFilterClass();

            pQueryFilter.WhereClause = FirstFieldName + ">=0";
            int number = pFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);

            //DataTable dt = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pFeatureLayer.FeatureClass as ITable, "");
            //DataAlignment.DataAlignment.CanlculateDistanceInMiddlePointTable(dt);

            IPointCollection pPointCollection = new MultipointClass();
            IPoint           PrevPT           = null;

            for (int i = 0; i < number; i++)
            {
                IGeometry pGeometry = pFeature.Shape as IGeometry;
                IPoint    pt        = pGeometry as IPoint;
                IPoint    pPoint    = new PointClass();

                IZAware zpt = pPoint as IZAware;
                zpt.ZAware = true;
                IMAware mpt = pPoint as IMAware;
                mpt.MAware = true;

                pPoint.PutCoords(pt.X, pt.Y);
                pPoint.Z = Convert.ToDouble(pFeature.Value[pFeature.Fields.FindField("Z_高程(米")]);

                if (i == 0)
                {
                    pPoint.M = 0;
                    PrevPT   = pPoint;
                }
                else
                {
                    pPoint.M = PrevPT.M + DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pPoint, PrevPT);

                    PrevPT = pPoint;
                }
                pPointCollection.AddPoint(pPoint);

                pFeature = pFeatureCursor.NextFeature();
            }

            return(pPointCollection);
        }
Example #43
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // 右键返回
            if (Button == 2)
            {
                return;
            }
            if (m_pDongshiFeatureLayer == null)
            {
                return;
            }
            m_pPoint = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            m_pPoint = GIS.GraphicEdit.SnapSetting.getSnapPoint(m_pPoint);

            double angle     = -1;
            string layerName = LayerNames.LAYER_ALIAS_MR_TUNNEL_FD;      //巷道

            pFeatLayer = drawSpecialCom.GetFeatureLayerByName(layerName);

            IFeature pFeature = null;

            TestExistPointFeature(m_hookHelper, m_pPoint, pFeatLayer, ref pFeature);
            if (pFeature == null)
            {
                MessageBox.Show(@"鼠标点击处没有巷道,请先选择一条巷道边线", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //IPoint hightPoint= Snapping(m_pPoint, pFeatLayer, pFeature);
            //if (hightPoint.IsEmpty)
            //{
            //    MessageBox.Show("获取巷道边界失败,请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            IProximityOperator proximityOperator = (IProximityOperator)pFeature.Shape;
            IPoint             mousePoint        = proximityOperator.ReturnNearestPoint(m_pPoint, esriSegmentExtension.esriNoExtension);

            IProximityOperator proximityOperator2 = (IProximityOperator)mousePoint;
            ISegmentCollection segmentCollection  = (ISegmentCollection)pFeature.Shape;

            for (int i = 0; i < segmentCollection.SegmentCount; i++)
            {
                ISegmentCollection geometryCollection = new PolylineClass();
                ISegment           segment            = segmentCollection.get_Segment(i);
                geometryCollection.AddSegment(segment);
                geometryCollection.SegmentsChanged();
                var distance = proximityOperator2.ReturnDistance((IGeometry)geometryCollection);

                if (distance < 0.0001)
                {
                    angle = ((ILine)segment).Angle;
                    break;
                }
            }
            if (angle == -1)
            {
                MessageBox.Show(@"获取巷道边界失败,请重新选择!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //得到相应的中线
            string hdid = pFeature.get_Value(pFeature.Fields.FindField(GIS_Const.FIELD_HDID)).ToString();
            string bid  = pFeature.get_Value(pFeature.Fields.FindField(GIS_Const.FIELD_BID)).ToString();

            FormCaveSizeInput frmCaveSize = new FormCaveSizeInput();

            frmCaveSize.ShowDialog();
            if (frmCaveSize.DialogResult == DialogResult.OK)
            {
                //输入正确,获得硐室的长和宽
                double Width  = frmCaveSize.CaveWidth;
                double Height = frmCaveSize.CaveHeight;

                PointClass p0 = RectanglePoint(mousePoint, angle, Width);
                PointClass p1 = RectanglePoint(mousePoint, angle + Math.PI, Width);
                PointClass p2 = RectanglePoint2(p0, angle + 90 * Math.PI / 180, Height);
                PointClass p3 = RectanglePoint2(p1, angle + 90 * Math.PI / 180, Height);
                //绘制硐室
                CreateDongShi(p0, p2, p3, p1, hdid, bid);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            QZ quanzhong;

            quanzhong.MD = 0;
            quanzhong.BL = 0;
            quanzhong.HB = 0;
            quanzhong.PD = 0;
            quanzhong.JL = 0;
            quanzhong.LS = 0;

            if (this.listView1.Items != null)
            {
                foreach (ListViewItem item in this.listView1.Items)
                {
                    if (item.SubItems[0].Text == "人口密度")
                    {
                        quanzhong.MD = Convert.ToDouble(item.SubItems[1].Text);
                    }
                    if (item.SubItems[0].Text == "居民地比例")
                    {
                        quanzhong.BL = Convert.ToDouble(item.SubItems[1].Text);
                    }
                    if (item.SubItems[0].Text == "平均海拔")
                    {
                        quanzhong.HB = Convert.ToDouble(item.SubItems[1].Text);
                    }
                    if (item.SubItems[0].Text == "平均坡度")
                    {
                        quanzhong.PD = Convert.ToDouble(item.SubItems[1].Text);
                    }
                    if (item.SubItems[0].Text == "与公路距离")
                    {
                        quanzhong.JL = Convert.ToDouble(item.SubItems[1].Text);
                    }
                    if (item.SubItems[0].Text == "坡向离散度")
                    {
                        quanzhong.LS = Convert.ToDouble(item.SubItems[1].Text);
                    }
                }
            }

            IFeatureLayer featureLayer = mapControl.get_Layer(17) as IFeatureLayer;
            string        n            = featureLayer.Name;
            IFeatureClass featureClass = featureLayer.FeatureClass;

            IQueryFilter   queryFilter   = new QueryFilterClass();
            IFeatureCursor featureCursor = featureClass.Update(queryFilter, true);

            int MDIndex    = featureCursor.FindField("人口密度");
            int BLIndex    = featureCursor.FindField("居民地比例");
            int HBIndex    = featureCursor.FindField("平均海拔");
            int PDIndex    = featureCursor.FindField("平均坡度");
            int JLIndex    = featureCursor.FindField("与公路距离");
            int LSIndex    = featureCursor.FindField("坡向离散度");
            int scoreIndex = featureCursor.FindField("总分值");



            IFeature feature = featureCursor.NextFeature();

            while (feature != null)
            {
                double MD_t = Convert.ToDouble(feature.get_Value(MDIndex));
                double BL_t = Convert.ToDouble(feature.get_Value(BLIndex));
                double HB_t = Convert.ToDouble(feature.get_Value(HBIndex));
                double PD_t = Convert.ToDouble(feature.get_Value(PDIndex));
                double JL_t = Convert.ToDouble(feature.get_Value(JLIndex));
                double LS_t = Convert.ToDouble(feature.get_Value(LSIndex));


                double totalScore = quanzhong.MD * MD_t + quanzhong.BL * BL_t + quanzhong.HB * HB_t + quanzhong.PD * PD_t + quanzhong.JL * JL_t + quanzhong.LS * LS_t;

                feature.set_Value(scoreIndex, totalScore);
                featureCursor.UpdateFeature(feature);
                feature = featureCursor.NextFeature();
                featureCursor.UpdateFeature(feature);
                feature = featureCursor.NextFeature();
            }
        }
Example #45
0
        // 公共方法
        void FeatureLayerVisualize(IConnectionInfo ci, bool needfly, string sourceName)
        {
            try
            {
                IDataSourceFactory dsFactory = new DataSourceFactory();
                IDataSource        ds        = dsFactory.OpenDataSource(ci);
                string[]           setnames  = (string[])ds.GetFeatureDatasetNames();
                if (setnames.Length == 0)
                {
                    return;
                }
                IFeatureDataSet dataset = ds.OpenFeatureDataset(setnames[0]);
                string[]        fcnames = (string[])dataset.GetNamesByType(gviDataSetType.gviDataSetFeatureClassTable);
                if (fcnames.Length == 0)
                {
                    return;
                }
                fcMap = new Hashtable(fcnames.Length);
                foreach (string name in fcnames)
                {
                    IFeatureClass fc = dataset.OpenFeatureClass(name);
                    _featureClass = fc;
                    // 找到空间列字段
                    List <string>        geoNames   = new List <string>();
                    IFieldInfoCollection fieldinfos = fc.GetFields();
                    for (int i = 0; i < fieldinfos.Count; i++)
                    {
                        IFieldInfo fieldinfo = fieldinfos.Get(i);
                        if (null == fieldinfo)
                        {
                            continue;
                        }
                        IGeometryDef geometryDef = fieldinfo.GeometryDef;
                        if (null == geometryDef)
                        {
                            continue;
                        }
                        geoNames.Add(fieldinfo.Name);
                    }
                    fcMap.Add(fc, geoNames);
                }
            }
            catch (COMException ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
                return;
            }

            // CreateFeautureLayer
            bool hasfly = !needfly;

            foreach (IFeatureClass fc in fcMap.Keys)
            {
                List <string> geoNames = (List <string>)fcMap[fc];
                foreach (string geoName in geoNames)
                {
                    IFeatureLayer featureLayer = this.axRenderControl1.ObjectManager.CreateFeatureLayer(
                        fc, geoName, null, null, rootId);

                    IFieldInfoCollection fieldinfos  = fc.GetFields();
                    IFieldInfo           fieldinfo   = fieldinfos.Get(fieldinfos.IndexOf(geoName));
                    IGeometryDef         geometryDef = fieldinfo.GeometryDef;
                    IEnvelope            env         = geometryDef.Envelope;
                    if (env == null || (env.MaxX == 0.0 && env.MaxY == 0.0 && env.MaxZ == 0.0 &&
                                        env.MinX == 0.0 && env.MinY == 0.0 && env.MinZ == 0.0))
                    {
                        continue;
                    }

                    // 相机飞入
                    if (!hasfly)
                    {
                        IEulerAngle angle = new EulerAngle();
                        angle.Set(0, -20, 0);
                        this.axRenderControl1.Camera.LookAt(env.Center, 1000, angle);
                    }
                    hasfly = true;
                }
            }
        }
Example #46
0
 public RenderFeatureLayer(Map map, IDatasetCachingContext datasetCachingContext, IFeatureLayer layer, ICancelTracker cancelTracker, FeatureCounter counter)
 {
     _map = map;
     _datasetCachingContext = datasetCachingContext;
     _isServiceMap          = map is IServiceMap;
     _layer           = layer;
     _cancelTracker   = ((cancelTracker == null) ? new CancelTracker() : cancelTracker);
     _counter         = counter;
     _counter.Counter = 0;
 }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (listViewEx.CheckedItems.Count == 0)
            {
                return;
            }

            LayerList = new List <ILayer>();
            for (int i = 0; i < Mapcontrol.Map.LayerCount; i++)
            {
                //IFeatureLayer featLay = Mapcontrol.Map.get_Layer(i) as IFeatureLayer;
                //changed by xisheng 20110828
                ILayer mLayer = Mapcontrol.Map.get_Layer(i);
                if (mLayer is IGroupLayer)
                {
                    ICompositeLayer pComLayer = mLayer as ICompositeLayer;
                    for (int j = 0; j < pComLayer.Count; j++)
                    {
                        IFeatureLayer featLay = pComLayer.get_Layer(j) as IFeatureLayer;

                        if (featLay == null)
                        {
                            continue;
                        }
                        if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH"))
                        {
                            continue;
                        }
                        LayerList.Add(featLay);
                    }
                }
                else
                {
                    IFeatureLayer featLay = Mapcontrol.Map.get_Layer(i) as IFeatureLayer;
                    if (featLay == null)
                    {
                        continue;
                    }
                    if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH"))
                    {
                        continue;
                    }
                    LayerList.Add(featLay);
                }
            }

            LstArcGisMapControl = new List <AxMapControl>();
            BarHistory.Items["dockItemHistoryData0"].Text    = listViewEx.CheckedItems[0].Text;
            BarHistory.Items["dockItemHistoryData0"].Tooltip = listViewEx.CheckedItems[0].Text;
            ESRI.ArcGIS.Controls.AxMapControl axMapControlHistoryData = (BarHistory.Items["dockItemHistoryData0"] as DockContainerItem).Control.Controls[0] as AxMapControl;
            LstArcGisMapControl.Add(axMapControlHistoryData);
            for (int i = LayerList.Count - 1; i >= 0; i--)
            {
                IFeatureLayer layTemp       = LayerList[i] as IFeatureLayer;
                IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                if (layTemp.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                {
                    pFeatureLayer = new FDOGraphicsLayerClass();
                }
                else
                {
                    (pFeatureLayer as IGeoFeatureLayer).Renderer = (layTemp as IGeoFeatureLayer).Renderer;
                }

                pFeatureLayer.FeatureClass = layTemp.FeatureClass;
                pFeatureLayer.Name         = (layTemp.FeatureClass as IDataset).Name;


                IFeatureLayerDefinition featLayDefRes = null;
                if (m_Sel)
                {
                    int fdIndex = layTemp.FeatureClass.Fields.FindField("SourceOID");
                    if (fdIndex == -1)
                    {
                        continue;
                    }
                    IFeatureLayerDefinition featLayDefTemp = layTemp as IFeatureLayerDefinition;
                    IEnumIDs      pEnumIDs = featLayDefTemp.DefinitionSelectionSet.IDs;
                    int           ID       = pEnumIDs.Next();
                    StringBuilder sb       = new StringBuilder();
                    while (ID != -1)
                    {
                        IFeature pFeat = layTemp.FeatureClass.GetFeature(ID);
                        if (sb.Length != 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append(pFeat.get_Value(fdIndex).ToString());
                        ID = pEnumIDs.Next();
                    }
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "SourceOID in (" + sb.ToString() + ")";
                    IFeatureSelection featSel = pFeatureLayer as IFeatureSelection;
                    featSel.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    featSel.SelectionChanged();

                    IFeatureLayerDefinition featLayDef       = pFeatureLayer as IFeatureLayerDefinition;
                    IFeatureLayer           selFeatLay       = featLayDef.CreateSelectionLayer(pFeatureLayer.Name, true, "", "");
                    IGeoFeatureLayer        pGeoFeatureLayer = layTemp as IGeoFeatureLayer;
                    if (pGeoFeatureLayer != null)
                    {
                        (selFeatLay as IGeoFeatureLayer).Renderer = pGeoFeatureLayer.Renderer;
                    }

                    axMapControlHistoryData.Map.AddLayer(selFeatLay);
                    featLayDefRes = selFeatLay as IFeatureLayerDefinition;
                }
                else
                {
                    axMapControlHistoryData.Map.AddLayer(pFeatureLayer);
                    featLayDefRes = pFeatureLayer as IFeatureLayerDefinition;
                }

                featLayDefRes.DefinitionExpression = "FromDate<='" + listViewEx.CheckedItems[0].Text + "' and ToDate>'" + listViewEx.CheckedItems[0].Text + "'";
            }
            axMapControlHistoryData.ActiveView.Extent = ArcGisMapControl.ActiveView.Extent;
            axMapControlHistoryData.ActiveView.Refresh();

            for (int i = 1; i < listViewEx.CheckedItems.Count; i++)
            {
                DockContainerItem dockItemHistoryData = new DockContainerItem("dockItemHistoryData" + i.ToString(), listViewEx.CheckedItems[i].Text);
                dockItemHistoryData.Tooltip = listViewEx.CheckedItems[i].Text;
                PanelDockContainer PanelTipHistoryData = new PanelDockContainer();

                dockItemHistoryData.Control = PanelTipHistoryData;
                BarHistory.Items.Add(dockItemHistoryData);
            }

            ArcGisMapControl.OnExtentUpdated += new IMapControlEvents2_Ax_OnExtentUpdatedEventHandler(ArcGisMapControl_OnExtentUpdated);
            ArcGisMapControl.OnViewRefreshed += new IMapControlEvents2_Ax_OnViewRefreshedEventHandler(ArcGisMapControl_OnViewRefreshed);

            this.Close();
        }
        private void BarHistory_DockTabChange(object sender, DockTabChangeEventArgs e)
        {
            DockContainerItem dockItemHistoryData = e.NewTab as DockContainerItem;

            if (dockItemHistoryData.Control.Controls.Count != 0)
            {
                return;
            }

            if (LayerList.Count == 0)
            {
                return;
            }
            frmArcgisMapControl newFrm = new frmArcgisMapControl();

            for (int j = LayerList.Count - 1; j >= 0; j--)
            {
                IFeatureLayer layTemp       = LayerList[j] as IFeatureLayer;
                IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                if (layTemp.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                {
                    pFeatureLayer = new FDOGraphicsLayerClass();
                }
                else
                {
                    (pFeatureLayer as IGeoFeatureLayer).Renderer = (layTemp as IGeoFeatureLayer).Renderer;
                }

                pFeatureLayer.FeatureClass = layTemp.FeatureClass;
                pFeatureLayer.Name         = (layTemp.FeatureClass as IDataset).Name;

                IFeatureLayerDefinition featLayDefRes = null;
                if (m_Sel)
                {
                    int fdIndex = layTemp.FeatureClass.Fields.FindField("SourceOID");
                    if (fdIndex == -1)
                    {
                        continue;
                    }
                    IFeatureLayerDefinition featLayDefTemp = layTemp as IFeatureLayerDefinition;
                    IEnumIDs      pEnumIDs = featLayDefTemp.DefinitionSelectionSet.IDs;
                    int           ID       = pEnumIDs.Next();
                    StringBuilder sb       = new StringBuilder();
                    while (ID != -1)
                    {
                        IFeature pFeat = layTemp.FeatureClass.GetFeature(ID);
                        if (sb.Length != 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append(pFeat.get_Value(fdIndex).ToString());
                        ID = pEnumIDs.Next();
                    }
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "SourceOID in (" + sb.ToString() + ")";
                    IFeatureSelection featSel = pFeatureLayer as IFeatureSelection;
                    featSel.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    featSel.SelectionChanged();

                    IFeatureLayerDefinition featLayDef       = pFeatureLayer as IFeatureLayerDefinition;
                    IFeatureLayer           selFeatLay       = featLayDef.CreateSelectionLayer(pFeatureLayer.Name, true, "", "");
                    IGeoFeatureLayer        pGeoFeatureLayer = layTemp as IGeoFeatureLayer;
                    if (pGeoFeatureLayer != null)
                    {
                        (selFeatLay as IGeoFeatureLayer).Renderer = pGeoFeatureLayer.Renderer;
                    }

                    newFrm.ArcGisMapControl.Map.AddLayer(selFeatLay);
                    featLayDefRes = selFeatLay as IFeatureLayerDefinition;
                }
                else
                {
                    newFrm.ArcGisMapControl.Map.AddLayer(pFeatureLayer);
                    featLayDefRes = pFeatureLayer as IFeatureLayerDefinition;
                }

                featLayDefRes.DefinitionExpression = "FromDate<='" + dockItemHistoryData.Text + "' and ToDate>'" + dockItemHistoryData.Text + "'";
            }
            newFrm.ArcGisMapControl.ActiveView.Extent = ArcGisMapControl.ActiveView.Extent;
            newFrm.ArcGisMapControl.Refresh();
            newFrm.ArcGisMapControl.Dock = DockStyle.Fill;
            dockItemHistoryData.Control.Controls.Add(newFrm.ArcGisMapControl);

            LstArcGisMapControl.Add(newFrm.ArcGisMapControl);
        }
Example #49
0
        private void AddRecord(IGeometry geo)
        {
            try
            {
                if (geo.GeometryType != gviGeometryType.gviGeometryModelPoint)
                {
                    return;
                }

                this.beforeRowBufferMap.Clear();
                SelectCollection.Instance().Clear();
                DF3DFeatureClass featureClassInfo = CommonUtils.Instance().CurEditLayer;
                if (featureClassInfo == null)
                {
                    return;
                }
                IFeatureClass fc = featureClassInfo.GetFeatureClass();
                if (fc == null)
                {
                    return;
                }
                IFeatureDataSet fds = fc.FeatureDataSet;
                if (fds == null)
                {
                    return;
                }
                IFeatureLayer fl = featureClassInfo.GetFeatureLayer();
                if (fl == null)
                {
                    return;
                }
                IFieldInfoCollection fields = fc.GetFields();
                int indexGeo = fields.IndexOf(fl.GeometryFieldName);
                if (indexGeo == -1)
                {
                    return;
                }
                IFieldInfo fiGeo = fields.Get(indexGeo);
                if (fiGeo == null || fiGeo.GeometryDef == null)
                {
                    return;
                }

                IModelPoint pt       = geo as IModelPoint;
                string      mname    = Path.GetFileNameWithoutExtension(pt.ModelName);
                IEnvelope   envelope = ImportOsg(fc, pt.ModelName);
                if (envelope == null)
                {
                    return;
                }
                IModelPoint geoOut = pt.Clone2(fiGeo.GeometryDef.VertexAttribute) as IModelPoint;
                if (fiGeo.GeometryDef.HasZ)
                {
                    geoOut.SetCoords(pt.X, pt.Y, pt.Z, 0, 0);
                }
                else
                {
                    geoOut.SetCoords(pt.X, pt.Y, 0, 0, 0);
                }
                geoOut.ModelName     = mname;
                geoOut.ModelEnvelope = new EnvelopeClass
                {
                    MinX = envelope.MinX,
                    MaxX = envelope.MaxX,
                    MinY = envelope.MinY,
                    MaxY = envelope.MaxY,
                    MinZ = envelope.MinZ,
                    MaxZ = envelope.MaxZ
                };

                IRowBufferCollection rowCol = new RowBufferCollection();
                IRowBufferFactory    fac    = new RowBufferFactory();
                IRowBuffer           row    = fac.CreateRowBuffer(fields);
                row.SetValue(indexGeo, geoOut);
                foreach (DataRow dr in this._dt.Rows)
                {
                    IFieldInfo fi = dr["F"] as IFieldInfo;
                    if (fi == null)
                    {
                        continue;
                    }
                    string fn    = fi.Name;
                    int    index = fields.IndexOf(fn);
                    if (index != -1)
                    {
                        if (dr["FV"] == null)
                        {
                            row.SetNull(index);
                        }
                        else
                        {
                            string strobj = dr["FV"].ToString();
                            bool   bRes   = false;
                            switch (fi.FieldType)
                            {
                            case gviFieldType.gviFieldBlob:
                            case gviFieldType.gviFieldGeometry:
                            case gviFieldType.gviFieldUnknown:
                                break;

                            case gviFieldType.gviFieldFloat:
                                float f;
                                bRes = float.TryParse(strobj, out f);
                                if (bRes)
                                {
                                    row.SetValue(index, f);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldDouble:
                                double d;
                                bRes = double.TryParse(strobj, out d);
                                if (bRes)
                                {
                                    row.SetValue(index, d);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldFID:
                            case gviFieldType.gviFieldUUID:
                            case gviFieldType.gviFieldInt16:
                                Int16 i16;
                                bRes = Int16.TryParse(strobj, out i16);
                                if (bRes)
                                {
                                    row.SetValue(index, i16);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldInt32:
                                Int32 i32;
                                bRes = Int32.TryParse(strobj, out i32);
                                if (bRes)
                                {
                                    row.SetValue(index, i32);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldInt64:
                                Int64 i64;
                                bRes = Int64.TryParse(strobj, out i64);
                                if (bRes)
                                {
                                    row.SetValue(index, i64);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;;

                            case gviFieldType.gviFieldString:
                                row.SetValue(index, strobj);
                                break;

                            case gviFieldType.gviFieldDate:
                                DateTime dt;
                                bRes = DateTime.TryParse(strobj, out dt);
                                if (bRes)
                                {
                                    row.SetValue(index, dt);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
                rowCol.Add(row);
                beforeRowBufferMap[featureClassInfo] = rowCol;
                UpdateDatabase();
                Clear();
                (this._drawTool as Draw3DModel).Set3DModelFilePath(this.beFilePath.Text);
            }
            catch (Exception ex)
            {
            }
        }
Example #50
0
        public void SelectionTest()
        {
            IMap map = new Map();

            // load layer with us states
            IMapLayer     ml = map.AddLayer(Path.Combine(@"Testfiles", "50mil_us_states.shp"));
            IFeatureLayer fl = ml as IFeatureLayer;

            Assert.IsNotNull(fl);

            // add two categories for testing category.SelectionEnabled
            PolygonScheme scheme = new PolygonScheme();

            scheme.ClearCategories();
            scheme.AddCategory(new PolygonCategory(Color.LightBlue, Color.DarkBlue, 1)
            {
                FilterExpression = "[FIPS] >= 10",
                LegendText       = ">= 10"
            });
            var cat = new PolygonCategory(Color.Pink, Color.DarkRed, 1)
            {
                FilterExpression = "[FIPS] < 10",
                LegendText       = "< 10"
            };

            scheme.AddCategory(cat);
            fl.Symbology = scheme;
            Assert.IsTrue(cat.SelectionEnabled, "Categories must be initialized with SelectionEnabled = true.");

            // load the second layer for testing the layers SelectionEnabled property
            IMapLayer ml2 = map.AddLayer(Path.Combine(@"Testfiles", "50m_admin_0_countries.shp"));

            ml2.SelectionEnabled = false;
            IFeatureLayer fl2 = ml2 as IFeatureLayer;

            Assert.IsNotNull(fl2);

            // select the first area
            Envelope e = new Envelope(-72, -66, 40, 48);

            Assert.IsTrue(map.Select(e, e));
            Assert.AreEqual(7, fl.Selection.Count, "Error selecting 50mil_us_states");
            Assert.AreEqual(0, fl2.Selection.Count, "Error selecting 50m_admin_0_countries");

            // invert a slighly larger area, ignoring the features of the second category
            cat.SelectionEnabled = false;
            Envelope e2 = new Envelope(-78, -66, 40, 48);

            Assert.IsTrue(map.InvertSelection(e2, e2));
            Assert.AreEqual(4, fl.Selection.Count, "Error inverting selection 50mil_us_states");
            Assert.AreEqual(0, fl2.Selection.Count, "Error inverting selection 50m_admin_0_countries");

            // add another area allowing the second layer to be selected too
            ml2.SelectionEnabled = true;
            Envelope e3 = new Envelope(-89, -77, 24, 33);

            Assert.IsTrue(map.Select(e3, e3));
            Assert.AreEqual(9, fl.Selection.Count, "Error adding to selection 50mil_us_states");
            Assert.AreEqual(2, fl2.Selection.Count, "Error adding to selection 50m_admin_0_countries");
            ml2.SelectionEnabled = false;

            // unselect the whole area ignoring the second layer and the deactivated category
            Envelope e4 = new Envelope(-89, -66, 24, 48);

            Assert.IsTrue(map.UnSelect(e4, e4));
            Assert.AreEqual(1, fl.Selection.Count, "Error unselecting 50mil_us_states");
            Assert.AreEqual(2, fl2.Selection.Count, "Error unselecting 50m_admin_0_countries");
        }
Example #51
0
        async public Task Render()
        {
            if (_layer == null || _map == null)
            {
                return;
            }

            #region JSON FilterCollection

            if (_layer.FilterQuery != null && !String.IsNullOrEmpty(_layer.FilterQuery.JsonWhereClause))
            {
                try
                {
                    DisplayFilterCollection dfc = DisplayFilterCollection.FromJSON(_layer.FilterQuery.JsonWhereClause);
                    if (dfc == null)
                    {
                        return;
                    }

                    IFeatureLayer flayer = (IFeatureLayer)LayerFactory.Create(_layer.Class, _layer);
                    flayer.FilterQuery = (IQueryFilter)_layer.FilterQuery.Clone();
                    foreach (DisplayFilter df in dfc)
                    {
                        // immer neu klonen (wegen PenWidth...)!!
                        flayer.FeatureRenderer = _layer.FeatureRenderer != null ? (IFeatureRenderer)_layer.FeatureRenderer.Clone() : null;

                        flayer.FilterQuery.WhereClause = df.Filter;
                        if (flayer.FeatureRenderer != null)
                        {
                            foreach (ISymbol symbol in flayer.FeatureRenderer.Symbols)
                            {
                                if (df.Color.A > 0)
                                {
                                    if (symbol is IPenColor)
                                    {
                                        ((IPenColor)symbol).PenColor = df.Color;
                                    }

                                    if (symbol is IBrushColor)
                                    {
                                        ((IBrushColor)symbol).FillColor = df.Color;
                                    }

                                    if (symbol is IFontColor)
                                    {
                                        ((IFontColor)symbol).FontColor = df.Color;
                                    }
                                }
                                if (df.PenWidth > 0f && symbol is IPenWidth)
                                {
                                    ((IPenWidth)symbol).PenWidth = df.PenWidth;
                                }
                            }
                        }
                        await Render(flayer);
                    }
                }
                catch { }
                return;
            }

            #endregion

            await Render(_layer);
        }
Example #52
0
        /// <summary>
        /// 空值检查
        /// </summary>
        /// <param name="pMapControl"></param>
        /// <param name="cbxLayerName"></param>
        /// <param name="dgv"></param>
        public static void CheckCode(IMap pMapControl, ComboBoxEx cbxLayerName, DataGridViewX dgv)
        {
            int j = 0;

            DataGridViewX dataView = dgv;

            dataView.Rows.Clear();
            dataView.ColumnHeadersDefaultCellStyle.ForeColor = System.Drawing.Color.Black;
            dataView.ColumnHeadersDefaultCellStyle.BackColor = System.Drawing.Color.White;
            dataView.ColumnHeadersDefaultCellStyle.Font      = new System.Drawing.Font(dataView.Font, System.Drawing.FontStyle.Bold);
            dataView.AutoSizeRowsMode         = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
            dataView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Sunken;
            dataView.GridColor                   = System.Drawing.Color.Black;
            dataView.RowHeadersVisible           = false;
            dataView.ColumnCount                 = 3;
            dataView.SelectionMode               = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            dataView.MultiSelect                 = false;
            dataView.AllowUserToAddRows          = false;
            dataView.ReadOnly                    = true;
            dataView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataView.Columns[0].Name             = "LayerName";
            dataView.Columns[0].HeaderText       = "图层名称";

            dataView.Columns[1].Name       = "YesOrNo";
            dataView.Columns[1].HeaderText = "是否有FCODE";

            dataView.Columns[2].Name       = "LayerGroup";
            dataView.Columns[2].HeaderText = "所在图层组";

            string fcodeField = "FCODE";
            ILayer pLayer     = GetLayerByName(pMapControl, cbxLayerName.Text);

            if (pLayer is IGroupLayer)
            {
                string          GroupLayer      = pLayer.Name;
                ICompositeLayer pCompositeLayer = pLayer as ICompositeLayer;
                for (int k = 0; k < pCompositeLayer.Count; k++)
                {
                    if (pCompositeLayer.get_Layer(k) is IFeatureLayer)
                    {
                        j = dataView.Rows.Add();
                        dataView["LayerGroup", j].Value = GroupLayer;
                        dataView["LayerName", j].Value  = pMapControl.get_Layer(k).Name;
                        IFeatureLayer pFeatureLayer = pCompositeLayer.get_Layer(k) as IFeatureLayer;
                        IClass        pTable        = pFeatureLayer.FeatureClass as IClass;
                        if (pTable.Fields.FindField(fcodeField) == -1)
                        {
                            dataView["YesOrNo", j].Value     = "否";
                            dataView.Columns[0].Width        = dataView.Width / 3;
                            dataView.Columns[1].Width        = dataView.Width / 3;
                            dataView.Columns[2].AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
                        }
                        else
                        {
                            dataView["YesOrNo", j].Value = "是";
                            NullCheck(pMapControl, dataView, pLayer);
                        }
                    }
                }
            }
            else
            {
                if (pLayer is IFeatureLayer)
                {
                    j = dataView.Rows.Add();
                    dataView["LayerGroup", j].Value = "NULL";
                    dataView["LayerName", j].Value  = cbxLayerName.Text;
                    IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                    IClass        pTable        = pFeatureLayer.FeatureClass as IClass;
                    if (pTable.Fields.FindField(fcodeField) == -1)
                    {
                        dataView["YesOrNo", j].Value     = "否";
                        dataView.Columns[0].Width        = dataView.Width / 3;
                        dataView.Columns[1].Width        = dataView.Width / 3;
                        dataView.Columns[2].AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
                    }
                    else
                    {
                        dataView["YesOrNo", j].Value = "是";
                        NullCheck(pMapControl, dataView, pLayer);
                    }
                }
            }
        }
Example #53
0
        /// <summary>
        /// Attempts to create a new PointLayer using the specified file.  If the filetype is not
        /// does not generate a point layer, an exception will be thrown.
        /// </summary>
        /// <param name="fileName">A string fileName to create a point layer for.</param>
        /// <returns>A PointLayer created from the specified fileName.</returns>
        public static new IPointLayer OpenFile(string fileName)
        {
            IFeatureLayer fl = LayerManager.DefaultLayerManager.OpenVectorLayer(fileName);

            return(fl as PointLayer);
        }
Example #54
0
        private void button1_Click(object sender, EventArgs e)
        {
            /////////////
            if (axMapControl1.LayerCount == 0)
            {
                MessageBox.Show("请加载图层");
                return;
            }
            /////////////  图层combobox
            //string str = toolStripComboBox1.Items[toolStripComboBox1.SelectedIndex].ToString();
            if (toolStripComboBox1.SelectedIndex == -1)
            {
                this.initToolStripComboBox(toolStripComboBox1);
            }
            else
            {
                this.initToolStripComboBox(toolStripComboBox1);
            }

            {
                DataTable     dt           = new DataTable();
                IFeatureLayer getLayer     = axMapControl1.get_Layer(toolStripComboBox1.SelectedIndex) as IFeatureLayer;
                IFeatureClass featureclass = getLayer.FeatureClass;
                IQueryFilter  queryFilter  = new QueryFilter();
                if (textBox1.Text == "")
                {
                    MessageBox.Show("请输入");
                }
                else
                {
                    string filter = comboBox1.Items[comboBox1.SelectedIndex].ToString() + "=" + "'" + textBox1.Text + "'";
                    Console.WriteLine(filter);
                    IQueryFilter Filter = new QueryFilter();
                    Filter.WhereClause = filter;
                    IFeatureCursor featurecursor = getLayer.Search(Filter, false);
                    IFields        fields        = featurecursor.Fields;
                    for (int i = 0; i < fields.FieldCount; i++)
                    {
                        IField     field = fields.Field[i];
                        string     name  = field.Name;
                        DataColumn dc    = new DataColumn(name, typeof(String));
                        dt.Columns.Add(dc);
                    }
                    IFeature feature = null;
                    while ((feature = featurecursor.NextFeature()) != null)
                    {
                        object[] objs   = new object[fields.FieldCount];
                        ITable   t      = feature.Table;
                        ICursor  Cursor = t.Search(Filter, false);
                        IRow     row    = null;
                        while ((row = Cursor.NextRow()) != null)
                        {
                            for (int i = 0; i < fields.FieldCount; i++)
                            {
                                objs[i] = row.Value[i];
                            }
                        }
                        dt.Rows.Add(objs);
                    }
                    dataGridView1.DataSource = dt;
                }
            }
        }
        private void AddTemplate(YTEditTemplate template)
        {
            List <YTEditTemplate> list;
            ListViewGroup         group;
            ListViewItem          item;
            string        str;
            IFeatureLayer featureLayer = template.FeatureLayer;

            if (!m_list.ContainsKey(featureLayer))
            {
                list = new List <YTEditTemplate>();
                m_list.Add(featureLayer, list);
            }
            else
            {
                list = m_list[featureLayer];
            }
            list.Add(template);
            if (this.m_GroupType != GroupType.GroupByLayer)
            {
                if (this.m_GroupType != GroupType.GroupByGeometryType)
                {
                    if (this.IsAdd(featureLayer))
                    {
                        item = new ListViewItem
                        {
                            Text = template.Name,
                            Tag  = template
                        };
                        this.listView1.AddItem(item);
                    }
                    return;
                }
                esriGeometryType shapeType   = template.FeatureLayer.FeatureClass.ShapeType;
                esriFeatureType  featureType = template.FeatureLayer.FeatureClass.FeatureType;
                str = "";
                if (featureType == esriFeatureType.esriFTAnnotation)
                {
                    str = "注记";
                }
                else
                {
                    switch (shapeType)
                    {
                    case esriGeometryType.esriGeometryPolyline:
                        str = "线";
                        break;

                    case esriGeometryType.esriGeometryPolygon:
                        str = "面";
                        break;

                    case esriGeometryType.esriGeometryPoint:
                    case esriGeometryType.esriGeometryMultipoint:
                        str = "点";
                        break;
                    }
                }
                group = null;
                foreach (ListViewGroup group2 in this.listView1.Groups)
                {
                    if (group2.Name == str)
                    {
                        group = group2;
                        break;
                    }
                }
            }
            else
            {
                group = null;
                foreach (ListViewGroup group2 in this.listView1.Groups)
                {
                    if (group2.Tag == featureLayer)
                    {
                        group = group2;
                        break;
                    }
                }
                if ((group == null) && this.IsAdd(featureLayer))
                {
                    group = new ListViewGroup
                    {
                        Tag    = featureLayer,
                        Name   = featureLayer.Name,
                        Header = featureLayer.Name
                    };
                    this.listView1.Groups.Add(group);
                }
                if (group != null)
                {
                    item = new ListViewItem
                    {
                        Text  = template.Name,
                        Tag   = template,
                        Group = group
                    };
                    this.listView1.AddItem(item);
                }
                return;
            }
            if ((group == null) && this.IsAdd(featureLayer))
            {
                group = new ListViewGroup
                {
                    Name   = str,
                    Header = str
                };
                this.listView1.Groups.Add(group);
            }
            if (group != null)
            {
                item = new ListViewItem
                {
                    Text  = template.Name,
                    Tag   = template,
                    Group = group
                };
                this.listView1.AddItem(item);
            }
        }
Example #56
0
        private void button1_Click(object sender, EventArgs e)
        {
            IMapDocument mxd = ZoomNextError.ArcMap.Application.Document as IMapDocument;
            IMap         map = mxd.get_Map(0);
            string       gdb = AO.getLayerPathFromMxd(map, "חלקות לעריכה");



            if (String.IsNullOrEmpty(gdb))
            {
                MessageBox.Show("שכבת חלקות לעריכה אינה קיימת במפה");
            }
            if (String.IsNullOrEmpty(gdb))
            {
                MessageBox.Show("שכבת חלקות לעריכה אינה קיימת במפה");
            }
            else
            {
                ITable table     = AO.open_table(gdb, "Errors");
                int    sum_items = table.RowCount(null);
                if (table != null)
                {
                    counter_items++;
                    int     counter = 0;
                    ICursor cursor  = AO.create_table_cursor_with_query(table, "\"OBJECTID\" > " + current_OID.ToString());
                    IRow    row     = cursor.NextRow();
                    while (counter < 1 && row != null)
                    {
                        if (counter_items < sum_items)
                        {
                            counter++;
                            current_OID = row.OID;
                            //MessageBox.Show(current_OID.ToString());
                            string GushNum        = row.Value[row.Fields.FindField("GushNum")];
                            string ParcelNum      = row.Value[row.Fields.FindField("ParcelNum")];
                            string GushSfx        = row.Value[row.Fields.FindField("GushSfx")];
                            object ErrDescription = row.Value[row.Fields.FindField("ErrDescription")];

                            string query = "OBJECTID < 0";
                            if (GushNum == "0" && ParcelNum == "0" && ErrDescription != null)
                            {
                                if (ErrDescription.ToString().Contains("OID:"))
                                {
                                    //MessageBox.Show(System.Text.RegularExpressions.Regex.Match(ErrDescription.ToString(), @"\d+").Value);
                                    string oid = System.Text.RegularExpressions.Regex.Match(ErrDescription.ToString(), @"\d+").Value;
                                    query = "OBJECTID = " + oid;
                                }
                            }
                            else
                            {
                                query = "GUSH_NUM = " + GushNum +
                                        " AND PARCEL = " + ParcelNum +
                                        " AND GUSH_SUFFIX = " + GushSfx;
                            }


                            IFeatureLayer flayer = AO.getLayerFromMxd(map, "חלקות לעריכה");

                            AO.ZoomToSelection(mxd, flayer, query);
                            List_acc.Add(row.OID);
                            //MessageBox.Show(get(List_acc));
                            row = cursor.NextRow();

                            if (ErrDescription != null)
                            {
                                label3.Text = ErrDescription.ToString();
                                label5.Text = sum_items.ToString() + " / " + List_acc.Count.ToString();
                            }
                            else
                            {
                                label3.Text = "ללא תיאור";
                                label5.Text = "";
                            }
                        }
                        else
                        {
                            current_OID   = -1;
                            counter_items = 0;
                        }
                    }
                }
            }
        }
Example #57
0
        async private Task Render(IFeatureLayer layer)
        {
            IFeatureRenderer clonedFeatureRenderer = null;
            ILabelRenderer   clonedLabelRenderer   = null;

            GraphicsEngine.Abstraction.IBitmap compositionModeCopyBitmap = null;
            GraphicsEngine.Abstraction.ICanvas compositionModeCopyCanvas = null, originalCanvas = null;

            try
            {
                _map.FireOnUserInterface(true);
                if ((
                        layer.FeatureRenderer == null ||
                        layer.FeatureRenderer.HasEffect(layer, _map) == false)
                    &&
                    (
                        layer.LabelRenderer == null ||
                        _useLabelRenderer == false
                    ))
                {
                    return;
                }

                IFeatureClass fClass = layer.FeatureClass;
                if (fClass == null)
                {
                    return;
                }

                //IDataset dataset = (IDataset)_map[layer];
                //if (dataset == null) return;

                //if (!(dataset is IFeatureDataset)) return;

                IGeometry filterGeom = _map.Display.DisplayTransformation.TransformedBounds(_map.Display); //_map.Display.Envelope;

                if (_map.Display.GeometricTransformer != null)
                {
                    filterGeom = MapHelper.Project(fClass, _map.Display);
                }

                gView.Framework.Data.SpatialFilter filter = new gView.Framework.Data.SpatialFilter();
                filter.DatasetCachingContext = _datasetCachingContext;
                filter.Geometry = filterGeom;
                filter.AddField(fClass.ShapeFieldName);
                //filter.FuzzyQuery = true;
                filter.SpatialRelation = spatialRelation.SpatialRelationMapEnvelopeIntersects;
                filter.MapScale        = _map.Display.mapScale;
                filter.CancelTracker   = _cancelTracker;

                if (layer.FilterQuery != null)
                {
                    filter.WhereClause = layer.FilterQuery.WhereClause;
                    if (layer.FilterQuery is IBufferQueryFilter)
                    {
                        ISpatialFilter sFilter = await BufferQueryFilter.ConvertToSpatialFilter(layer.FilterQuery as IBufferQueryFilter);

                        if (sFilter == null)
                        {
                            return;
                        }
                        filter.SpatialRelation = spatialRelation.SpatialRelationIntersects;
                        filter.Geometry        = sFilter.Geometry;
                    }
                    if (layer.FilterQuery is ISpatialFilter)
                    {
                        //filter.FuzzyQuery = ((ISpatialFilter)layer.FilterQuery).FuzzyQuery;
                        filter.SpatialRelation = ((ISpatialFilter)layer.FilterQuery).SpatialRelation;
                        filter.Geometry        = ((ISpatialFilter)layer.FilterQuery).Geometry;
                    }
                }

                // Erst nach dem Clonen anwenden!!!
                //if (layer.FeatureRenderer != null && layer.FeatureRenderer.HasEffect(layer, _map))
                //{
                //    layer.FeatureRenderer.PrepareQueryFilter(layer, filter);
                //}
                //if (layer.LabelRenderer != null && _useLabelRenderer)
                //{
                //    layer.LabelRenderer.PrepareQueryFilter(_map.Display, layer, filter);
                //}

                IDisplay display  = _map;
                double   refScale = display.refScale;

                #region Layer Clonen

                IFeatureRenderer renderer      = null;
                ILabelRenderer   labelRenderer = null;

                lock (lockThis)
                {
                    // Beim Clonen sprerren...
                    // Da sonst bei der Servicemap bei gleichzeitigen Requests
                    // Exception "Objekt wird bereits an anderer Stelle verwendet" auftreten kann!
                    if (layer.FeatureRenderer != null && layer.FeatureRenderer.HasEffect(layer, _map))
                    {
                        if (layer.RequiresFeatureRendererClone(display))
                        {
                            renderer = clonedFeatureRenderer = (IFeatureRenderer)layer.FeatureRenderer.Clone(
                                new CloneOptions(display,
                                                 layer.UseWithRefScale(display),
                                                 maxRefScaleFactor: layer.MaxRefScaleFactor));
                        }
                        else
                        {
                            renderer = layer.FeatureRenderer;
                        }
                    }
                    if (layer.LabelRenderer != null && _useLabelRenderer)
                    {
                        if (layer.RequiresLabelRendererClone(display))
                        {
                            labelRenderer = clonedLabelRenderer =
                                (ILabelRenderer)layer.LabelRenderer.Clone(new CloneOptions(display,
                                                                                           layer.UseLabelsWithRefScale(display),
                                                                                           maxLabelRefscaleFactor: layer.MaxLabelRefScaleFactor));
                        }
                        else  // Clone with null => simple clone
                        {
                            //display.refScale = 0;
                            labelRenderer = clonedLabelRenderer = (ILabelRenderer)layer.LabelRenderer.Clone(null);
                            //display.refScale = refScale;
                        }
                    }
                }

                #endregion

                #region Prepare filter

                // Prepare erst auf geclonte renderer anwenden!! (Threadsafe)
                if (renderer != null && renderer.HasEffect(layer, _map))
                {
                    renderer.PrepareQueryFilter(layer, filter);
                }
                if (labelRenderer != null && _useLabelRenderer)
                {
                    labelRenderer.PrepareQueryFilter(_map.Display, layer, filter);
                }

                #endregion

                using (IFeatureCursor fCursor = await fClass.GetFeatures(MapHelper.MapQueryFilter(filter)))
                {
                    _map.FireOnUserInterface(false);

                    if (fCursor != null)
                    {
                        IFeature feature;

                        if (renderer != null)
                        {
                            renderer.StartDrawing(_map);

                            bool useCompostionModeCopy = layer is IFeatureLayerComposition &&
                                                         ((IFeatureLayerComposition)layer).CompositionMode == FeatureLayerCompositionMode.Copy;

                            if (useCompostionModeCopy)
                            {
                                originalCanvas            = _map.Display.Canvas;
                                compositionModeCopyBitmap = GraphicsEngine.Current.Engine.CreateBitmap(_map.Display.Bitmap.Width, _map.Display.Bitmap.Height, GraphicsEngine.PixelFormat.Rgba32);
                                compositionModeCopyCanvas = compositionModeCopyBitmap.CreateCanvas();

                                compositionModeCopyBitmap.MakeTransparent();
                                compositionModeCopyBitmap.SetResolution(_map.Display.Bitmap.DpiX,
                                                                        _map.Display.Bitmap.DpiY);

                                ((Display)_map.Display).Canvas = compositionModeCopyCanvas;
                            }

                            while ((feature = await fCursor.NextFeature()) != null)
                            {
                                if (_cancelTracker != null)
                                {
                                    if (!_cancelTracker.Continue)
                                    {
                                        break;
                                    }
                                }

                                renderer.Draw(_map, feature);

                                if (labelRenderer != null)
                                {
                                    labelRenderer.Draw(_map, feature);
                                }

                                _counter.Counter++;

                                if (_isServiceMap == false)
                                {
                                    if (_counter.Counter % 100 == 0)
                                    {
                                        _map.FireRefreshMapView();
                                    }
                                }
                            }
                        }
                        else if (labelRenderer != null && _cancelTracker.Continue)
                        {
                            while ((feature = await fCursor.NextFeature()) != null)
                            {
                                if (_cancelTracker != null)
                                {
                                    if (!_cancelTracker.Continue)
                                    {
                                        break;
                                    }
                                }

                                labelRenderer.Draw(_map, feature);
                                _counter.Counter++;
                            }
                        }

                        if (labelRenderer != null)
                        {
                            labelRenderer.Release();
                        }

                        if (renderer != null)
                        {
                            renderer.FinishDrawing(_map, _cancelTracker);
                        }

                        if (compositionModeCopyCanvas != null && compositionModeCopyBitmap != null)
                        {
                            originalCanvas.DrawBitmap(compositionModeCopyBitmap,
                                                      new GraphicsEngine.CanvasRectangle(0, 0, compositionModeCopyBitmap.Width, compositionModeCopyBitmap.Height),
                                                      new GraphicsEngine.CanvasRectangle(0, 0, compositionModeCopyBitmap.Width, compositionModeCopyBitmap.Height),
                                                      opacity: (float)Math.Min(1, (100f - ((IFeatureLayerComposition)layer).CompositionModeCopyTransparency) / 100));
                        }
                    }
                    else
                    {
                        if (fClass is IDebugging && ((IDebugging)fClass).LastException != null)
                        {
                            throw ((IDebugging)fClass).LastException;
                        }

                        throw new Exception("Can't query feature class. Unknown error");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_map is IServiceMap && ((IServiceMap)_map).MapServer != null)
                {
                    await((IServiceMap)_map).MapServer.LogAsync(
                        ((IServiceMap)_map).Name,
                        "RenderFeatureLayer: " + ((layer != null) ? layer.Title : String.Empty),
                        loggingMethod.error,
                        ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
                }
                if (_map != null)
                {
                    _map.AddRequestException(new Exception("RenderFeatureLayerThread: " + ((layer != null) ? layer.Title : String.Empty) + "\n" + ex.Message, ex));
                }
            }
            finally
            {
                if (clonedFeatureRenderer != null)
                {
                    clonedFeatureRenderer.Release();
                }

                if (clonedLabelRenderer != null)
                {
                    clonedLabelRenderer.Release();
                }

                if (originalCanvas != null)
                {
                    ((Display)_map.Display).Canvas = originalCanvas;
                }

                if (compositionModeCopyCanvas != null)
                {
                    compositionModeCopyCanvas.Dispose();
                    compositionModeCopyCanvas = null;
                }

                if (compositionModeCopyBitmap != null)
                {
                    compositionModeCopyBitmap.Dispose();
                    compositionModeCopyBitmap = null;
                }

                _map.FireOnUserInterface(false);
            }
        }
Example #58
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            //Choropleth mapping : Exactly same with the function in frmChoroplethwithOverlay HK102915
            string strLayerName = cboSourceLayer.Text;

            if (cboSourceLayer.Text == "" || cboValueField.Text == "" || cboUField.Text == "")
            {
                MessageBox.Show("Assign proper layer and field");
                return;
            }

            int    intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName);
            ILayer pLayer    = mForm.axMapControl1.get_Layer(intLIndex);

            IFeatureLayer pFLayer = pLayer as IFeatureLayer;
            IFeatureClass pFClass = pFLayer.FeatureClass;

            //Create Rendering of Mean Value at Target Layer
            int    intGCBreakeCount = Convert.ToInt32(nudGCNClasses.Value);
            string strGCRenderField = cboValueField.Text;

            IGeoFeatureLayer pGeofeatureLayer;

            pGeofeatureLayer = (IGeoFeatureLayer)pFLayer;

            ITable       pTable = (ITable)pFClass;
            IClassifyGEN pClassifyGEN;

            switch (cboGCClassify.Text)
            {
            case "Equal Interval":
                pClassifyGEN = new EqualIntervalClass();
                break;

            case "Geometrical Interval":
                pClassifyGEN = new GeometricalInterval();
                break;

            case "Natural Breaks":
                pClassifyGEN = new NaturalBreaksClass();
                break;

            case "Quantile":
                pClassifyGEN = new QuantileClass();
                break;

            case "StandardDeviation":
                pClassifyGEN = new StandardDeviationClass();
                break;

            default:
                pClassifyGEN = new NaturalBreaksClass();
                break;
            }

            //Need to be changed 1/29/15
            ITableHistogram pTableHistogram = new TableHistogramClass();

            pTableHistogram.Field = strGCRenderField;
            pTableHistogram.Table = pTable;
            IHistogram pHistogram = (IHistogram)pTableHistogram;

            object xVals, frqs;

            pHistogram.GetHistogram(out xVals, out frqs);
            pClassifyGEN.Classify(xVals, frqs, intGCBreakeCount);

            ClassBreaksRenderer pRender = new ClassBreaksRenderer();

            double[] cb = (double[])pClassifyGEN.ClassBreaks;
            pRender.Field        = strGCRenderField;
            pRender.BreakCount   = intGCBreakeCount;
            pRender.MinimumBreak = cb[0];

            //' create our color ramp
            IAlgorithmicColorRamp pColorRamp = new AlgorithmicColorRampClass();

            pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
            IRgbColor pColor1 = new RgbColor();
            IRgbColor pColor2 = new RgbColor();

            //Can Change the color in here!
            pColor1.Red   = picSymolfrom.BackColor.R;
            pColor1.Green = picSymolfrom.BackColor.G;
            pColor1.Blue  = picSymolfrom.BackColor.B;

            Boolean blnOK = true;

            pColor2.Red          = picSymbolTo.BackColor.R;
            pColor2.Green        = picSymbolTo.BackColor.G;
            pColor2.Blue         = picSymbolTo.BackColor.B;
            pColorRamp.FromColor = pColor1;
            pColorRamp.ToColor   = pColor2;
            pColorRamp.Size      = intGCBreakeCount;
            pColorRamp.CreateRamp(out blnOK);

            IEnumColors pEnumColors = pColorRamp.Colors;

            pEnumColors.Reset();

            IRgbColor pColorOutline = new RgbColor();

            //Can Change the color in here!
            pColorOutline.Red   = picGCLineColor.BackColor.R;
            pColorOutline.Green = picGCLineColor.BackColor.G;
            pColorOutline.Blue  = picGCLineColor.BackColor.B;
            double dblGCOutlineSize = Convert.ToDouble(nudGCLinewidth.Value);

            ICartographicLineSymbol pOutLines = new CartographicLineSymbol();

            pOutLines.Width = dblGCOutlineSize;
            pOutLines.Color = (IColor)pColorOutline;

            //' use this interface to set dialog properties
            IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pRender;

            pUIProperties.ColorRamp = "Custom";

            ISimpleFillSymbol pSimpleFillSym;

            //' be careful, indices are different for the diff lists
            for (int j = 0; j < intGCBreakeCount; j++)
            {
                pRender.Break[j]          = cb[j + 1];
                pRender.Label[j]          = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString();
                pUIProperties.LowBreak[j] = cb[j];
                pSimpleFillSym            = new SimpleFillSymbolClass();
                pSimpleFillSym.Color      = pEnumColors.Next();
                pSimpleFillSym.Outline    = pOutLines;
                pRender.Symbol[j]         = (ISymbol)pSimpleFillSym;
            }
            pGeofeatureLayer.Renderer = (IFeatureRenderer)pRender;


            //////////////////The Robustness
            int    intRoundingDigits   = 2;
            int    intUncernBreakCount = Convert.ToInt32(nudTeNClasses.Value);
            string strUncerFieldName   = cboUField.Text;

            int intUncernIdx = pFClass.FindField(strUncerFieldName);
            int intValueIdx  = pFClass.FindField(strGCRenderField);

            //Calculate Robustness
            //Add fld
            int    intTempfldIdx  = 0;
            string strTempfldName = txtFldName.Text;

            if (chkRobustness.Checked)
            {
                if (pFClass.FindField(strTempfldName) == -1)
                {
                    AddField(pFClass, strTempfldName);
                }
                intTempfldIdx = pFClass.FindField(strTempfldName);
            }

            Chart pChart = new Chart();

            IFeature pFeat = null;
            //IFeatureCursor pFCursor = pFClass.Search(null, false);
            IFeatureCursor pFCursor = null;

            if (chkRobustness.Checked)
            {
                pFCursor = pFClass.Update(null, false);
            }
            else
            {
                pFCursor = pFClass.Search(null, false);
            }

            pFeat = pFCursor.NextFeature();
            double[] arrRobustness = new double[pFClass.FeatureCount(null)];

            int i = 0;

            while (pFeat != null)
            {
                for (int j = 0; j < (cb.Length - 1); j++)
                {
                    double dblValue = Convert.ToDouble(pFeat.get_Value(intValueIdx));
                    double dblStd   = Convert.ToDouble(pFeat.get_Value(intUncernIdx));
                    if (j == 0)
                    {
                        if (dblValue >= cb[j] && dblValue <= cb[j + 1])
                        {
                            double dblUpperZvalue  = (cb[j + 1] - dblValue) / dblStd;
                            double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
                            double dblLowerZvalue  = (cb[j] - dblValue) / dblStd;
                            double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
                            arrRobustness[i] = dblUpperConfLev - dblLowerConfLev;
                            if (chkRobustness.Checked)
                            {
                                pFeat.set_Value(intTempfldIdx, arrRobustness[i]);
                            }
                        }
                    }
                    else
                    {
                        if (dblValue > cb[j] && dblValue <= cb[j + 1])
                        {
                            double dblUpperZvalue  = (cb[j + 1] - dblValue) / dblStd;
                            double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
                            double dblLowerZvalue  = (cb[j] - dblValue) / dblStd;
                            double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
                            arrRobustness[i] = dblUpperConfLev - dblLowerConfLev;
                            if (chkRobustness.Checked)
                            {
                                pFeat.set_Value(intTempfldIdx, arrRobustness[i]);
                            }
                        }
                    }
                }
                if (chkRobustness.Checked)
                {
                    pFCursor.UpdateFeature(pFeat);
                }

                i++;
                pFeat = pFCursor.NextFeature();
            }

            //Define the intervals (the last class is fixed to 1)
            if (intUncernBreakCount == 1)
            {
                return;
            }

            double[] arrRobustBrks     = new double[intUncernBreakCount + 1];
            double   dblRBrksIntervals = Math.Round(1 / Convert.ToDouble(intUncernBreakCount - 1), intRoundingDigits);

            arrRobustBrks[0] = 0;
            for (int j = 1; j < intUncernBreakCount; j++)
            {
                arrRobustBrks[j] = dblRBrksIntervals * j;
            }
            arrRobustBrks[intUncernBreakCount] = 1;



            IFeatureLayer pflUncern = new FeatureLayerClass();

            pflUncern.FeatureClass = pFClass;
            pflUncern.Name         = "Robustness";
            pflUncern.Visible      = true;

            IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern;

            pFCursor = pGFLUncern.Search(null, true);
            RobustnessRenderer pRobustnessRenderer = new RobustnessRenderer();

            pRobustnessRenderer.arrRobustBrks       = arrRobustBrks;
            pRobustnessRenderer.arrRobustness       = arrRobustness;
            pRobustnessRenderer.dblAngle            = Convert.ToDouble(nudAngleFrom.Value);
            pRobustnessRenderer.dblFromSep          = Convert.ToDouble(nudSeperationFrom.Value);
            pRobustnessRenderer.dblLinewidth        = Convert.ToDouble(nudTeLinewidth.Value);
            pRobustnessRenderer.dblToSep            = Convert.ToDouble(nudSeperationTo.Value);
            pRobustnessRenderer.intUncernBreakCount = intUncernBreakCount;
            pRobustnessRenderer.pLineColor          = pSnippet.getRGB(picTeLineColor.BackColor.R, picTeLineColor.BackColor.G, picTeLineColor.BackColor.B);
            IQueryFilter pQFilter = new QueryFilterClass();


            pRobustnessRenderer.PrepareFilter(pFClass, pQFilter);
            pRobustnessRenderer.Draw(pFCursor, esriDrawPhase.esriDPSelection, pActiveView.ScreenDisplay, null);
            pRobustnessRenderer.CreateLegend();
            pGFLUncern.Renderer = pRobustnessRenderer;

            pActiveView.FocusMap.AddLayer(pGFLUncern as ILayer);

            mForm.axMapControl1.ActiveView.Refresh();
            mForm.axTOCControl1.Update();
        }
        private void btOK_Click(object sender, EventArgs e)
        {
            try
            {
                string        pBasePointFileName    = cboBoxPointLayer.SelectedItem.ToString();
                string        pAlignmentPointnName  = comboBoxExCenterlineLayer.SelectedItem.ToString();
                IFeatureLayer pBasePointLayer       = null;
                IFeatureLayer pCenterlinePointLayer = null;
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pBasePointFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pBasePointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                    if (pAlignmentPointnName == pMapcontrol.get_Layer(i).Name)
                    {
                        pCenterlinePointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                }
                IFeatureClass pAlignmentPointFC = pCenterlinePointLayer.FeatureClass;
                IFeatureClass pPointFC          = pBasePointLayer.FeatureClass;
                IQueryFilter  pQF = null;
                DataTable     alignmentPointTable = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pAlignmentPointFC as ITable, pQF);
                DataTable     baseTable           = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pPointFC as ITable, pQF);

                //IMUTable => basetable, Centerlinetable => alignmenttable
                double beginM = (double)numericUpDown1.Value;
                double endM   = (double)numericUpDown2.Value;


                string baseMeasureColumn  = comboBoxBaseMeasureField.SelectedItem.ToString();
                string AlingMeasureColumn = comboBoxMeasureField.SelectedItem.ToString();

                DataView dv = baseTable.DefaultView;
                dv.Sort             = baseMeasureColumn + " ASC";
                baseTable           = dv.ToTable();
                dv                  = alignmentPointTable.DefaultView;
                dv.Sort             = AlingMeasureColumn + " ASC";
                alignmentPointTable = dv.ToTable();

                double centerlineLength = endM - beginM;
                alignmentPointTable.Columns.Add("特征点里程差");
                alignmentPointTable.Columns.Add("对齐里程");

                double endIMUM   = Convert.ToDouble(alignmentPointTable.Rows[alignmentPointTable.Rows.Count - 1][AlingMeasureColumn]);
                double beginIMUM = Convert.ToDouble(alignmentPointTable.Rows[0][AlingMeasureColumn]);
                double IMULength = endIMUM - beginM;

                List <DataRow> WantouPointList = (from DataRow r in alignmentPointTable.Rows
                                                  where r["类型"].ToString().Contains("弯头")
                                                  select r).ToList();
                List <DataRow> GuandianPointList = (from DataRow r in baseTable.Rows
                                                    where r["类型"].ToString().Contains("弯头")
                                                    select r).ToList();

                Dictionary <DataRow, DataRow> MatchedDataRowPair = new Dictionary <DataRow, DataRow>();
                for (int i = 0; i < WantouPointList.Count; i++)
                {
                    DataRow        IMUr       = WantouPointList[i];
                    double         ActionIMUM = (Convert.ToDouble(IMUr[AlingMeasureColumn]) - beginIMUM) * centerlineLength / IMULength + beginM;
                    List <DataRow> Featurerow = (from r in GuandianPointList
                                                 where Math.Abs(Convert.ToDouble(r[baseMeasureColumn]) - ActionIMUM) < Convert.ToDouble(numericUpDown3.Value)
                                                 select r).OrderBy(x => Math.Abs(Convert.ToDouble(x[baseMeasureColumn]) - ActionIMUM)).ToList();
                    if (Featurerow.Count > 0)
                    {
                        DataRow NearestR = Featurerow[0];
                        if (MatchedDataRowPair.Values.Contains(NearestR) == false)
                        {
                            IMUr["特征点里程差"] = Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM;
                            MatchedDataRowPair.Add(IMUr, NearestR);
                        }
                        else
                        {
                            DataRow mathcedIMUr = (from DataRow k in MatchedDataRowPair.Keys
                                                   where MatchedDataRowPair[k].Equals(NearestR)
                                                   select k).ToList().First();
                            double dis    = Math.Abs(Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM);
                            double olddis = Math.Abs(Convert.ToDouble(mathcedIMUr["特征点里程差"]));
                            if (dis < olddis)
                            {
                                MatchedDataRowPair.Remove(mathcedIMUr);
                                IMUr["特征点里程差"] = Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM;
                                MatchedDataRowPair.Add(IMUr, NearestR);
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }
                foreach (DataRow r in MatchedDataRowPair.Keys)
                {
                    r["对齐里程"] = MatchedDataRowPair[r][baseMeasureColumn];
                }
                alignmentPointTable.Rows[0]["对齐里程"] = beginM;
                alignmentPointTable.Rows[alignmentPointTable.Rows.Count - 1]["对齐里程"] = endM;

                DataRow PrevRowWithM = null;
                for (int i = 0; i < alignmentPointTable.Rows.Count; i++)
                {
                    DataRow r = alignmentPointTable.Rows[i];
                    if (r["对齐里程"] != DBNull.Value)
                    {
                        PrevRowWithM = r;
                    }
                    else
                    {
                        DataRow NextRowWithM = null;
                        for (int j = i + 1; j < alignmentPointTable.Rows.Count; j++)
                        {
                            DataRow r2 = alignmentPointTable.Rows[j];
                            if (r2["对齐里程"] != DBNull.Value)
                            {
                                NextRowWithM = r2;
                                break;
                            }
                        }
                        if (PrevRowWithM == null || NextRowWithM == null)
                        {
                            break;
                        }
                        double BeginJiluM   = Convert.ToDouble(PrevRowWithM[AlingMeasureColumn]);
                        double endJiluM     = Convert.ToDouble(NextRowWithM[AlingMeasureColumn]);
                        double BeginAM      = Convert.ToDouble(PrevRowWithM["对齐里程"]);
                        double endAM        = Convert.ToDouble(NextRowWithM["对齐里程"]);
                        double currentJiluM = Convert.ToDouble(r[AlingMeasureColumn]);
                        r["对齐里程"] = (currentJiluM - BeginJiluM) * (endAM - BeginAM) / (endJiluM - BeginJiluM) + BeginAM;
                    }
                }


                MatchedDataRowPair.Clear();
                alignmentPointTable.Columns.Add("对齐基准点里程");
                alignmentPointTable.Columns.Add("对齐基准点里程差");
                alignmentPointTable.Columns.Add("对齐基准点类型");

                foreach (DataRow IMUr in alignmentPointTable.Rows)
                {
                    double ActionIMUM = Convert.ToDouble(IMUr["对齐里程"]);

                    List <DataRow> Featurerow = (from DataRow r in baseTable.Rows
                                                 where Math.Abs(Convert.ToDouble(r[baseMeasureColumn]) - ActionIMUM) < Convert.ToDouble(numericUpDown3.Value) &&
                                                 ((r["类型"].ToString().Contains("弯头") && IMUr["类型"].ToString().Contains("弯头")) ||
                                                  (r["类型"].ToString().Contains("异常") && IMUr["类型"].ToString().Contains("异常")))
                                                 select r).OrderBy(x => Math.Abs(Convert.ToDouble(x[baseMeasureColumn]) - ActionIMUM)).ToList();
                    if (Featurerow.Count > 0)
                    {
                        DataRow NearestR = Featurerow[0];
                        if (MatchedDataRowPair.Values.Contains(NearestR) == false)
                        {
                            IMUr["对齐基准点里程差"] = Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM;
                            IMUr["对齐基准点里程"]  = NearestR[baseMeasureColumn];
                            IMUr["对齐基准点类型"]  = NearestR["类型"];
                            MatchedDataRowPair.Add(IMUr, NearestR);
                        }
                        else
                        {
                            DataRow mathcedIMUr = (from DataRow k in MatchedDataRowPair.Keys
                                                   where MatchedDataRowPair[k].Equals(NearestR)
                                                   select k).ToList().First();
                            double dis    = Math.Abs(Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM);
                            double olddis = Math.Abs(Convert.ToDouble(mathcedIMUr["对齐基准点里程差"]));
                            if (dis < olddis)
                            {
                                MatchedDataRowPair.Remove(mathcedIMUr);
                                IMUr["对齐基准点里程差"] = Convert.ToDouble(NearestR[baseMeasureColumn]) - ActionIMUM;
                                IMUr["对齐基准点里程"]  = NearestR[baseMeasureColumn];
                                IMUr["对齐基准点类型"]  = NearestR["类型"];
                                MatchedDataRowPair.Add(IMUr, NearestR);
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }



                FrmIMUAlignmentresult frm = new FrmIMUAlignmentresult(alignmentPointTable);
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #60
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (pDrawDenplot.cboSourceLayer.Text != "" && pDrawDenplot.cboUField.Text != "" && pDrawDenplot.cboValueField.Text != "")
            {
                IGeoFeatureLayer pGeoFeatureLayer = pDrawDenplot.pGeofeatureLayer;

                mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;
                IActiveView pActiveView        = mForm.axMapControl1.ActiveView;
                string      strTargetLayerName = pDrawDenplot.cboSourceLayer.Text;
                string      strValueField      = pDrawDenplot.cboValueField.Text;
                string      strUncerField      = pDrawDenplot.cboUField.Text;

                clsSnippet pSnippet = new clsSnippet();

                //Using IRubberband
                IEnvelope pEnvelop = pSnippet.DrawRectangle(pActiveView);

                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry   = pEnvelop;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);

                ILayer        pLayer  = mForm.axMapControl1.get_Layer(intTLayerIdx);
                IFeatureLayer pFLayer = (IFeatureLayer)pLayer;

                string ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName;
                pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName;
                IFeatureClass pFeatureClass = pFLayer.FeatureClass;


                int intValueFldIdx = pFeatureClass.FindField(strValueField);
                int intUncerFldIdx = pFeatureClass.FindField(strUncerField);

                IFeatureCursor pFCursor = pGeoFeatureLayer.Search(pSpatialFilter, true);

                StackedChartRenderer pStackedChartRenderer = new StackedChartRenderer();

                pStackedChartRenderer.dblError               = pDrawDenplot.dblError;
                pStackedChartRenderer.intValueFldIdx         = intValueFldIdx;
                pStackedChartRenderer.intUncerFldIdx         = intUncerFldIdx;
                pStackedChartRenderer.dblMaxValue            = pDrawDenplot.dblMaxValue;
                pStackedChartRenderer.bln3Dfeature           = pDrawDenplot.bln3Dfeature;
                pStackedChartRenderer.m_strOriRenderField    = strValueField;
                pStackedChartRenderer.m_strUncernRenderField = strUncerField;

                pStackedChartRenderer.dblMaxEstimate = pDrawDenplot.dblMaxEstimate;
                pStackedChartRenderer.dblMaxUncern   = pDrawDenplot.dblMaxUncern;

                pStackedChartRenderer.m_pQueryFilter = pSpatialFilter as IQueryFilter;

                //pStackedChartRenderer.m_stackedChart = pGeoFeatureLayer.Renderer;

                //pStackedChartRenderer.PrepareFilter(pFeatureClass, pSpatialFilter);
                pStackedChartRenderer.m_pDisplay = pActiveView.ScreenDisplay;
                //pStackedChartRenderer.Draw(pFCursor, esriDrawPhase.esriDPSelection, pDisplay, null);
                //pStackedChartRenderer.CreateLegend();
                pGeoFeatureLayer.Renderer = pStackedChartRenderer;


                //mForm.axMapControl1.ActiveView.Refresh();
                pActiveView.Refresh();
            }
        }