Exemplo n.º 1
0
        /// <summary>
        /// 从比例尺列表中,选择能够展示指定要素范围的最合适比例尺
        /// </summary>
        /// <param name="pageLayout">页面布局</param>
        /// <param name="mapFrame">要设定显示范围及比例尺的地图数据框</param>
        /// <param name="featureEnv">地图要素显示范围</param>
        /// <param name="scaleList">比例尺列表,将从中选取最合适的比例尺</param>
        /// <param name="bufferDistance">要素与图廓的缓冲距离(厘米),即地图实际显示范围是featEnvelope + 2 * bufferDistance</param>
        /// <returns></returns>
        public static double SetMapScale(this IPageLayout pageLayout, IMapFrame mapFrame,
                                         IEnvelope featureEnv, double[] scaleList, double bufferDistance = 2)
        {
            esriUnits pageUnit = pageLayout.Page.Units;
            esriUnits mapUnit  = mapFrame.Map.DistanceUnits;
            esriUnits cmUnit   = esriUnits.esriCentimeters; //厘米

            IEnvelope      mapFrameEnv   = (mapFrame as IElement)?.Geometry.Envelope;
            IUnitConverter unitConverter = new UnitConverterClass();
            double         wScale        = unitConverter.ConvertUnits(featureEnv.Width, mapUnit, cmUnit) / (unitConverter.ConvertUnits(mapFrameEnv.Width, pageUnit, cmUnit) - 2 * bufferDistance);
            double         hScale        = unitConverter.ConvertUnits(featureEnv.Height, mapUnit, cmUnit) / (unitConverter.ConvertUnits(mapFrameEnv.Height, pageUnit, cmUnit) - 2 * bufferDistance);
            double         dScale        = wScale > hScale ? wScale : hScale;

            int maxIndex = 0;

            while (maxIndex < scaleList.Length && dScale > scaleList[maxIndex])
            {
                maxIndex++;//寻找比要素全图廓显示所确定的比例尺小一级的比例尺
            }
            if (maxIndex == scaleList.Length)
            {
                throw new Exception("需要更小的比例尺!");
            }

            return(scaleList[maxIndex]);
        }
Exemplo n.º 2
0
        //定位
        private void button1_Click(object sender, EventArgs e)
        {
            //ESRI.ArcGIS.esriSystem.IUnitConverter unitConverter = (ESRI.ArcGIS.esriSystem.IUnitConverter)ServerContext.CreateObject("esriSystem.UnitConverter");


            //project raster
            //IUnitConverter iu = new esriUnits();

            IUnitConverter unitConverter             = new UnitConverterClass();
            double         dFittedBoundsWidthInches  = unitConverter.ConvertUnits(-100, esriUnits.esriDecimalDegrees, esriUnits.esriMeters) / 100;
            double         dFittedBoundsWidthInchesy = unitConverter.ConvertUnits(40, esriUnits.esriDecimalDegrees, esriUnits.esriMeters) / 100;
            //ui.ConvertUnits(10, esriUnits.esriMeters, esriUnits.esriMeters);
            //IPoint pPoint = new PointClass();
            //pPoint.X = -1000;
            //pPoint.Y = -1000;

            //IGeometry pGeometry;
            //pGeometry = (IGeometry)pPoint;

            //IMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbolClass();

            //axMapControl.FlashShape(pGeometry, 4, 100, pMarkerSymbol);



            IEnvelope pEnvelope = new EnvelopeClass();
            IPoint    pPoint    = new PointClass();

            //axMapControl.MapUnits = esriUnits.esriDecimalDegrees;
            //axMapControl.MapUnits = esriUnits.esriMeters; //米


            // esriUnits mapUnits = axMapControl.MapUnits;


            //axMapControl.MapUnits = esriUnits.esriDecimalDegrees;
            //pPoint.PutCoords(Convert.ToDouble(textBox1.Text), Convert.ToDouble(textBox2.Text));//该句中的txtlong,txtlat是输入经纬值的TextBox
            pPoint.X  = Convert.ToDouble(textBox1.Text);
            pPoint.Y  = Convert.ToDouble(textBox2.Text);
            pEnvelope = axMapControl.Extent;
            pEnvelope.CenterAt(pPoint);

            axMapControl.Extent = pEnvelope.Envelope;     //前一段代码实现平移
            axMapControl.ActiveView.ScreenDisplay.UpdateWindow();
            axMapControl.FlashShape(pPoint as IGeometry); //此句实现闪烁(效果没有ArcMap中好, )
            //axMapControl.ActiveView.Extent = pEnvelope;
            //showAnnotationByScale();
        }
        /// <summary>
        /// 将输入的数据单位转化为米
        /// </summary>
        /// <param name="dValue"></param>
        /// <param name="outUnits"></param>
        /// <returns></returns>
        public double UnitsConvertToMeters(double dValue, esriUnits outUnits)
        {
            IUnitConverter unitConverter = new UnitConverterClass();
            double         newValue      = unitConverter.ConvertUnits(dValue, esriUnits.esriMeters, outUnits);

            return(newValue);
        }
Exemplo n.º 4
0
        public static double GetGlobeElevation(IGlobeDisplay globeDisplay, double longitude, double latitude, bool maxResolution)
        {
            IUnitConverter unitConverter = new UnitConverterClass();

            double doubleZ = 0;

            globeDisplay.GetSurfaceElevation(longitude, latitude, maxResolution, out doubleZ);
            return(unitConverter.ConvertUnits(doubleZ, esriUnits.esriMeters, globeDisplay.Globe.GlobeUnits));
        }
Exemplo n.º 5
0
        public double getLinearConversion(IProjectedCoordinateSystem prjSys)
        {
            IUnitConverter converter  = new UnitConverterClass();
            ILinearUnit    linearUnit = prjSys.CoordinateUnit;
            double         meter      = linearUnit.MetersPerUnit;
            double         unitToFoot = converter.ConvertUnits(meter, esriUnits.esriMeters, esriUnits.esriFeet);

            return(unitToFoot);
        }
Exemplo n.º 6
0
        //private void toolCM_Click(object sender, EventArgs e)
        //{
        //    this.m_Units = esriUnits.esriCentimeters;
        //}


        //private void toolMM_Click(object sender, EventArgs e)
        //{
        //    this.m_Units = esriUnits.esriMillimeters;
        //}

        #endregion

        /// <summary>
        /// guozheng 2011-5-8 added 将量算坐标单位转换为实际要求的单位
        /// </summary>
        /// <param name="in_Len">输入需要转换的数值</param>
        /// <returns>输出:转换后的数值,内部异常返回-1并记录异常日志</returns>
        private double UnitConvert(double in_Len)
        {
            IUnitConverter pUnitConvert = new UnitConverterClass();

            try
            {
                double Res = pUnitConvert.ConvertUnits(in_Len, this.m_Displayunit, this.m_Units);
                return(Res);
            }
            catch (Exception eError)
            {
                if (SysCommon.Log.Module.SysLog == null)
                {
                    SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                }
                SysCommon.Log.Module.SysLog.Write(eError);
                return(-1);
            }
        }
        public int DrawGpsCep(double latitude, double longitude, double[] radii)
        {
            if (MxDocument == null)
            {
                return(-1);
            }
            if (GraphicsLayer == null)
            {
                return(-2);
            }
            ISpatialReference sr = MxDocument.FocusMap.SpatialReference;

            if (sr == null || sr is IGeographicCoordinateSystem)
            {
                return(-3);
            }
            esriUnits mapUnits = MxDocument.FocusMap.MapUnits;

            if (mapUnits == esriUnits.esriUnknownUnits ||
                mapUnits == esriUnits.esriDecimalDegrees ||
                mapUnits == esriUnits.esriUnitsLast)
            {
                return(-3);
            }
            IUnitConverter uc       = new UnitConverterClass();
            var            mapRadii = from radius in radii
                                      select uc.ConvertUnits(radius, esriUnits.esriMeters, mapUnits);

            IPoint point = new PointClass();

            point.PutCoords(longitude, latitude);
            point.SpatialReference = Wgs84;
            point.Project(sr);
            if (point.IsEmpty)
            {
                return(-3);
            }

            int id = AddCepGraphic(point, mapRadii.ToList());

            return(id);
        }
Exemplo n.º 8
0
        private double GetBuffSize()
        {
            double dBufferSize = 0;

            //double.TryParse(this.dblBuffLen.Text, out dblSize);
            dBufferSize = Convert.ToDouble(dblBuffLen.Text); /*/ 10*/; //20110802 xisheng
            dBufferSize = dBufferSize < 1 ? 1 : dBufferSize;           //设置缓冲值不能设置成0 xisheng 20110722
            if (dBufferSize == 0.0)
            {
                dBufferSize = 0.001;
            }
            //转换如果是经纬度的地图 xisheng 20110731
            UnitConverter punitConverter = new UnitConverterClass();

            if (m_pMap.MapUnits == esriUnits.esriDecimalDegrees)
            {
                dBufferSize = punitConverter.ConvertUnits(dBufferSize, esriUnits.esriMeters, esriUnits.esriDecimalDegrees);
            }//转换如果是经纬度的地图 xisheng 20110731
            return(dBufferSize);
        }
Exemplo n.º 9
0
        private void GetArea(ref double area, IMap pMap)
        {
            switch (pMap.MapUnits)
            {
            case esriUnits.esriKilometers:
                area = (Math.Abs(area)) * 1000000;
                break;

            case esriUnits.esriMeters:
            case esriUnits.esriUnknownUnits:
                area = Math.Abs(area);
                break;

            case esriUnits.esriDecimalDegrees:
                //转换如果是经纬度的地图 xisheng 20110731
                UnitConverter punitConverter = new UnitConverterClass();
                area = punitConverter.ConvertUnits(Math.Abs(area), esriUnits.esriMeters, esriUnits.esriDecimalDegrees);
                break;

            default:
                area = 0;
                break;
            }
        }
Exemplo n.º 10
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (Button == 2)
            {
                return;
            }
            IPoint pt = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);

            pt = GIS.GraphicEdit.SnapSetting.getSnapPoint(pt);
            IGraphicsContainer g          = m_hookHelper.ActiveView.GraphicsContainer;
            IEnvelope          pEnvBounds = null;

            //获取上一次轨迹线的范围,以便确定刷新范围
            try
            {
                if (m_TraceLine != null)
                {
                    m_TraceLine.QueryEnvelope(pEnvBounds);
                    pEnvBounds.Expand(4, 4, true); //矩形框向四周扩大4倍(大于2倍就行),目的是为了保证有充足的刷新区域
                }
                else
                {
                    pEnvBounds = m_hookHelper.ActiveView.Extent;
                }
            }
            catch
            {
                pEnvBounds = m_hookHelper.ActiveView.Extent;
            }

            #region 启动画线
            if (m_NewLineFeedback == null)
            {
                //移除element
                RemoveElements();
                //刷新
                m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                Application.DoEvents();

                m_NewLineFeedback         = new NewLineFeedbackClass();
                m_NewLineFeedback.Display = m_hookHelper.ActiveView.ScreenDisplay;
                //必须先得到symbol,后设置symbol
                ISimpleLineSymbol simpleLineSymbol = m_NewLineFeedback.Symbol as ISimpleLineSymbol;
                simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
                simpleLineSymbol.Width = 2;
                simpleLineSymbol.Color = TransColorToAEColor(Color.Blue);

                m_NewLineFeedback.Start(pt);
            }
            else
            {
                m_NewLineFeedback.AddPoint(pt);
            }

            if (m_ptColl == null)
            {
                m_ptColl = new PolylineClass();
            }
            //记录节点
            object obj = Type.Missing;
            m_ptColl.AddPoint(pt, ref obj, ref obj);

            #endregion

            #region 绘制结点

            try
            {
                IElement vertexElement = createElement_x(pt);
                //
                g = m_hookHelper.ActiveView as IGraphicsContainer;

                //g.AddElement(vertexElement, 0);
                //g.MoveElementToGroup(vertexElement, m_VertexElement);

                m_VertexElement.AddElement(vertexElement);
                //刷新
                m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, vertexElement, pEnvBounds);
            }
            catch
            { }
            #endregion

            try
            {
                if (m_ptColl.PointCount >= 2)
                {
                    IPoint fromPt = m_ptColl.get_Point(m_ptColl.PointCount - 2); //倒数第二个点
                    IPoint toPt   = m_ptColl.get_Point(m_ptColl.PointCount - 1); //最后第一个点
                    ILine  line   = new LineClass();
                    line.PutCoords(fromPt, toPt);

                    #region 绘制轨迹线

                    try
                    {
                        object             missing = Type.Missing;
                        ISegmentCollection segColl = new PolylineClass();
                        segColl.AddSegment(line as ISegment, ref missing, ref missing);
                        IElement traceElement = createElement_x(segColl as IPolyline);
                        //
                        g = m_hookHelper.ActiveView as IGraphicsContainer;

                        //g.AddElement(traceElement, 0);
                        //g.MoveElementToGroup(traceElement, m_TraceElement);

                        m_TraceElement.AddElement(traceElement);

                        m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, traceElement, pEnvBounds);
                    }
                    catch
                    { }
                    #endregion

                    #region 计算单线的长度,并将结果显示在单线中点偏上上面
                    try
                    {
                        double angle = line.Angle;
                        if ((angle > (Math.PI / 2) && angle < (Math.PI)) || (angle > -Math.PI && angle < -(Math.PI / 2))) // 大于90度小于等于180
                        {
                            angle += Math.PI;
                        }

                        //标注点Y值偏移量
                        double d_OffsetY = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.FromPoints(9);

                        //标注点

                        double d_CenterX = (fromPt.X + toPt.X) / 2;
                        double d_CenterY = (fromPt.Y + toPt.Y) / 2 + d_OffsetY; //向上偏移

                        IPoint labelPt = new PointClass();
                        labelPt.PutCoords(d_CenterX, d_CenterY);
                        IUnitConverter unitConverter = new UnitConverterClass();
                        double         segmentLength = unitConverter.ConvertUnits(line.Length, _MsgInfo.inUnit.pUnit, _MsgInfo.outUnit.pUnit);
                        ITextElement   txtElement    = CreateTextElement(segmentLength.ToString("0.00"));

                        IElement labelelement = txtElement as IElement;
                        labelelement.Geometry = labelPt;
                        object oElement = (object)labelelement;

                        //根据角度旋转
                        TransformByRotate(ref oElement, labelPt, angle);

                        ////添加到GraphicsContainer
                        //g.AddElement(labelelement, 0);

                        ////移到m_LabelElement组中
                        //g.MoveElementToGroup(labelelement, m_LabelElement);

                        //添加到组
                        m_LabelElement.AddElement(labelelement);

                        //刷新

                        m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, labelelement, pEnvBounds);
                    }
                    catch
                    { }
                    #endregion
                }
            }
            catch
            { }

            _MsgInfo.LineResultChange();
        }
Exemplo n.º 11
0
        private void MapUserIdentify(double mapX, double mapY)
        {
            try
            {
                //axMapControl1.Map.ClearSelection();
                ESRI.ArcGIS.Controls.IMapControl3 m_mapControl = (IMapControl3)axMapControl1.Object;
                IMap        pMap        = axMapControl1.Map;
                IGroupLayer pGroupLayer = new GroupLayer();

                if (pMap.LayerCount == 0)
                {
                    return;
                }
                IEnumLayer pEnumLayer;
                ILayer     pLayer;
                pEnumLayer = pMap.get_Layers(null, true);
                if (pEnumLayer == null)
                {
                    return;
                }
                pEnumLayer.Reset();
                double dCurrScale = m_mapControl.MapScale;
                for (pLayer = pEnumLayer.Next(); pLayer != null; pLayer = pEnumLayer.Next())
                {
                    if (pLayer.Visible)
                    {
                        if (pLayer is IGroupLayer)
                        {
                            continue;
                        }
                        if (pLayer.MinimumScale != 0 && dCurrScale > pLayer.MinimumScale)
                        {
                            continue;
                        }
                        if (pLayer.MaximumScale != 0 && dCurrScale < pLayer.MaximumScale)
                        {
                            continue;
                        }
                        pGroupLayer.Add(pLayer);
                    }
                }

                IPoint pPoint = new ESRI.ArcGIS.Geometry.Point();
                pPoint.X = mapX; pPoint.Y = mapY;
                IIdentifyObj        pIdObj;
                IIdentify           pIdentify = pGroupLayer as IIdentify;
                IArray              pIDArray;
                IFeatureIdentifyObj pFeatIdObj;

                IEnvelope pEnv             = pPoint.Envelope;
                IDisplayTransformation pDT = m_mapControl.ActiveView.ScreenDisplay.DisplayTransformation;
                pEnv.Expand(pDT.VisibleBounds.Width / 200, pDT.VisibleBounds.Height / 200, false);

                pIDArray = pIdentify.Identify(pEnv);

                if (pIDArray == null || pIDArray.Count == 0)
                {
                    return;
                }

                pFeatIdObj = pIDArray.get_Element(0) as IFeatureIdentifyObj;
                pIdObj     = pFeatIdObj as IIdentifyObj;

                IRowIdentifyObject pRowIdentifyObj = pFeatIdObj as IRowIdentifyObject;
                IFeature           pFeature        = pRowIdentifyObj.Row as IFeature;
                if (pFeature != null && pFeature.Shape != null && !pFeature.Shape.IsEmpty)
                {
                    //axMapControl1.FlashShape(pFeature.Shape);
                    axMapControl1.Map.SelectFeature(pIdObj.Layer, pFeature);
                    FlashFeature(axMapControl1, pFeature.Shape);
                }

                //  pIdObj.Flash(m_mapControl.ActiveView.ScreenDisplay);//The Flash method is not supported with ArcGIS Engine, use the IHookActions.DoActions() method with the esriHookActionsFlash for this functionality.
                ILayer pIdentiyLayer = pIdObj.Layer;

                DataTable  pTable      = new DataTable();
                DataColumn pDataColumn = pTable.Columns.Add();
                pDataColumn.ColumnName = "列名";
                pDataColumn            = pTable.Columns.Add();
                pDataColumn.ColumnName = "值";

                DataRow pFirestDataRow = pTable.Rows.Add();
                pFirestDataRow[0] = "所在层";
                pFirestDataRow[1] = pIdentiyLayer.Name;

                if (pIdentiyLayer is IFeatureLayer)
                {
                    IRowIdentifyObject pRowObj = pIdObj as IRowIdentifyObject;
                    //   IRow pRow = pRowObj.Row;

                    IFeature pRow    = pRowObj.Row as IFeature;
                    IFields  pFields = pRow.Fields;

                    for (int i = 0; i < pFields.FieldCount; i++)
                    {
                        IField  pField   = pFields.get_Field(i);
                        DataRow pDataRow = null;

                        /*
                         * switch (pField.Type)
                         * {
                         *  case esriFieldType.esriFieldTypeOID:
                         *      pDataRow = pTable.Rows.Add();
                         *      pDataRow[0] = pField.Name;
                         *      pDataRow[1] = pRow.OID.ToString();
                         *      break;
                         *  case esriFieldType.esriFieldTypeGeometry:
                         *      //pDataRow[0] = "Geometry";
                         *      //pDataRow[1] = QueryShapeType(pField.GeometryDef.GeometryType);;
                         *      break;
                         *  default:
                         *      pDataRow = pTable.Rows.Add();
                         *      pDataRow[0] = pField.Name;
                         *      pDataRow[1] = pRow.get_Value(i).ToString();
                         *      break;
                         * }
                         * * */

                        //////////////////////////////////////////////////
                        string sValue   = pRow.get_Value(i).ToString();
                        string strFName = pField.AliasName.ToUpper();
                        string strUName = strFName.ToUpper();
                        if (strUName == "SHAPE" || strUName == "LENGTH" || strUName == "OBJECTID" || strUName == "ID" || strUName == "FNODE_" || strUName == "TNODE_" || strUName == "LPOLY_" || strUName == "RPOLY_" || strUName == "SDXL_" || strUName == "SDXL_ID" || strUName == "OBJECTID_1" || strUName == "FID")
                        {
                            continue;
                        }
                        else if (strUName == "SHAPE.LEN" || strUName == "SHAPE_LENG")
                        {
                            strFName = "几何长度";
                        }
                        else if (strUName == "SHAPE_AREA" || strUName == "SHAPE.AREA")
                        {
                            strFName = "多边形面积";
                        }
                        else if (strUName == "HEIGHT")
                        {
                            strFName = "高程";
                        }
                        else if (strUName == "NAME")
                        {
                            strFName = "名称";
                        }
                        else if (strUName == "TYPE")
                        {
                            strFName = "类型";
                        }
                        else if (strUName == "SUBTYPE")
                        {
                            strFName = "子类型";
                        }

                        if (strUName == "LENGTH" || strUName == "SHAPE.LEN")
                        {
                            IUnitConverter myUnit = new UnitConverterClass();
                            sValue = Math.Round(myUnit.ConvertUnits((double)pRow.get_Value(i), esriUnits.esriMeters, esriUnits.esriKilometers), 2).ToString();
                            sValue = sValue.ToString() + "千米";
                        }
                        if (strUName == "SHAPE_AREA" || strUName == "SHAPE.AREA")
                        {
                            IGeometry pGeo = pRow.ShapeCopy;
                            pGeo.Project(axMapControl1.Map.SpatialReference);
                            IPolygon pPolygon = (IPolygon)pGeo;
                            IArea    pArea    = (IArea)pPolygon;
                            double   strValue = pArea.Area * 0.000001;
                            //// double strValue = Math.Abs((double)pFeature.get_Value(j)) * 10585;
                            strValue = Math.Round(strValue, 2);
                            sValue   = strValue.ToString() + "平方千米";
                        }
                        esriFieldType tFieldTypy = pField.Type;
                        if (tFieldTypy == esriFieldType.esriFieldTypeGeometry)
                        {
                            sValue = pField.GeometryDef.GeometryType.ToString();
                            sValue = sValue.Substring(12, sValue.Length - 12);
                        }

                        pDataRow    = pTable.Rows.Add();
                        pDataRow[0] = strFName;
                        pDataRow[1] = sValue;

                        //////////////////////////////////////////////////
                    }
                }
                else if (pIdentiyLayer is ITinLayer)
                {
                    ITinLayer   pTinLayer   = (ITinLayer)pIdentiyLayer;
                    ITinSurface pTinSurface = (ITinSurface)pTinLayer.Dataset;
                    if (pTinSurface == null)
                    {
                        return;
                    }
                    ITinSurfaceElement pTinSurfaceElement = pTinSurface.GetSurfaceElement(pPoint);

                    if (pTinSurfaceElement == null)
                    {
                        return;
                    }
                    IFields pFields  = pTinLayer.Dataset.Fields;
                    DataRow pDataRow = null;

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "高度";
                    pDataRow[1] = pTinSurfaceElement.Elevation.ToString();

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "坡度";
                    pDataRow[1] = pTinSurfaceElement.SlopeDegrees.ToString();

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "方向";
                    pDataRow[1] = pTinSurfaceElement.AspectDegrees.ToString();
                }

                if (pIdentiyLayer is IRasterLayer)
                {
                    MessageBox.Show("aa");
                }
                //ShowIndetify(pTable);
                //m_pMainform.ShowIndetify(pTable);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
        }
Exemplo n.º 12
0
        //获取当前的缓冲后的几何体
        private void get_BufferGeometry()
        {
            Error_Lable.Visible = false;
            Error_Lable.Text    = "";
            //存在上次的缓冲几何体 则先抹去其图形
            if (m_pBufferGeometry != null)
            {
                drawgeometryXOR(m_pBufferGeometry as IPolygon, m_pScreenDisplay);
            }

            //获取缓冲半径
            dBufferSize = Convert.ToDouble(txtBufferValue.Text); /*/ 10*/; //20110802 xisheng
            dBufferSize = dBufferSize < 1 ? 1 : dBufferSize;               //设置缓冲值不能设置成0 xisheng 20110722
            if (dBufferSize == 0.0)
            {
                dBufferSize = 0.001;
            }
            //转换如果是经纬度的地图 xisheng 20110731
            UnitConverter punitConverter = new UnitConverterClass();

            if (m_pMap.MapUnits == esriUnits.esriDecimalDegrees)
            {
                dBufferSize = punitConverter.ConvertUnits(dBufferSize, esriUnits.esriMeters, esriUnits.esriDecimalDegrees);
            }//转换如果是经纬度的地图 xisheng 20110731
            //==如果直接操作,则原pGeometry会被改变
            //进行克隆,获取topo实例
            IClone pClone = (IClone)m_pGeometry;
            ITopologicalOperator pTopo;

            if (m_pGeometry.GeometryType != esriGeometryType.esriGeometryBag)
            {
                pTopo = pClone.Clone() as ITopologicalOperator;

                //topo非空则进行缓冲,获取缓冲后的 m_pBufferGeometry
                if (pTopo != null)
                {
                    m_pBufferGeometry = pTopo.Buffer(dBufferSize);
                }
            }
            else
            {
                IGeometryCollection pGeometryBag = (IGeometryCollection)pClone.Clone();
                pTopo = (ITopologicalOperator)pGeometryBag.get_Geometry(0);
                IGeometry pUnionGeom = pTopo.Buffer(dBufferSize);
                for (int i = 1; i < pGeometryBag.GeometryCount; i++)
                {
                    pTopo = (ITopologicalOperator)pGeometryBag.get_Geometry(i);
                    IGeometry pTempGeom = pTopo.Buffer(dBufferSize);
                    pTopo      = (ITopologicalOperator)pUnionGeom;
                    pUnionGeom = pTopo.Union(pTempGeom);
                }
                m_pBufferGeometry = pUnionGeom;
            }
            // m_pBufferGeometry为空,直接返回
            if (m_pBufferGeometry == null)
            {
                return;
            }

            //对 m_pBufferGeometry的topo进行简化再绘出
            pTopo = m_pBufferGeometry as ITopologicalOperator;
            if (pTopo != null)
            {
                pTopo.Simplify();
            }

            IPolygon pPolygon = m_pBufferGeometry as IPolygon;

            drawgeometryXOR(pPolygon, m_pScreenDisplay);
        }
Exemplo n.º 13
0
        public override int Execute(string logfileName)
        {
            this.InitLogging(logfileName);
            this.LogMessage(this.Name + " QA test execution started.");

            int currentOid = -1;
            bool bProblemsRunning = false;

            try
            {
                this.LogMessage(this.Name + " Parameters:");
                for (int i = 0; i < this.ParameterCount; i++)
                    this.LogMessage(this.get_ParameterText(i) + ": " + this.get_ParameterValue(i));

                this.ClearErrors();

                int index = this.FindParameter(ParameterInfo.PARAM_CANDEFER);
                bool canDefer = (bool)((ParameterInfo)this._params[index]).ParamValue;
                index = this.FindParameter(ParameterInfo.PARAM_CANEXCEPT);
                bool canExcept = (bool)((ParameterInfo)this._params[index]).ParamValue;

                if (canDefer || canExcept)
                {
                    this.LogMessage("Errors found by " + this.Name + " cannot be deferred or excepted.");
                }

                IFeatureLayer theSeeLayer = this.SEELayer;
                if (theSeeLayer == null)
                {
                    this.LogMessage("Missing SEE layer. Exiting Execute.");
                    bProblemsRunning = true;
                }
                else if (this._eDao == null)
                {
                    this.LogMessage("Missing Edits Data Access Object. Exiting Execute.");
                    bProblemsRunning = true;
                }
                //else if (this._tmConfig == null)
                //{
                //    this.LogMessage("Missing Transaction Config object. Exiting Execute.");
                //    bProblemsRunning = true;
                //}
                else
                {
                    // Select the SEE polygon
                    string theTxID = this.TxID;
                    IQueryFilter theQF = new QueryFilterClass();
                    theQF.WhereClause = SEE_ID_FIELD_NAME + " = '" + theTxID + "'";
                    IFeatureCursor theFCursor = theSeeLayer.Search(theQF, false);
                    IFeature theSee = theFCursor.NextFeature();
                    Marshal.ReleaseComObject(theFCursor);
                    theFCursor = null;

                    if (theSee == null)
                    {
                        this.LogMessage("Could not find SEE feature with id " + theTxID + ". Exiting Execute.");
                        bProblemsRunning = true;
                    }
                    else if (theSee.Shape == null || theSee.Shape.IsEmpty)
                    {
                        this.LogMessage("The SEE feature with id " + theTxID + " does not have a valid shape. Exiting Execute.");
                        bProblemsRunning = true;
                    }
                    else
                    {
                        ISegmentCollection theSColl = (ISegmentCollection)this.ShapeCopy(theSee);
                        IPolygon theSeeBounds = new PolygonClass();
                        ((ISegmentCollection)theSeeBounds).AddSegmentCollection(theSColl);
                        theSeeBounds.Close();

                        // Convert shift limit to metres
                        DoubleParameterInfo theParam = (DoubleParameterInfo)this._params[this.FindParameter("ignore-shift-smaller-than")];
                        double shiftLimit = (double)theParam.ParamValue;
                        UnitsParameterInfo theUnits = (UnitsParameterInfo)this._params[this.FindParameter("shift-units")];
                        IUnitConverter theConverter = new UnitConverterClass();
                        shiftLimit = theConverter.ConvertUnits(shiftLimit, theUnits.ParamValueInUnits, esriUnits.esriMeters);

                        for (int i = 0; i < this.LayerCount; i++)
                        {
                            IFeatureLayer theFLayer = this.get_Layer(i);
                             if (this.SupportsGeometryType(theFLayer.FeatureClass.ShapeType) == false)
                            {
                                this.LogMessage("Geometry type " + theFLayer.FeatureClass.ShapeType + " of layer " + theFLayer.Name + " not supported by " + this.Name);
                                continue;
                            }

                            if (theFLayer == theSeeLayer)
                                continue;

                            string theLayerKey = ((IDataset)theFLayer.FeatureClass).Name;
                            if (theLayerKey == null)
                            {
                                this.LogMessage("Could not find TM layer key for layer " + theFLayer.Name + " passed to " + this.Name);
                                bProblemsRunning = true;
                                break;
                            }

                            IFeatureClass theEditsFC = this.SiblingFClassWithName(i, "E_" + theLayerKey);
                            if (theEditsFC == null)
                                this.LogMessage("Could not find TM edits featureclass for layer " + theFLayer.Name + " passed to " + this.Name);
                            IFeatureClass thePristineFC = this.SiblingFClassWithName(i, "P_" + theLayerKey);
                            if (thePristineFC == null)
                                this.LogMessage("Could not find TM pristine featureclass for layer " + theFLayer.Name + " passed to " + this.Name);

                            if (theEditsFC == null || thePristineFC == null)
                            {
                                bProblemsRunning = true;
                                break;
                            }

                            if (this.ProcessLayer(theLayerKey, theFLayer.FeatureClass, theEditsFC, thePristineFC, theSeeBounds, shiftLimit) == false)
                            {
                                bProblemsRunning = true;
                                break;
                            }
                        }
                    }
                }

                this.LogMessage("Number of errors found: " + this.ErrorCount);
                if (!bProblemsRunning)
                    this.LogMessage("Test " + this.Name + " successful.");
            }
            catch (Exception ex)
            {
                this.LogMessage("Exception caught: \n" + ex.Message + "\n" + ex.StackTrace.ToString());
                this.LogMessage("id of the current polygon: " + currentOid);
                return -1;
            }
            finally
            {
                this.StopLogging();
            }

            if (bProblemsRunning)
                return -1;

            return this.ErrorCount;
        }
Exemplo n.º 14
0
        public static IAnimationTrack CreateZoomOverLocationAnimation(IGlobeDisplay globeDisplay, double doubleX, double doubleY, double doubleAltitide)
        {
            // Set Mouse Cursor
            //IMouseCursor mouseCursor = new MouseCursorClass();
            //mouseCursor.SetCursor(2);
            // QI to GlobeDisplayRendering Interface
            IGlobeDisplayRendering globeDisplayRendering = (IGlobeDisplayRendering)
                                                           globeDisplay;
            // Get Elevation Multiplication Factor
            IUnitConverter unitConverter = new UnitConverterClass();
            // Get GlobeDisplay and Camera
            IGlobe           globe           = globeDisplay.Globe;
            IAnimationTracks animationTracks = (IAnimationTracks)globe;

            IGlobeCamera globeCamera = (IGlobeCamera)globeDisplay.ActiveViewer.Camera;
            // Create New Animation Track
            IAnimationTrack animationTrack = new AnimationTrackClass();

            try
            {
                IAnimationType animationType = new AnimationTypeGlobeCameraClass();
                animationTrack.AnimationType = animationType;
                // Create First KeyFrame At Current Location
                IKeyframe keyframe1 = new GlobeCameraKeyframeClass();
                keyframe1.CaptureProperties((IScene)globe, globeCamera);
                animationTrack.InsertKeyframe(keyframe1, animationTrack.KeyframeCount);
                // Create Last KeyFrame Over Desired Location
                IKeyframe keyframe3 = new GlobeCameraKeyframeClass();
                keyframe3.set_PropertyValueInt(0, 0);
                keyframe3.set_PropertyValueDouble(1, doubleY);
                keyframe3.set_PropertyValueDouble(2, doubleX);
                keyframe3.set_PropertyValueDouble(3, -1d *
                                                  unitConverter.ConvertUnits(globeDisplayRendering.GlobeRadius, esriUnits.esriMeters,
                                                                             globe.GlobeUnits)); // (globeDisplayRendering.GlobeRadius / -1000));
                keyframe3.set_PropertyValueDouble(4, doubleY);
                keyframe3.set_PropertyValueDouble(5, doubleX);
                keyframe3.set_PropertyValueDouble(6, doubleAltitide);
                keyframe3.set_PropertyValueDouble(7, 30);
                keyframe3.set_PropertyValueDouble(8, 0);

                #region 获取第一帧和第三帧的参数
                double dX1_Tar, dY1_Tar, dZ1_Tar, dX1_Obs, dY1_Obs, dZ1_Obs;
                GetParametersFromKeyFrame(keyframe1, out dX1_Tar, out dY1_Tar, out dZ1_Tar, out dX1_Obs, out dY1_Obs, out dZ1_Obs);
                double dX3_Tar, dY3_Tar, dZ3_Tar, dX3_Obs, dY3_Obs, dZ3_Obs;
                GetParametersFromKeyFrame(keyframe3, out dX3_Tar, out dY3_Tar, out dZ3_Tar, out dX3_Obs, out dY3_Obs, out dZ3_Obs);
                #endregion

                ////=========================================== 创建中间帧    == == == == == == == == == == == == == == == == == == == == == =
                IKeyframe keyframe2 = CreateMiddleKeyframe(globeDisplay.Globe, dX1_Tar,
                                                           dY1_Tar, dZ1_Tar, dX1_Obs, dY1_Obs, dZ1_Obs,
                                                           dX3_Tar, dY3_Tar, dZ3_Tar, dX3_Obs, dY3_Obs, dZ3_Obs); //头晕、高血压、糖尿病患者调用该函数请慎重!
                //=========================================== 创建中间帧    == == == == == == == == == == == == == == == == == == == == == =
                //animationTrack.InsertKeyframe(keyframe2, animationTrack.KeyframeCount);
                animationTrack.InsertKeyframe(keyframe3, animationTrack.KeyframeCount);
                // Set The Animation Track Name
                animationTrack.Name = "Zoom Over Location";
                // Set Track Attachments
                animationTrack.AttachObject(globeCamera);
                animationTrack.ApplyToAllViewers = true;
                // Add The New Track To The Scene
                animationTracks.AddTrack(animationTrack);
                // Return The Newly Create Aninmation Track
            }
            catch { }
            return(animationTrack);
        }
Exemplo n.º 15
0
        private IPolygon CreateBox(IPoint centre, double orientation, double size, esriUnits units)
        {
            // Orientation is in degrees from east, counterclockwise
            // First point in the polygon will be on a face, at the orientation point
            // Four points on the corners will be at sqrt(2) * size,
            // at orientation+45, orientation+135, orientation+225 and orientation+315
            ISDUTExtension theExt = this.Extension;
            IPolygon theBox = new PolygonClass();

            ISpatialReference theWorkingReference = theExt.FocusMap.SpatialReference;
            theBox.SpatialReference = theWorkingReference;
            esriUnits theWorkingUnits = esriUnits.esriMeters;

            UnitConverter theConverter = new UnitConverterClass();
            double theSize = theConverter.ConvertUnits(size, units, theWorkingUnits);
            double theCornerDistance = Math.Sqrt(2) * theSize;

            IPoint theCentroid = this._Wellsite;
            theCentroid.Project(theWorkingReference);
            Debug.WriteLine("Box centroid X: " + theCentroid.X + "  Y: " + theCentroid.Y);

            IPointCollection thePtColl = (IPointCollection)theBox;
            object theMissing = Type.Missing;

            // Place the first point
            IPoint thePoint = new PointClass();
            thePoint.SpatialReference = theWorkingReference;
            double theAngle = orientation * Math.PI / 180;
            ((IConstructPoint2)thePoint).ConstructAngleDistance(theCentroid, theAngle, theSize);
            Debug.WriteLine("    First point X: " + thePoint.X + "  Y: " + thePoint.Y);
            thePtColl.AddPoint(thePoint, ref theMissing, ref theMissing);

            // Place the corners
            for (int i = 1; i <= 4; i++)
            {
                thePoint = new PointClass();
                thePoint.SpatialReference = theWorkingReference;
                theAngle =  (orientation - 45 + (i * 90)) * Math.PI / 180;
                ((IConstructPoint2)thePoint).ConstructAngleDistance(theCentroid, theAngle, theCornerDistance);
                Debug.WriteLine("    Corner " + i + " X: " + thePoint.X + "  Y: " + thePoint.Y);
                thePtColl.AddPoint(thePoint, ref theMissing, ref theMissing);
            }

            theBox.Close();
            return theBox;
        }
Exemplo n.º 16
0
        //定位
        private void button1_Click(object sender, EventArgs e)
        {
            //ESRI.ArcGIS.esriSystem.IUnitConverter unitConverter = (ESRI.ArcGIS.esriSystem.IUnitConverter)ServerContext.CreateObject("esriSystem.UnitConverter");

            //project raster
            //IUnitConverter iu = new esriUnits();

            IUnitConverter unitConverter = new UnitConverterClass();
            double dFittedBoundsWidthInches = unitConverter.ConvertUnits(-100, esriUnits.esriDecimalDegrees, esriUnits.esriMeters)/100;
            double dFittedBoundsWidthInchesy = unitConverter.ConvertUnits(40, esriUnits.esriDecimalDegrees, esriUnits.esriMeters)/100;
            //ui.ConvertUnits(10, esriUnits.esriMeters, esriUnits.esriMeters);
            //IPoint pPoint = new PointClass();
            //pPoint.X = -1000;
            //pPoint.Y = -1000;

            //IGeometry pGeometry;
            //pGeometry = (IGeometry)pPoint;

            //IMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbolClass();

            //axMapControl.FlashShape(pGeometry, 4, 100, pMarkerSymbol);

            IEnvelope pEnvelope = new EnvelopeClass();
            IPoint pPoint = new PointClass();

            //axMapControl.MapUnits = esriUnits.esriDecimalDegrees;
            //axMapControl.MapUnits = esriUnits.esriMeters; //米

               // esriUnits mapUnits = axMapControl.MapUnits;

            //axMapControl.MapUnits = esriUnits.esriDecimalDegrees;
            //pPoint.PutCoords(Convert.ToDouble(textBox1.Text), Convert.ToDouble(textBox2.Text));//该句中的txtlong,txtlat是输入经纬值的TextBox
            pPoint.X = Convert.ToDouble(textBox1.Text);
            pPoint.Y = Convert.ToDouble(textBox2.Text);
            pEnvelope = axMapControl.Extent;
            pEnvelope.CenterAt(pPoint);

            axMapControl.Extent = pEnvelope.Envelope;//前一段代码实现平移
            axMapControl.ActiveView.ScreenDisplay.UpdateWindow();
            axMapControl.FlashShape(pPoint as IGeometry);//此句实现闪烁(效果没有ArcMap中好, )
            //axMapControl.ActiveView.Extent = pEnvelope;
            //showAnnotationByScale();
        }
Exemplo n.º 17
0
        public override int Execute(string logfileName)
        {
            this.InitLogging(logfileName);
            this.LogMessage(this.Name + " QA test execution started.");

            int currentOid = -1;

            try
            {
                this.LogMessage(this.Name + " Parameters:");
                for (int i = 0; i < this.ParameterCount; i++)
                    this.LogMessage(this.get_ParameterText(i) + ": " + this.get_ParameterValue(i));

                this.ClearErrors();

                // Check the search radius
                int idx = this.FindParameter("search-radius");
                DoubleParameterInfo theInfo = (DoubleParameterInfo)this._params[idx];
                double theSearchRadius = (double)theInfo.ParamValue;

                if (theSearchRadius <= 0)
                {
                    this.LogMessage("Zero or negative value passed as search radius for " + this.Name + ". Stopping.");
                    return -1;
                }

                // Check the cluster tolerance
                idx = this.FindParameter("cluster-tolerance");
                theInfo = (DoubleParameterInfo)this._params[idx];
                double theCluster = (double)theInfo.ParamValue;

                if (theCluster >= theSearchRadius)
                {
                    this.LogMessage("Cluster tolerance equal to or larger than search radius for " + this.Name + ". Stopping.");
                    return -1;
                }

                // Convert them to metres
                idx = this.FindParameter("search-units");
                UnitsParameterInfo theUnitsParam = (UnitsParameterInfo)this._params[idx];
                esriUnits theUnits = theUnitsParam.ParamValueInUnits;
                IUnitConverter theConverter = new UnitConverterClass();
                theSearchRadius = theConverter.ConvertUnits(theSearchRadius, theUnits, esriUnits.esriMeters);
                theCluster = theConverter.ConvertUnits(theCluster, theUnits, esriUnits.esriMeters);

                // Get the canDefer/canExcept params
                idx = this.FindParameter(ParameterInfo.PARAM_CANDEFER);
                bool canDefer = (bool)((ParameterInfo)this._params[idx]).ParamValue;
                idx = this.FindParameter(ParameterInfo.PARAM_CANEXCEPT);
                bool canExcept = (bool)((ParameterInfo)this._params[idx]).ParamValue;

                // Loop through the layers
                for (int i = 0; i < this.LayerCount - 1; i++)
                {
                    IFeatureLayer theLayer1 = this.get_Layer(i);
                    if (this.SupportsGeometryType(theLayer1.FeatureClass.ShapeType) == false)
                        continue;

                    // Index the points in theLayer1
                    IDataset theDataset1 = (IDataset)theLayer1.FeatureClass;
                    IGeoDataset theGeoDS = (IGeoDataset)theDataset1;
                    IEnvelope theAOI = theGeoDS.Extent;
                    if (theAOI == null || theAOI.IsEmpty)
                        continue;

                    theAOI.Project(SpatialReferenceHelper.BCAlbersSpatialReference);
                    double theCellsize = theAOI.Width / 100;
                    this.LogMessage("Indexing features in " + theDataset1.Name + ". Cellsize (m): " + theCellsize);
                    PointCollectionIndex theIndex = new PointCollectionIndex(theCellsize);

                    IFeatureCursor theFCursor1 = null;
                    if (this.ConstrainToSelection)
                    {
                        ICursor theCursor = null;
                        IFeatureSelection theFSel = (IFeatureSelection)theLayer1;
                        theFSel.SelectionSet.Search(null, true, out theCursor);
                        theFCursor1 = (IFeatureCursor)theCursor;
                    }
                    else
                    {
                        theFCursor1 = theLayer1.Search(null, true);
                    }

                    IFeature theFeature1 = theFCursor1.NextFeature();
                    while (theFeature1 != null)
                    {
                        if (theFeature1.Shape != null && theFeature1.Shape.IsEmpty == false)
                        {
                            IPointCollection thePtColl = (IPointCollection)theFeature1.Shape;
                            for (int k = 0; k < thePtColl.PointCount; k++)
                            {
                                theIndex.AddPoint(new IndexPoint(theFeature1.OID, k, thePtColl.get_Point(k)));
                            }
                        }

                        theFeature1 = theFCursor1.NextFeature();
                    }

                    // Release the cursor
                    Marshal.ReleaseComObject(theFCursor1);
                    theFCursor1 = null;

                    if (theIndex.PointCount > 0)
                    {
                        // Use the index to analyze the other layers
                        for (int j = i+1; j < this.LayerCount; j++)
                        {
                            IFeatureLayer theLayer2 = this.get_Layer(j);
                            if (this.SupportsGeometryType(theLayer2.FeatureClass.ShapeType) == false)
                                continue;

                            IDataset theDataset2 = (IDataset)theLayer2.FeatureClass;
                            IFeatureCursor theFCursor2 = null;
                            if (this.ConstrainToSelection)
                            {
                                ICursor theCursor = null;
                                IFeatureSelection theFSel = (IFeatureSelection)theLayer2;
                                theFSel.SelectionSet.Search(null, true, out theCursor);
                                theFCursor2 = (IFeatureCursor)theCursor;
                            }
                            else
                            {
                                theFCursor2 = theLayer2.Search(null, true);
                            }

                            IFeature theFeature2 = theFCursor2.NextFeature();
                            while (theFeature2 != null)
                            {
                                if (theFeature2.Shape != null && theFeature2.Shape.IsEmpty == false)
                                {
                                    IGeometry theCopy = theFeature2.ShapeCopy;
                                    theCopy.Project(SpatialReferenceHelper.BCAlbersSpatialReference);
                                    IPointCollection thePtColl = (IPointCollection)theCopy;
                                    for (int k = 0; k < thePtColl.PointCount; k++)
                                    {
                                        // Find the closest point in the index. If it's less than
                                        // the search radius and larger than the cluster tolerance,
                                        // log as an error
                                        IPoint thePoint = thePtColl.get_Point(k);
                                        IndexPoint theIdxPoint = theIndex.get_ClosestPointWithinLimits(
                                            thePoint.X,
                                            thePoint.Y,
                                            theCluster,
                                            theSearchRadius);

                                        if (theIdxPoint != null)
                                        {
                                            // Build a straight line between the offending points
                                            IPolyline thePolyline = new PolylineClass();
                                            thePolyline.Project(SpatialReferenceHelper.BCAlbersSpatialReference);
                                            ((IPointCollection)thePolyline).AddPoint(thePoint, ref this._missing, ref this._missing);
                                            IPoint theOtherPoint = new PointClass();
                                            theOtherPoint.Project(SpatialReferenceHelper.BCAlbersSpatialReference);
                                            theOtherPoint.PutCoords(theIdxPoint.X, theIdxPoint.Y);
                                            ((IPointCollection)thePolyline).AddPoint(theOtherPoint, ref this._missing, ref this._missing);

                                            // Get the distance
                                            double dist = PointCollectionIndex.get_Distance(thePoint.X, thePoint.Y, theOtherPoint.X, theOtherPoint.Y);

                                            // Project to geographics for error reporting
                                            thePolyline.Project(SpatialReferenceHelper.GeographicReference);

                                            // Error point will be 1/2 way along line between points
                                            IPoint theErrorPoint = new PointClass();
                                            thePolyline.QueryPoint(esriSegmentExtension.esriNoExtension, 0.5, true, theErrorPoint);

                                            DataQualityError theError = new DataQualityError(this.Name, canDefer, canExcept);
                                            theError.Location = theErrorPoint;

                                            // If it's in the smallest 10% of the search radius, mark high severity
                                            // 50%, medium
                                            if (dist <= theSearchRadius / 10)
                                                theError.Severity = 1;
                                            else if (dist <= theSearchRadius / 2)
                                                theError.Severity = 2;
                                            else
                                                theError.Severity = 3;

                                            theError.Description = "Points almost but not quite co-located";

                                            ExtendedInfo theExtInfo = new ExtendedInfo();

                                            theExtInfo.AddProperty("Feature class 1", theDataset1.Name);
                                            theExtInfo.AddProperty("Feature class 2", theDataset2.Name);
                                            if (theLayer1.FeatureClass.HasOID)
                                                theExtInfo.AddProperty("Feature ID 1", theIdxPoint.SourceFeatureID.ToString());
                                            if (theLayer2.FeatureClass.HasOID)
                                                theExtInfo.AddProperty("Feature ID 2", theFeature2.OID.ToString());
                                            theExtInfo.AddProperty("Distance", String.Format("{0:0.## metres}", dist));
                                            theExtInfo.AddProperty("From point x", thePolyline.FromPoint.X.ToString());
                                            theExtInfo.AddProperty("From point y", thePolyline.FromPoint.Y.ToString());
                                            theExtInfo.AddProperty("To point x", thePolyline.ToPoint.X.ToString());
                                            theExtInfo.AddProperty("To point y", thePolyline.ToPoint.Y.ToString());

                                            theError.ExtendedData = theExtInfo.WriteXML();
                                            //this.LogMessage(theError.ExtendedData);
                                            this._errors.Add(theError);
                                        }
                                    }
                                }

                                theFeature2 = theFCursor2.NextFeature();
                            }
                        }
                    }
                }

                this.LogMessage("Number of errors found: " + this.ErrorCount);
                this.LogMessage("Test " + this.Name + " successful.");
            }
            catch (Exception ex)
            {
                this.LogMessage("Exception caught: \n" + ex.Message + "\n" + ex.StackTrace.ToString());
                this.LogMessage("id of the current polygon: " + currentOid);
                return -1;
            }
            finally
            {
                this.StopLogging();
            }

            return this.ErrorCount;
        }
Exemplo n.º 18
0
        public override int Execute(string logfileName)
        {
            this.InitLogging(logfileName);
            this.LogMessage(this.Name + " QA test execution started.");

            int currentOid = -1;
            bool bProblemsRunning = false;

            try
            {
                this.LogMessage(this.Name + " Parameters:");
                for (int i = 0; i < this.ParameterCount; i++)
                    this.LogMessage(this.get_ParameterText(i) + ": " + this.get_ParameterValue(i));

                this.ClearErrors();

                int index = this.FindParameter("search-radius");
                double searchRadius = Math.Abs((double)((ParameterInfo)this._params[index]).ParamValue);

                index = this.FindParameter("aspect-ratio-limit");
                double aspectRatio = Math.Abs((double)((ParameterInfo)this._params[index]).ParamValue);
                if (aspectRatio <= 1)
                {
                    aspectRatio = 10;
                    this.LogMessage("Segment length to distance ratio set under 1.0, using 10 instead.");
                }

                index = this.FindParameter(ParameterInfo.PARAM_CANDEFER);
                bool canDefer = (bool)((ParameterInfo)this._params[index]).ParamValue;
                index = this.FindParameter(ParameterInfo.PARAM_CANEXCEPT);
                bool canExcept = (bool)((ParameterInfo)this._params[index]).ParamValue;
                index = this.FindParameter("limit-neatline-index");
                bool limitNeatline = (bool)((ParameterInfo)this._params[index]).ParamValue;

                // Convert gap limits to metres
                UnitsParameterInfo theUnits = (UnitsParameterInfo)this._params[this.FindParameter("search-units")];
                IUnitConverter theConverter = new UnitConverterClass();
                searchRadius = theConverter.ConvertUnits(searchRadius, theUnits.ParamValueInUnits, esriUnits.esriMeters);

                IFeatureLayer theNeatlineLayer = this.NeatlineLayer;
                if (theNeatlineLayer == null)
                {
                    this.LogMessage("Missing valid neatline layer. Exiting Execute.");
                    bProblemsRunning = true;
                }
                else
                {
                    // Create index of neatline segments
                    this.LogMessage("Building neatline index");

                    // Calc cell size by taking some segment lengths
                    double sum = 0;
                    int segCount = 0;
                    IFeatureCursor theNLCursor = this.NeatlineLayer.Search(null, true);
                    IFeature theNeatline = theNLCursor.NextFeature();

                    while (theNeatline != null)
                    {
                        IGeometry theGeometry = theNeatline.Shape;
                        theGeometry.Project(SpatialReferenceHelper.BCAlbersSpatialReference);
                        ISegmentCollection theSegColl = (ISegmentCollection)theGeometry;
                        for (int i = 0; i < theSegColl.SegmentCount; i++)
                        {
                            sum += theSegColl.get_Segment(i).Length;
                            segCount++;
                        }
                        theNeatline = theNLCursor.NextFeature();
                        if (segCount > 100)
                            break;
                    }
                    Marshal.ReleaseComObject(theNLCursor);
                    theNLCursor = null;

                    double cellsize = (sum / segCount) * 5;
                    this.LogMessage("Cellsize: (" + sum + " / " + segCount + ") = " + cellsize);

                    // Determine the bounding env for the features to analyze
                    // If this is significantly smaller than the bounds of the neatline
                    // layer, this will save time building the cache
                    ISpatialFilter theSF = null;
                    if (limitNeatline)
                    {
                        IEnvelope theAOI = null;
                        for (int layerIdx = 0; layerIdx < this.LayerCount; layerIdx++)
                        {
                            IFeatureLayer theFLayer = this.get_Layer(layerIdx);
                            IFeatureClass theFClass = theFLayer.FeatureClass;
                            if (theFLayer != theNeatlineLayer
                                && this.SupportsGeometryType(theFClass.ShapeType))
                            {
                                if (this.ConstrainToSelection)
                                {
                                    IFeatureCursor theFCursor;
                                    ICursor theCursor;
                                    IFeatureSelection theFSel = (IFeatureSelection)theFLayer;
                                    theFSel.SelectionSet.Search(null, true, out theCursor);
                                    theFCursor = (IFeatureCursor)theCursor;
                                    IFeature theFeature = theFCursor.NextFeature();
                                    while (theFeature != null)
                                    {
                                        if (theFeature.Shape != null && theFeature.Shape.IsEmpty == false)
                                        {
                                            if (theAOI != null)
                                                theAOI.Union(theFeature.Shape.Envelope);
                                            else
                                                theAOI = theFeature.Shape.Envelope;
                                        }
                                        theFeature = theFCursor.NextFeature();
                                    }
                                    Marshal.ReleaseComObject(theFCursor);
                                }
                                else
                                {
                                    if (theAOI != null)
                                        theAOI.Union(theFLayer.AreaOfInterest);
                                    else
                                        theAOI = theFLayer.AreaOfInterest;
                                }
                            }
                        }

                        theSF = new SpatialFilterClass();
                        theSF.Geometry = theAOI;
                        theSF.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    }

                    SegmentCollectionIndex theIndex = new SegmentCollectionIndex(cellsize);
                    theNLCursor = this.NeatlineLayer.Search(theSF, true);
                    theNeatline = theNLCursor.NextFeature();
                    while (theNeatline != null)
                    {
                        ISegmentCollection theSegColl = theNeatline.Shape as ISegmentCollection;
                        for (int i = 0; i < theSegColl.SegmentCount; i++)
                        {
                            IndexSegment theSegment = new IndexSegment(theNeatline.OID, theSegColl.get_Segment(i));
                            theIndex.AddSegment(theSegment);
                        }
                        theNeatline = theNLCursor.NextFeature();
                    }

                    for (int layerIdx = 0; layerIdx < this.LayerCount; layerIdx++)
                    {
                        IFeatureLayer theFLayer = this.get_Layer(layerIdx);
                        IFeatureClass theFClass = theFLayer.FeatureClass;
                        IDataset theDataset = (IDataset)theFClass;

                        if (theFLayer != theNeatlineLayer
                            && this.SupportsGeometryType(theFClass.ShapeType))
                        {
                            this.LogMessage("Detecting neatline artifacts in featureclass " + theDataset.Name);

                            int nFeatures = 0;

                            IFeatureCursor theFCursor = null;
                            IFeatureSelection theFSel = (IFeatureSelection)theFLayer;

                            if (this.ConstrainToSelection)
                            {
                                this.LogMessage("Constraining analysis to selected features.");
                                ICursor theCursor;
                                theFSel.SelectionSet.Search(null, true, out theCursor);
                                theFCursor = (IFeatureCursor)theCursor;
                                nFeatures = theFSel.SelectionSet.Count;
                            }
                            else
                            {
                                theFCursor = theFClass.Search(null, true);
                                nFeatures = theFClass.FeatureCount(null);
                            }

                            this.LogMessage("Number of features to process: " + nFeatures);

                            int count = 0;
                            int countIncrement = Math.Max(1, nFeatures / 10);

                            IFeature theFeature = theFCursor.NextFeature();

                            while (theFeature != null)
                            {
                                if (theFeature.HasOID)
                                    currentOid = theFeature.OID; // for error trapping and debugging

                                ArrayList theList = this.ProcessFeature(theFeature, theIndex,
                                    searchRadius, aspectRatio, canDefer, canExcept);

                                if (theList != null)
                                {
                                    foreach (DataQualityError dqe in theList)
                                        this._errors.Add(dqe);
                                }

                                if (++count % countIncrement == 0)
                                {
                                    this.LogMessage("Processed " + count + " polygons...");
                                }
                                theFeature = theFCursor.NextFeature();
                            }

                            Marshal.ReleaseComObject(theFCursor);
                        }
                    }
                }

                this.LogMessage("Number of errors found: " + this.ErrorCount);
                this.LogMessage("Test " + this.Name + " successful.");
            }
            catch (Exception ex)
            {
                this.LogMessage("Exception caught: \n" + ex.Message + "\n" + ex.StackTrace.ToString());
                this.LogMessage("id of the current polygon: " + currentOid);
                return -1;
            }
            finally
            {
                this.StopLogging();
            }

            if (bProblemsRunning)
                return -1;

            return this.ErrorCount;
        }
 /// <summary>
 /// 将输入的数据单位转化为米
 /// </summary>
 /// <param name="dValue"></param>
 /// <param name="outUnits"></param>
 /// <returns></returns>
 public double UnitsConvertToMeters(double dValue,esriUnits outUnits)
 {
     IUnitConverter unitConverter = new UnitConverterClass();
     double newValue = unitConverter.ConvertUnits(dValue, esriUnits.esriMeters, outUnits);
     return newValue;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Converts the unit.
        /// </summary>
        /// <param name="dValue">The d value.</param>
        /// <param name="inUnits">The in units.</param>
        /// <param name="outUnits">The out units.</param>
        /// <returns>System.Double.</returns>
        public static double ConvertUnit(double dValue, esriUnits inUnits, esriUnits outUnits)
        {
            IUnitConverter unitConverter = new UnitConverterClass();

            return(unitConverter.ConvertUnits(dValue, inUnits, outUnits));
        }
Exemplo n.º 21
0
        //双击则创建该线,并弹出缓冲窗体
        public override void OnDblClick()
        {
            //获取折线 并获取当前视图的屏幕显示
            if (m_pNewPolygonFeedback == null)
            {
                return;
            }
            IPolygon pPolygon = m_pNewPolygonFeedback.Stop();

            m_pNewPolygonFeedback = null;

            //不存在,为空。尺寸不够均退出
            if (pPolygon == null || pPolygon.IsEmpty)
            {
                return;
            }
            //xisheng 判断面积的高度,宽度时需判断是什么单位,若是经纬度则需要转换。20111220
            double        w      = pPolygon.Envelope.Width;
            double        h      = pPolygon.Envelope.Height;
            UnitConverter conver = new UnitConverterClass();

            if (m_MapControl.Map.MapUnits == esriUnits.esriDecimalDegrees)
            {
                w = conver.ConvertUnits(w, esriUnits.esriDecimalDegrees, esriUnits.esriMeters);
                h = conver.ConvertUnits(h, esriUnits.esriDecimalDegrees, esriUnits.esriMeters);
            }
            if (w < 0.01 || h < 0.01)
            {
                return;
            }
            //xisheng 20111220 end *********************************************************

            //创建Topo对象,简化后统一空间参考
            ITopologicalOperator pTopo = (ITopologicalOperator)pPolygon;

            pTopo.Simplify();
            pPolygon.Project(m_MapControl.Map.SpatialReference);

            if (m_frmQuery == null)
            {
                m_frmQuery             = new frmQuery(m_MapControl, m_enumQueryMode);
                m_frmQuery.Owner       = m_mainFrm;
                m_frmQuery.FormClosed += new FormClosedEventHandler(frmQuery_FormClosed);
            }
            if (this.WriteLog)
            {
                Plugin.LogTable.Writelog("面缓冲查询");//xisheng 日志记录 0928;
            }
            //清除上次的所有元素
            (m_MapControl.Map as IGraphicsContainer).DeleteAllElements();
            m_frmBufferSet = new frmBufferSet(pPolygon as IGeometry, m_MapControl.Map, m_frmQuery);
            IGeometry pGeometry = m_frmBufferSet.GetBufferGeometry();

            if (pGeometry == null || m_frmBufferSet.Res == false)
            {
                return;
            }
            // m_frmQuery.Show();
            ///ZQ 20111119  modify
            //m_frmQuery.FillData(m_MapControl.ActiveView.FocusMap, pGeometry,m_frmBufferSet.pesriSpatialRelEnum);
            _QueryBar.m_pMapControl = m_MapControl;
            _QueryBar.EmergeQueryData(m_MapControl.ActiveView.FocusMap, pGeometry, m_frmBufferSet.pesriSpatialRelEnum);
            try
            {
                DevComponents.DotNetBar.Bar pBar = _QueryBar.Parent.Parent as DevComponents.DotNetBar.Bar;
                if (pBar != null)
                {
                    pBar.AutoHide = false;
                    //pBar.SelectedDockTab = 1;
                    int tmpindex = pBar.Items.IndexOf("dockItemDataCheck");
                    pBar.SelectedDockTab = tmpindex;
                }
            }
            catch
            { }
        }
Exemplo n.º 22
0
        public static double GetGlobeElevation(IGlobeDisplay globeDisplay, double longitude, double latitude, bool maxResolution)
        {
            IUnitConverter unitConverter = new UnitConverterClass();

            double doubleZ = 0;
            globeDisplay.GetSurfaceElevation(longitude, latitude, maxResolution, out doubleZ);
            return unitConverter.ConvertUnits(doubleZ, esriUnits.esriMeters, globeDisplay.Globe.GlobeUnits);
        }
Exemplo n.º 23
0
        private void GenerateReportOfSegment(double BegMeasure, double endMeasure, string outFile)
        {
            if (checkBoxRotateMap.Checked)
            {
                IFeatureLayer pCenterlineLayer    = null;
                string        pCenterlineFileName = comboBoxExCenterline.SelectedItem.ToString();
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pCenterlineFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                }
                IFeatureClass pCenterlineFC = pCenterlineLayer.FeatureClass;
                try
                {
                    IFeatureCursor pCurcor  = pCenterlineFC.Search(null, false);
                    IFeature       pFeature = pCurcor.NextFeature();
                    IGeometry      pGeo     = pFeature.Shape;
                    IMSegmentation pMS      = pGeo as IMSegmentation;
                    double         minM     = pMS.MMin;
                    double         maxM     = pMS.MMax;
                    BegMeasure = BegMeasure < minM ? minM : BegMeasure;
                    endMeasure = endMeasure > maxM ? maxM : endMeasure;
                    IPoint begPt = pMS.GetPointsAtM(BegMeasure, 0).Geometry[0] as IPoint;
                    IPoint endPt = pMS.GetPointsAtM(endMeasure, 0).Geometry[0] as IPoint;

                    ISpatialReference sourcePrj;
                    sourcePrj = pCenterlineFC.Fields.get_Field(pCenterlineFC.FindField(pCenterlineFC.ShapeFieldName)).GeometryDef.SpatialReference;
                    ISpatialReference targetPrj = pMapcontrol.Map.SpatialReference;
                    IPoint            begPtPrj;
                    IPoint            endPtPrj;
                    begPt.Project(targetPrj);
                    endPt.Project(targetPrj);
                    begPtPrj = begPt;
                    endPtPrj = endPt;
                    IActiveView pView = this.pMapcontrol.Map as IActiveView;
                    pView.ScreenDisplay.DisplayTransformation.Rotation = 0;
                    double widthHeightR = (((double)pView.ExportFrame.right - pView.ExportFrame.left) / ((double)pView.ExportFrame.bottom - pView.ExportFrame.top));
                    // Dim fw As New FileWindow(begPt, endPt, widthHeightR)
                    MCenterlineUtil fw = new MCenterlineUtil(begPtPrj, endPtPrj, widthHeightR);

                    fw.FitActiveViewTo(pView, true);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pCurcor);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }


            #region //导出arcmap 地图 export mapfram

            IPageLayout _PageLayout = this.pPageLayoutControl.PageLayout;
            SizeF       m_PageSize  = new SizeF();
            double      width;
            double      hight;



            _PageLayout.Page.QuerySize(out width, out hight);
            m_PageSize.Width  = Convert.ToSingle(width);
            m_PageSize.Height = Convert.ToSingle(hight);
            IUnitConverter pUConvert = new UnitConverterClass();
            esriUnits      ut        = _PageLayout.Page.Units;
            float          pageUnitToInchUnitScale = (float)pUConvert.ConvertUnits(1, ut, esriUnits.esriInches);



            var layerOutPageSize = m_PageSize;
            var outputDPI        = 300;
            int BandHeadWidth    = 40;

            var originalActiveView = _PageLayout as IActiveView;
            var activeView         = _PageLayout as IActiveView;
            originalActiveView.Refresh();
            var avEvents = _PageLayout as IActiveViewEvents;

            float centerX = layerOutPageSize.Width / 2;
            float centerY = layerOutPageSize.Height / 2;

            var backGroundEnv = new Envelope() as IEnvelope;
            backGroundEnv.PutCoords(0, 0, layerOutPageSize.Width, layerOutPageSize.Height);

            activeView.Extent = backGroundEnv;
            //System.Threading.Thread.Sleep(2000);

            IExport pExporter = new ExportPDF() as IExport;
            pExporter.ExportFileName = outFile;
            pExporter.Resolution     = outputDPI;

            var pExPdf = pExporter as IExportPDF;
            pExPdf.Compressed       = true;
            pExPdf.ImageCompression = esriExportImageCompression.esriExportImageCompressionDeflate;

            var screenResolution = GetCurrentScreenResolution();
            var outputResolution = outputDPI;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = (int)(activeView.ExportFrame.right * outputResolution / screenResolution) + 1;
            exportRECT.bottom = (int)(activeView.ExportFrame.bottom * outputResolution / screenResolution) + 1;

            var envelope = new Envelope() as IEnvelope;
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            pExporter.PixelBounds = envelope;

            var hDC = pExporter.StartExporting();
            activeView.Output(hDC, outputDPI, exportRECT, backGroundEnv, null);

            pExporter.FinishExporting();
            pExporter.Cleanup();
            // MessageBox.Show("Export finished.");
            #endregion

            #region  //根据中线图层生成剖面图
            System.Drawing.Point LastBottomLeftPoint = new System.Drawing.Point();
            int         bandwidth = 0;
            PdfGraphics pGraphics = null;

            IFeatureLayer pCenterlinePointLayer = null;
            string        centerlinePointnName  = cboBoxPointLayer.SelectedItem.ToString();

            for (int i = 0; i < pMapcontrol.LayerCount; i++)
            {
                if (centerlinePointnName == pMapcontrol.get_Layer(i).Name)
                {
                    pCenterlinePointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
            }
            IQueryFilter pQF = null;
            DataTable    centerlinePointTable = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pCenterlinePointLayer.FeatureClass as ITable, pQF);
            chartControl1.Series.Clear();
            Series         series  = new Series("高程", ViewType.Line);
            Series         series2 = new Series("埋深", ViewType.Line);
            SecondaryAxisY myAxisY = new SecondaryAxisY("埋深");

            foreach (DataRow r in centerlinePointTable.Rows)
            {
                double m; double z; double underz;
                m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                if (m < BegMeasure || m > endMeasure)
                {
                    continue;
                }
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineZField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineZField]);
                    series.Points.Add(new SeriesPoint(m, z));
                }
                // if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r["管道埋深("] != DBNull.Value)
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineBuryDepthField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineBuryDepthField]);
                    series2.Points.Add(new SeriesPoint(m, z));
                }
            }

            chartControl1.Series.Add(series);
            chartControl1.Series.Add(series2);
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesX.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Add(myAxisY);
            ((LineSeriesView)series2.View).AxisY = myAxisY;
            ((LineSeriesView)series.View).AxisY  = ((XYDiagram)chartControl1.Diagram).AxisY;
            series.ChangeView(ViewType.Line);
            ((XYDiagram)chartControl1.Diagram).AxisY.WholeRange.Auto = true;
            myAxisY.WholeRange.Auto = true;
            series2.ChangeView(ViewType.Line);
            myAxisY.Tickmarks.Visible      = true;
            myAxisY.Tickmarks.MinorVisible = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.AutoSideMargins  = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SideMarginsValue = 0;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SetMinMaxValues(BegMeasure, endMeasure);
            series.ArgumentScaleType = ScaleType.Numerical;

            int ProfileMapHight = 8;

            #endregion


            #region export chartcontrol
            IGraphicsContainer pGC = _PageLayout as IGraphicsContainer;
            pGC.Reset();
            IElement pE = pGC.Next();
            while (pE != null)
            {
                if (pE is IMapFrame)
                {
                    // framgeo related to _PageLayout.Page pagesize, 8.5 x 11, inch
                    IEnvelope framgeo    = pE.Geometry.Envelope as IEnvelope;
                    float     defaultDPI = PdfGraphics.DefaultDpi;
                    double    x          = defaultDPI * framgeo.LowerLeft.X * pageUnitToInchUnitScale;
                    double    y          = defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1;

                    bandwidth = (int)(defaultDPI * (framgeo.Width * pageUnitToInchUnitScale));

                    LastBottomLeftPoint.X = (int)x;
                    LastBottomLeftPoint.Y = (int)y;

                    chartControl1.Size = new System.Drawing.Size((int)(framgeo.Width * pageUnitToInchUnitScale * defaultDPI), (int)(ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                    Image  img = null;
                    Bitmap bmp = null;
                    // Create an image of the chart.
                    ImageFormat format = ImageFormat.Png;
                    using (MemoryStream s = new MemoryStream())
                    {
                        chartControl1.ExportToImage(s, format);
                        img = Image.FromStream(s);
                        bmp = new Bitmap(img);
                        bmp.SetResolution(300, 300);
                    }

                    using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
                    {
                        processor.LoadDocument(outFile);
                        PdfDocument  pd     = processor.Document;
                        PdfPage      page   = pd.Pages[0];
                        PdfRectangle pdfrec = page.MediaBox;
                        // RectangleF rf = new RectangleF(0, 0, Convert.ToSingle(pdfrec.Width) * 96 / 72, Convert.ToSingle(pdfrec.Height) * 96 / 72);
                        // Create and draw PDF graphics.
                        using (pGraphics = processor.CreateGraphics())
                        {
                            PdfGraphics graph = pGraphics;

                            Pen defaultPen = new Pen(Color.Black);
                            defaultPen.Width = 1;
                            graph.DrawImage(bmp, new RectangleF((float)x, (float)y, (float)framgeo.Width * pageUnitToInchUnitScale * defaultDPI, (float)ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                            // draw map head.
                            RectangleF MapheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                    (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.UpperLeft.Y) * pageUnitToInchUnitScale),
                                                                    (float)(int)(BandHeadWidth),
                                                                    (float)(int)(defaultDPI * framgeo.Height * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, MapheadRect);
                            //draw head text
                            RectangleF      rF  = new RectangleF(0, 0, (float)MapheadRect.Height, (float)BandHeadWidth);
                            PdfStringFormat psf = new PdfStringFormat(PdfStringFormat.GenericDefault);
                            psf.Alignment     = PdfStringAlignment.Center;
                            psf.LineAlignment = PdfStringAlignment.Center;
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            System.Drawing.Font textfont = new System.Drawing.Font("仿宋", 6F);
                            graph.TranslateTransform((float)(MapheadRect.Left), (float)(MapheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("地图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            // draw chart head
                            RectangleF ChartheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                      (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1),
                                                                      (float)(int)(BandHeadWidth),
                                                                      (float)(int)(defaultDPI * ProfileMapHight * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, ChartheadRect);
                            //draw head text
                            rF = new RectangleF(0, 0, (float)ChartheadRect.Height, (float)BandHeadWidth);
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            graph.TranslateTransform((float)(ChartheadRect.Left), (float)(ChartheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("剖面图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            LastBottomLeftPoint.Y = (int)ChartheadRect.Bottom;
                            //double beginM = -999; double endM = -999;
                            //GetIMUBeginEndMeasure(ref beginM, ref endM);
                            double beginM = BegMeasure;
                            double endM   = endMeasure;
                            for (int i = 0; i < listBoxDrawBandFields.Items.Count; i++)
                            {
                                string fieldname = listBoxDrawBandFields.Items[i].ToString();
                                band   b         = new band();
                                b.BandName    = fieldname;
                                b.pdfGC       = pGraphics;
                                b.BandWidth   = (int)bandwidth;
                                b.headFont    = labelbiaotou.Font;
                                b.ContentFont = labelNeirong.Font;
                                System.Drawing.Point pt = new System.Drawing.Point();
                                pt.X = LastBottomLeftPoint.X;
                                pt.Y = LastBottomLeftPoint.Y;
                                b.BandTopLeftLocation = pt;

                                b.BeginM = beginM;
                                b.EndM   = endM;
                                //b.bandData = new List<Tuple<double, string>>();
                                //for (int j = 0; j < 6; j++)
                                //{
                                //    double m = j * 500;
                                //    string txt = "异常2";
                                //    Tuple<double, string> t = new Tuple<double, string>(m,txt);
                                //    b.bandData.Add(t);
                                //}
                                b.bandData = GetPDFBandData(fieldname);
                                b.Draw();
                                LastBottomLeftPoint.Y += (int)b.BandHight;
                            }
                            // graph.DrawImage(img, rf);
                            graph.AddToPageForeground(page);
                            // Render a page with graphics.
                            //processor.RenderNewPage(PdfPaperSize.Letter, graph);
                            processor.SaveDocument(outFile);
                        }
                    }
                    break;
                }
                pE = pGC.Next();
            }
            #endregion
        }
Exemplo n.º 24
0
        public override int Execute(string logfileName)
        {
            this.InitLogging(logfileName);
            this.LogMessage(this.Name + " QA test execution started.");

            bool bProblemsRunning = false;

            int currentOid = -1;
            try
            {

                this.LogMessage(this.Name + " Parameters:");
                for (int i = 0; i < this.ParameterCount; i++)
                    this.LogMessage(this.get_ParameterText(i) + ": " + this.get_ParameterValue(i));

                this.ClearErrors();

                for (int layerIdx = 0; layerIdx < this.LayerCount; layerIdx++)
                {
                    IFeatureLayer theFLayer = this.get_Layer(layerIdx);
                    IFeatureClass theFClass = theFLayer.FeatureClass;
                    IDataset theDataset = (IDataset)theFClass;

                    if (!this.SupportsGeometryType(theFClass.ShapeType))
                    {
                        this.LogMessage("Overlap detector does not support the geometry type in featureclass " + theDataset.Name);
                        bProblemsRunning = true;
                    }
                    else if (theFClass.FeatureDataset == null)
                    {
                        this.LogMessage("Featureclass " + theDataset.Name + " is not in a feature dataset");
                        bProblemsRunning = true;
                    }
                    else
                    {
                        this.LogMessage("Looking for topology with overlap rule including featureclass " + theDataset.Name);

                        ITopology theTopology = null;
                        ArrayList theTRules = new ArrayList();
                        ITopologyRule theTopoRule = null;
                        IEnumDataset theDatasetEnum = theFClass.FeatureDataset.Subsets;

                        IDataset theSiblingDS = theDatasetEnum.Next();
                        while (theSiblingDS != null)
                        {
                            if (theSiblingDS.Type == esriDatasetType.esriDTTopology)
                            {
                                // Look for a gap rule featuring theFClass
                                theTopology = (ITopology)theSiblingDS;
                                ITopologyRuleContainer theTRContainer = (ITopologyRuleContainer)theTopology;
                                IEnumRule theRules = theTRContainer.get_RulesByClass(theFClass.FeatureClassID);

                                theTopoRule = (ITopologyRule)theRules.Next();
                                while (theTopoRule != null)
                                {
                                    if (theTopoRule.TopologyRuleType == esriTopologyRuleType.esriTRTAreaNoOverlap)
                                        theTRules.Add(theTopoRule);
                                    theTopoRule = (ITopologyRule)theRules.Next();
                                }
                            }
                            theSiblingDS = theDatasetEnum.Next();
                        }

                        if (theTopology == null || theTRules.Count == 0)
                        {
                            this.LogMessage("Featureclass " + theDataset.Name + " is not part of an Overlap topology rule");
                            bProblemsRunning = true;
                            continue;
                        }

                        if (this.ValidateTopology(theTopology) == false)
                        {
                            this.LogMessage("The topology " + ((IDataset)theTopology).Name + " could not be validated");
                            bProblemsRunning = true;
                            continue;
                        }

                        if (theTopology.State == esriTopologyState.esriTSAnalyzedWithErrors)
                        {
                            this.LogMessage("Processing overlap errors in featureclass " + theDataset.Name
                                + " as it relates to Topology " + ((IDataset)theTopology).Name);

                            IErrorFeatureContainer theTopoErrorContainer = (IErrorFeatureContainer)theTopology;

                            int count = 0;
                            int countIncrement = 500;

                            DoubleParameterInfo theParam = (DoubleParameterInfo)this._params[this.FindParameter("ignore-overlap-larger-than")];
                            double maxOverlap = (double)theParam.ParamValue;
                            theParam = (DoubleParameterInfo)this._params[this.FindParameter("ignore-overlap-smaller-than")];
                            double minOverlap = (double)theParam.ParamValue;

                            // Convert gap limits to metres
                            UnitsParameterInfo theUnits = (UnitsParameterInfo)this._params[this.FindParameter("overlap-units")];
                            IUnitConverter theConverter = new UnitConverterClass();
                            maxOverlap = theConverter.ConvertUnits(maxOverlap, theUnits.ParamValueInUnits, esriUnits.esriMeters);
                            minOverlap = theConverter.ConvertUnits(minOverlap, theUnits.ParamValueInUnits, esriUnits.esriMeters);

                            for (int j = 0; j < theTRules.Count; j++)
                            {
                                theTopoRule = (ITopologyRule)theTRules[j];

                                this.LogMessage("Processing rule " + (j+1) + " of " + theTRules.Count);

                                string theSubtypeName = "";
                                if (theFClass is ISubtypes && ((ISubtypes)theFClass).HasSubtype)
                                {
                                    IEnumSubtype theSubtypes = ((ISubtypes)theFClass).Subtypes;
                                    int theValue;
                                    string theLabel = theSubtypes.Next(out theValue);
                                    while (theLabel.Length > 0)
                                    {
                                        if (theValue == theTopoRule.OriginSubtype)
                                        {
                                            theSubtypeName = theLabel;
                                            break;
                                        }
                                        theLabel = theSubtypes.Next(out theValue);
                                    }
                                }

                                IGeoDataset theGeoDS = (IGeoDataset)theTopology;
                                IEnumTopologyErrorFeature theTopoErrors = theTopoErrorContainer.get_ErrorFeatures(theGeoDS.SpatialReference, theTopoRule, null, true, false);
                                ITopologyErrorFeature theTopoErrorFeature = theTopoErrors.Next();
                                while (theTopoErrorFeature != null)
                                {
                                    currentOid = theTopoErrorFeature.ErrorID;

                                    // Analysis here
                                    ArrayList theList = ProcessFeature(
                                        theTopoErrorFeature,
                                        theDataset,
                                        theSubtypeName,
                                        maxOverlap,
                                        minOverlap);

                                    if (theList != null)
                                    {
                                        foreach (DataQualityError dqe in theList)
                                            this._errors.Add(dqe);
                                    }

                                    if (++count % countIncrement == 0)
                                    {
                                        this.LogMessage("Processed " + count + " topology errors...");
                                    }

                                    theTopoErrorFeature = theTopoErrors.Next();
                                }
                            }
                        }
                        else
                        {
                            this.LogMessage("Topology has no errors");
                        }
                    }
                }

                this.LogMessage("Number of errors found: " + this.ErrorCount);
                this.LogMessage("Test " + this.Name + " successful.");
            }
            catch (Exception ex)
            {
                this.LogMessage("Exception caught: \n" + ex.Message + "\n" + ex.StackTrace.ToString());
                this.LogMessage("id of the current polygon: " + currentOid);
                return -1;
            }
            finally
            {
                this.StopLogging();
            }

            if (bProblemsRunning)
                return -1;

            return this.ErrorCount;
        }
 public double getLinearConversion(IProjectedCoordinateSystem prjSys)
 {
     IUnitConverter converter = new UnitConverterClass();
     ILinearUnit linearUnit = prjSys.CoordinateUnit;
     double meter = linearUnit.MetersPerUnit;
     double unitToFoot = converter.ConvertUnits(meter, esriUnits.esriMeters, esriUnits.esriFeet);
     return unitToFoot;
 }
Exemplo n.º 26
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (Button == 2)
                return;
            IPoint pt = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            pt = GIS.GraphicEdit.SnapSetting.getSnapPoint(pt);
            IGraphicsContainer g = m_hookHelper.ActiveView.GraphicsContainer;
            IEnvelope pEnvBounds = null;

            //��ȡ��һ�ι켣�ߵķ�Χ,�Ա�ȷ��ˢ�·�Χ
            try
            {
                if (m_TraceLine != null)
                {
                    m_TraceLine.QueryEnvelope(pEnvBounds);
                    pEnvBounds.Expand(4, 4, true); //���ο�����������4��(����2������),Ŀ����Ϊ�˱�֤�г����ˢ������
                }
                else
                    pEnvBounds = m_hookHelper.ActiveView.Extent;
            }
            catch
            {
                pEnvBounds = m_hookHelper.ActiveView.Extent;
            }

            #region �������
            if (m_NewLineFeedback == null)
            {
                //�Ƴ�element
                RemoveElements();
                //ˢ��
                m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                Application.DoEvents();

                m_NewLineFeedback = new NewLineFeedbackClass();
                m_NewLineFeedback.Display = m_hookHelper.ActiveView.ScreenDisplay;
                //�����ȵõ�symbol,������symbol
                ISimpleLineSymbol simpleLineSymbol = m_NewLineFeedback.Symbol as ISimpleLineSymbol;
                simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
                simpleLineSymbol.Width = 2;
                simpleLineSymbol.Color = TransColorToAEColor(Color.Blue);

                m_NewLineFeedback.Start(pt);
            }
            else
            {
                m_NewLineFeedback.AddPoint(pt);
            }

            if (m_ptColl == null)
            {
                m_ptColl = new PolylineClass();
            }
            //��¼�ڵ�
            object obj = Type.Missing;
            m_ptColl.AddPoint(pt, ref obj, ref obj);

            #endregion

            #region ���ƽ��

            try
            {
                IElement vertexElement = createElement_x(pt);
                //
                g = m_hookHelper.ActiveView as IGraphicsContainer;

                //g.AddElement(vertexElement, 0);
                //g.MoveElementToGroup(vertexElement, m_VertexElement);

                m_VertexElement.AddElement(vertexElement);
                //ˢ��
                m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, vertexElement, pEnvBounds);

            }
            catch
            { }
            #endregion

            try
            {
                if (m_ptColl.PointCount >= 2)
                {
                    IPoint fromPt = m_ptColl.get_Point(m_ptColl.PointCount - 2); //�����ڶ�����
                    IPoint toPt = m_ptColl.get_Point(m_ptColl.PointCount - 1); //����һ����
                    ILine line = new LineClass();
                    line.PutCoords(fromPt, toPt);

                    #region ���ƹ켣��

                    try
                    {
                        object missing = Type.Missing;
                        ISegmentCollection segColl = new PolylineClass();
                        segColl.AddSegment(line as ISegment, ref missing, ref missing);
                        IElement traceElement = createElement_x(segColl as IPolyline);
                        //
                        g = m_hookHelper.ActiveView as IGraphicsContainer;

                        //g.AddElement(traceElement, 0);
                        //g.MoveElementToGroup(traceElement, m_TraceElement);

                        m_TraceElement.AddElement(traceElement);

                        m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, traceElement, pEnvBounds);

                    }
                    catch
                    { }
                    #endregion

                    #region ���㵥�ߵij���,���������ʾ�ڵ����е�ƫ������
                    try
                    {
                        double angle = line.Angle;
                        if ((angle > (Math.PI / 2) && angle < (Math.PI)) || (angle > -Math.PI && angle < -(Math.PI / 2))) // ����90��С�ڵ���180
                            angle += Math.PI;

                        //��ע��Yֵƫ����
                        double d_OffsetY = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.FromPoints(9);

                        //��ע��

                        double d_CenterX = (fromPt.X + toPt.X) / 2;
                        double d_CenterY = (fromPt.Y + toPt.Y) / 2 + d_OffsetY; //����ƫ��

                        IPoint labelPt = new PointClass();
                        labelPt.PutCoords(d_CenterX, d_CenterY);
                        IUnitConverter unitConverter = new UnitConverterClass();
                        double segmentLength = unitConverter.ConvertUnits(line.Length, _MsgInfo.inUnit.pUnit, _MsgInfo.outUnit.pUnit);
                        ITextElement txtElement = CreateTextElement(segmentLength.ToString("0.00"));

                        IElement labelelement = txtElement as IElement;
                        labelelement.Geometry = labelPt;
                        object oElement = (object)labelelement;

                        //���ݽǶ���ת
                        TransformByRotate(ref oElement, labelPt, angle);

                        ////��ӵ�GraphicsContainer
                        //g.AddElement(labelelement, 0);

                        ////�Ƶ�m_LabelElement����
                        //g.MoveElementToGroup(labelelement, m_LabelElement);

                        //��ӵ���
                        m_LabelElement.AddElement(labelelement);

                        //ˢ��

                        m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, labelelement, pEnvBounds);
                    }
                    catch
                    { }
                    #endregion
                }

            }
            catch
            { }

            _MsgInfo.LineResultChange();
        }
Exemplo n.º 27
0
        public static IAnimationTrack CreateZoomOverLocationAnimation(IGlobeDisplay globeDisplay, double doubleX, double doubleY, double doubleAltitide)
        {
            // Set Mouse Cursor
            //IMouseCursor mouseCursor = new MouseCursorClass();
            //mouseCursor.SetCursor(2);
            // QI to GlobeDisplayRendering Interface
            IGlobeDisplayRendering globeDisplayRendering = (IGlobeDisplayRendering)
                    globeDisplay;
            // Get Elevation Multiplication Factor
            IUnitConverter unitConverter = new UnitConverterClass();
            // Get GlobeDisplay and Camera
            IGlobe globe = globeDisplay.Globe;
            IAnimationTracks animationTracks = (IAnimationTracks)globe;

            IGlobeCamera globeCamera = (IGlobeCamera)globeDisplay.ActiveViewer.Camera;
            // Create New Animation Track
            IAnimationTrack animationTrack = new AnimationTrackClass();
            try
            {
                IAnimationType animationType = new AnimationTypeGlobeCameraClass();
                animationTrack.AnimationType = animationType;
                // Create First KeyFrame At Current Location
                IKeyframe keyframe1 = new GlobeCameraKeyframeClass();
                keyframe1.CaptureProperties((IScene)globe, globeCamera);
                animationTrack.InsertKeyframe(keyframe1, animationTrack.KeyframeCount);
                // Create Last KeyFrame Over Desired Location
                IKeyframe keyframe3 = new GlobeCameraKeyframeClass();
                keyframe3.set_PropertyValueInt(0, 0);
                keyframe3.set_PropertyValueDouble(1, doubleY);
                keyframe3.set_PropertyValueDouble(2, doubleX);
                keyframe3.set_PropertyValueDouble(3, -1d *
                                                   unitConverter.ConvertUnits(globeDisplayRendering.GlobeRadius, esriUnits.esriMeters,
                                                           globe.GlobeUnits)); // (globeDisplayRendering.GlobeRadius / -1000));
                keyframe3.set_PropertyValueDouble(4, doubleY);
                keyframe3.set_PropertyValueDouble(5, doubleX);
                keyframe3.set_PropertyValueDouble(6, doubleAltitide);
                keyframe3.set_PropertyValueDouble(7, 30);
                keyframe3.set_PropertyValueDouble(8, 0);

                #region 获取第一帧和第三帧的参数
                double dX1_Tar, dY1_Tar, dZ1_Tar, dX1_Obs, dY1_Obs, dZ1_Obs;
                GetParametersFromKeyFrame(keyframe1, out dX1_Tar, out dY1_Tar, out dZ1_Tar, out dX1_Obs, out dY1_Obs, out dZ1_Obs);
                double dX3_Tar, dY3_Tar, dZ3_Tar, dX3_Obs, dY3_Obs, dZ3_Obs;
                GetParametersFromKeyFrame(keyframe3, out dX3_Tar, out dY3_Tar, out dZ3_Tar, out dX3_Obs, out dY3_Obs, out dZ3_Obs);
                #endregion

                ////=========================================== 创建中间帧    == == == == == == == == == == == == == == == == == == == == == =
                IKeyframe keyframe2 = CreateMiddleKeyframe(globeDisplay.Globe, dX1_Tar,
                                      dY1_Tar, dZ1_Tar, dX1_Obs, dY1_Obs, dZ1_Obs,
                                      dX3_Tar, dY3_Tar, dZ3_Tar, dX3_Obs, dY3_Obs, dZ3_Obs);  //头晕、高血压、糖尿病患者调用该函数请慎重!
                //=========================================== 创建中间帧    == == == == == == == == == == == == == == == == == == == == == =
                //animationTrack.InsertKeyframe(keyframe2, animationTrack.KeyframeCount);
                animationTrack.InsertKeyframe(keyframe3, animationTrack.KeyframeCount);
                // Set The Animation Track Name
                animationTrack.Name = "Zoom Over Location";
                // Set Track Attachments
                animationTrack.AttachObject(globeCamera);
                animationTrack.ApplyToAllViewers = true;
                // Add The New Track To The Scene
                animationTracks.AddTrack(animationTrack);
                // Return The Newly Create Aninmation Track
            }
            catch { }
            return animationTrack;
        }
Exemplo n.º 28
0
        public override int Execute(string logfileName)
        {
            this.InitLogging(logfileName);
            this.LogMessage(this.Name + " QA test execution started.");

            bool bProblemsRunning = false;

            int currentOid = -1;
            try
            {

                this.LogMessage(this.Name + " Parameters:");
                for (int i = 0; i < this.ParameterCount; i++)
                    this.LogMessage(this.get_ParameterText(i) + ": " + this.get_ParameterValue(i));

                this.ClearErrors();

                for (int layerIdx = 0; layerIdx < this.LayerCount; layerIdx++)
                {
                    IFeatureLayer theFLayer = this.get_Layer(layerIdx);
                    IFeatureClass theFClass = theFLayer.FeatureClass;
                    IDataset theDataset = (IDataset)theFClass;

                    if (!this.SupportsGeometryType(theFClass.ShapeType))
                    {
                        this.LogMessage("Gap detector does not support the geometry type in featureclass " + theDataset.Name);
                        bProblemsRunning = true;
                    }
                    else if (theFClass.FeatureDataset == null)
                    {
                        this.LogMessage("Featureclass " + theDataset.Name + " is not in a feature dataset");
                        bProblemsRunning = true;
                    }
                    else
                    {
                        this.LogMessage("Looking for topology with gap rule including featureclass " + theDataset.Name);

                        ITopology theTopology = null;
                        ArrayList theTRules = new ArrayList();
                        ITopologyRule theTopoRule = null;
                        IEnumDataset theDatasetEnum = theFClass.FeatureDataset.Subsets;

                        IDataset theSiblingDS = theDatasetEnum.Next();
                        while (theSiblingDS != null)
                        {
                            if (theSiblingDS.Type == esriDatasetType.esriDTTopology)
                            {
                                // Look for a gap rule featuring theFClass
                                theTopology = (ITopology)theSiblingDS;
                                ITopologyRuleContainer theTRContainer = (ITopologyRuleContainer)theTopology;
                                IEnumRule theRules = theTRContainer.get_RulesByClass(theFClass.FeatureClassID);

                                theTopoRule = (ITopologyRule)theRules.Next();
                                while (theTopoRule != null)
                                {
                                    if (theTopoRule.TopologyRuleType == esriTopologyRuleType.esriTRTAreaNoGaps)
                                        theTRules.Add(theTopoRule);
                                    theTopoRule = (ITopologyRule)theRules.Next();
                                }
                            }
                            theSiblingDS = theDatasetEnum.Next();
                        }

                        if (theTopology == null || theTRules.Count == 0)
                        {
                            this.LogMessage("Featureclass " + theDataset.Name + " is not part of a Gap topology rule");
                            bProblemsRunning = true;
                            continue;
                        }

                        if (this.ValidateTopology(theTopology) == false)
                        {
                            this.LogMessage("The topology " + ((IDataset)theTopology).Name + " could not be validated");
                            bProblemsRunning = true;
                            continue;
                        }

                        if (theTopology.State == esriTopologyState.esriTSAnalyzedWithErrors)
                        {
                            this.LogMessage("Indexing gap errors in featureclass " + theDataset.Name
                                + " as it relates to Topology " + ((IDataset)theTopology).Name);

                            IErrorFeatureContainer theTopoErrorContainer = (IErrorFeatureContainer)theTopology;

                            int count = 0;
                            int countIncrement = 500;

                            DoubleParameterInfo theParam = (DoubleParameterInfo)this._params[this.FindParameter("ignore-gap-larger-than")];
                            double maxGap = (double)theParam.ParamValue;
                            theParam = (DoubleParameterInfo)this._params[this.FindParameter("ignore-gap-smaller-than")];
                            double minGap = (double)theParam.ParamValue;

                            // Convert gap limits to metres
                            UnitsParameterInfo theUnits = (UnitsParameterInfo)this._params[this.FindParameter("gap-units")];
                            IUnitConverter theConverter = new UnitConverterClass();
                            maxGap = theConverter.ConvertUnits(maxGap, theUnits.ParamValueInUnits, esriUnits.esriMeters);
                            minGap = theConverter.ConvertUnits(minGap, theUnits.ParamValueInUnits, esriUnits.esriMeters);

                            for (int j = 0; j < theTRules.Count; j++)
                            {
                                theTopoRule = (ITopologyRule)theTRules[j];

                                this.LogMessage("Processing rule " + (j+1) + " of " + theTRules.Count);

                                double cellsize = maxGap * 5;
                                PointCollectionIndex theIndex = new PointCollectionIndex(cellsize);

                                IGeoDataset theGeoDS = (IGeoDataset)theTopology;
                                IEnumTopologyErrorFeature theTopoErrors = theTopoErrorContainer.get_ErrorFeatures(theGeoDS.SpatialReference, theTopoRule, null, true, false);
                                ITopologyErrorFeature theTopoErrorFeature = theTopoErrors.Next();
                                while (theTopoErrorFeature != null)
                                {
                                    currentOid = theTopoErrorFeature.ErrorID;

                                    IPointCollection thePtColl = (IPointCollection)((IFeature)theTopoErrorFeature).Shape;
                                    for (int i = 0; i < thePtColl.PointCount; i++)
                                    {
                                        // ErrorID the same as ObjectID on the error feature
                                        theIndex.AddPoint(new IndexPoint(theTopoErrorFeature.ErrorID, i, thePtColl.get_Point(i)));
                                    }

                                    if (++count % countIncrement == 0)
                                    {
                                        this.LogMessage("Indexed " + count + " topology errors...");
                                    }

                                    theTopoErrorFeature = theTopoErrors.Next();
                                }

                                this.LogMessage("Getting pairs of points within tolerances...");
                                ArrayList theResults = theIndex.PointPairsWithinLimits(minGap, maxGap);
                                this.LogMessage(theResults.Count + " pairs of points found within gap tolerances. Checking.");

                                // Get info from the params
                                int index = this.FindParameter("angle-tolerance-degrees");
                                theParam = (DoubleParameterInfo)this._params[index];
                                double theLimitRadians = Math.PI * (double)theParam.ParamValue / 180;
                                index = this.FindParameter("eliminate-pinches");
                                bool allowPinches = !(bool)((ParameterInfo)this._params[index]).ParamValue;

                                ArrayList theList = this.ProcessPotentialGapErrors(theResults, theTopology, theFClass,
                                    theLimitRadians, allowPinches);

                                if (theList != null)
                                {
                                    index = this.FindParameter(ParameterInfo.PARAM_CANDEFER);
                                    bool canDefer = (bool)((ParameterInfo)this._params[index]).ParamValue;
                                    index = this.FindParameter(ParameterInfo.PARAM_CANEXCEPT);
                                    bool canExcept = (bool)((ParameterInfo)this._params[index]).ParamValue;

                                    theList = this.WeedErrors(theList, canDefer, canExcept, minGap, maxGap);
                                }

                                if (theList != null)
                                {
                                    foreach (DataQualityError dqe in theList)
                                        this._errors.Add(dqe);
                                }
                            }
                        }
                        else
                        {
                            this.LogMessage("Topology has no errors");
                        }
                    }
                }

                this.LogMessage("Number of errors found: " + this.ErrorCount);
                this.LogMessage("Test " + this.Name + " successful.");
            }
            catch (Exception ex)
            {
                this.LogMessage("Exception caught: \n" + ex.Message + "\n" + ex.StackTrace.ToString());
                this.LogMessage("id of the current polygon: " + currentOid);
                return -1;
            }
            finally
            {
                this.StopLogging();
            }

            if (bProblemsRunning)
                return -1;

            return this.ErrorCount;
        }
Exemplo n.º 29
0
        /// <summary>
        ///     Converts the specified numeric data value from one unit of measure to another unit of measure.
        /// </summary>
        /// <param name="source">The source units of the value.</param>
        /// <param name="value">The value.</param>
        /// <param name="target">The target units that that the source units should be converted to.</param>
        /// <returns>Returns a <see cref="double" /> representing the converted units.</returns>
        public static double ConvertTo(this esriUnits source, double value, esriUnits target)
        {
            IUnitConverter converter = new UnitConverterClass();

            return(converter.ConvertUnits(value, source, target));
        }
        private string ExportPages(IActiveView docActiveView, int iDPI, string filename, enumExportType exportType, double paperWidth, double paperHeight, int blockCount)
        {
            string filepath = filename.Substring(0, filename.LastIndexOf("\\"));
            string NameExt = System.IO.Path.GetFileName(filename);
            if (docActiveView is IPageLayout)
            {
            double width = 0, height = 0;   //实际长宽
            //计算分页地图大小 paperWidth,paperHeight
            //分块数量 blockCount
            //计算分页图片大小 iWidth,iHeight
            #region 计算出图参数
            var pPageLayout = docActiveView as IPageLayout;
            pPageLayout.Page.QuerySize(out width, out height);
            IUnitConverter pUnitCon = new UnitConverterClass();
            switch (exportType)
            {
                case enumExportType.byPaperSize:
                    if (paperWidth <= 0 || paperHeight <= 0)
                    { paperWidth = 210; paperHeight = 297; }
                    paperWidth = pUnitCon.ConvertUnits(paperWidth, esriUnits.esriMillimeters, pPageLayout.Page.Units);
                    paperHeight = pUnitCon.ConvertUnits(paperHeight, esriUnits.esriMillimeters, pPageLayout.Page.Units);
                    bool bW = (width > paperWidth + 0.001) ? true : false;
                    bool bH = (height > paperHeight + 0.001) ? true : false;
                    blockCount = (bW && bH) ? 4 : 1;
                    break;
                case enumExportType.byBlockCount:
                default:
                    if (blockCount < 1) blockCount = 1;
                    paperWidth = width / blockCount;
                    paperHeight = height / blockCount;
                    break;
            }
            int iWidth = (int)(pUnitCon.ConvertUnits(paperWidth, pPageLayout.Page.Units, esriUnits.esriInches) * iDPI);
            int iHeight = (int)(pUnitCon.ConvertUnits(paperHeight, pPageLayout.Page.Units, esriUnits.esriInches) * iDPI);
            #endregion

            if (System.IO.File.Exists(filename))
            {
                var pWS = OpenWorkspace(filename, enumWsFactoryType.Raster) as IRasterWorkspace;
                var pRDs = pWS.OpenRasterDataset(NameExt);
                var pDS = pRDs as IDataset;
                pDS.Delete();
            }

            if (blockCount > 1)
            {
                #region 创建子目录,获得扩展名
                string NameNoExt = System.IO.Path.GetFileNameWithoutExtension(filename);
                string sExt = System.IO.Path.GetExtension(filename).ToLower();
                //创建子目录
                string subPath = filename.Substring(0, filename.LastIndexOf("."));
                if (System.IO.Directory.Exists(subPath))
                {
                    System.IO.Directory.Delete(subPath, true);
                }
                try
                {
                    System.IO.Directory.CreateDirectory(subPath);
                    if (!System.IO.Directory.Exists(subPath))
                    {
                        subPath = subPath + "_1";
                        System.IO.Directory.CreateDirectory(subPath);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    subPath = subPath + "_1";
                    System.IO.Directory.CreateDirectory(subPath);
                }

                //worldfile扩展名
                string worldfileExt = "." + sExt[1].ToString() + sExt[sExt.Length - 1].ToString() + "w";
                #endregion

                #region 分页输出
                int index = 0;
                int minX = 0, maxY = iHeight;
                double w, h = 0;
                string t_name = subPath + @"\" + NameNoExt + "_";
                IExport docExport = CreateExport(filename, 1);
                IEnvelope pEnv1 = new EnvelopeClass();
                while (h < height - 0.0001)
                {
                    w = 0;
                    minX = 0;
                    while (w < width - 0.0001)
                    {
                        pEnv1.XMin = w;
                        pEnv1.YMin = h;
                        pEnv1.XMax = w + paperWidth;
                        pEnv1.YMax = h + paperHeight;
                        index++;

                        label1.Text += ".";
                        Application.DoEvents();

                        //output输出
                        ActiveViewOutput(docActiveView, iDPI, iWidth, iHeight, pEnv1, t_name + index.ToString() + sExt, docExport);
                        //写入worldfile
                        WriteWorldfile(t_name + index.ToString() + worldfileExt, 1, 0, 0, -1, minX, maxY);
                        w += paperWidth;
                        minX += iWidth;
                    }
                    h += paperHeight;
                    maxY += iHeight;
                }
                #endregion

                #region 合并栅格
                //设置坐标参考
                var pRasterWS = OpenWorkspace(subPath, enumWsFactoryType.Raster);
                ISpatialReferenceFactory2 pSrF = new SpatialReferenceEnvironmentClass();
                var pSR = pSrF.CreateSpatialReference(3857);
                var pEnumDS = pRasterWS.get_Datasets(esriDatasetType.esriDTRasterDataset);
                var pDS = pEnumDS.Next();
                while (pDS != null)
                {
                    var GeoSchEdit = pDS as IGeoDatasetSchemaEdit;
                    if (GeoSchEdit.CanAlterSpatialReference)
                        GeoSchEdit.AlterSpatialReference(pSR);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(pDS);
                    pDS = pEnumDS.Next();
                }
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(pRasterWS);

                //saveas时占用很大内存且不释放,使用GP工具
                //怎么不创建金字塔和头文件??
                Geoprocessor geoprocessor = new Geoprocessor();
                try
                {
                    CreateRasterDataset createRD = new CreateRasterDataset();
                    createRD.cellsize = 1;
                    createRD.number_of_bands = 3;
                    createRD.out_path = filepath;
                    createRD.out_name = NameExt;
                    createRD.pyramids = "NONE";
                    createRD.compression = "NONE";
                    geoprocessor.Execute(createRD, null);

                    WorkspaceToRasterDataset MosaicToRaster = new WorkspaceToRasterDataset();
                    MosaicToRaster.in_workspace = subPath;
                    MosaicToRaster.in_raster_dataset = filename;
                    geoprocessor.Execute(MosaicToRaster, null);
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                    for (int i = 0; i < geoprocessor.MessageCount; i++)
                    {
                        string abc = geoprocessor.GetMessage(i);
                        Console.WriteLine(abc);
                    }

                }
                #endregion

                return subPath;
            }
            else
            {
                Export10Plus(docActiveView, filename, iDPI, 0, 0, null);
                return "";
            }
            }
            else      //map
            {
            return "";
            }
        }