基于VS2015的GIS开发代码(超详细版)

一、打开地图文档,保存地图文档代码

  1. 打开地图文档
    算法流程:
    ①获取地图信息,包括地图名称、格式、储存位置
    ②设置确定按钮
    ③检查地图有效性,无法打开时弹出错误提示
try
            {
                OpenFileDialog pOpenFileDialog = new OpenFileDialog();   //获取或设置一个值,该值指示如果用户指定不存在的文件名,对话框是否显示警告。
                pOpenFileDialog.Title = "打开地图文档";   //获取对话框标题
                pOpenFileDialog.Filter = "ArcMap文档(*.mxd)|*.mxd;|ArcMap模板(*.mxt)|*.mxt|发布地图文件(*.pmf)|*.pmf|所有地图格式(*.mxd;*.mxt;*.pmf)|*.mxd;*.mxt;*.pmf";   //获取或设置当前文件名筛选器字符串,该字符串决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容。
                pOpenFileDialog.Multiselect = false;   //不允许多个文件同时选择
                pOpenFileDialog.RestoreDirectory = true;   //存储打开的文件路径
                if (pOpenFileDialog.ShowDialog() == DialogResult.OK)   //如果用户在对话框中单击“确定”,则为 System.Windows.Forms.DialogResult.OK;否则为 System.Windows.Forms.DialogResult.Cancel。
                {
                    string pFileName = pOpenFileDialog.FileName;   //设置地图名称
                    if (pFileName == "")   
                    {
                        return;
                    }
                    if (axMapControl1.CheckMxFile(pFileName))   //检查地图名称有效性
                    {
           axMapControl1.LoadMxFile(pFileName);   //加载地图名称
                    }
                    else
                    {
                        MessageBox.Show(pFileName + "是无效的地图文档!", "信息提示");   //文档无效时弹出提示信息
                        return;
                    }
                }
            }
            catch (Exception ex)   //捕捉异常
            {
                MessageBox.Show("打开地图文档失败" + ex.Message);   //弹出提示信息}

  1. 保存地图文档
    算法流程:
    ①获取地图文件
    ②检察地图可保存性,不可保存弹出提示信息,可保存执行下一步
    ③设置保存地图名称、格式、储存位置
    ④保存地图,并捕捉错误信息
try
            {
                string sMxdFileName = axMapControl1.DocumentFilename;   //设置地图名称
                IMapDocument pMapDocument = new MapDocumentClass();   //获取地图文件
                if (sMxdFileName != null && axMapControl1.CheckMxFile(sMxdFileName))   //如果地图名称不是空值和规定格式
                {
                    if (pMapDocument.get_IsReadOnly(sMxdFileName))   //如果地图格式符合设定的格式
                    {
                        MessageBox.Show("本地图文档是只读的,不能保存!");   //弹出提示
                        pMapDocument.Close();   //关闭地图
                        return;
                    }
                }
                else
                {
                    SaveFileDialog pSaveFileDialog = new SaveFileDialog();   //更新保存地图窗体
                    pSaveFileDialog.Title = "请选择保存路径";   //设置保存路径
                    pSaveFileDialog.OverwritePrompt = true;   //在用户指定的文件名存在的情况下,如果在覆盖该文件之前对话框对用户进行提示
                    pSaveFileDialog.Filter = "ArcMap文档(*.mxd)|*.mxd|ArcMap模板(*.mxt)|*.mxt";   //地图文件保存格式
                    pSaveFileDialog.RestoreDirectory = true;   //假设用户在搜索文件的过程中更改了目录,那么,如果对话框会将当前目录还原为初始值
                    if (pSaveFileDialog.ShowDialog() == DialogResult.OK)   //如果对话框返回值为OK
                    {
                        sMxdFileName = pSaveFileDialog.FileName;   //保存文件名
                    }
                    else
                    {
                        return;   //执行返回
                    }
                }
                pMapDocument.New(sMxdFileName);   //文档名称
                pMapDocument.ReplaceContents(axMapControl1.Map as IMxdContents);   //文档内容替换
                pMapDocument.Save(pMapDocument.UsesRelativePaths, true);   //保存地图信息
                pMapDocument.Close();   //关闭窗口
                MessageBox.Show("保存地图文档成功!");   //提示信息
            }
            catch (Exception ex)   //程序发生错误
            {
                MessageBox.Show(ex.Message);   //弹出错误信息
            }

二、SQL查询代码

1.查询子窗体

            SQL SQL = new SQL(axMapControl1.Map);   //将当前主窗体中MapControl控件中的Map对象赋值给FormQuerSQL
            SQL.Show();   //显示属性查询窗体

2.加载图层

try
            {
                comboBoxLayerName.Items.Clear();   //将当前图层列表清空
                string layerName;   //设置临时变量存储图层名称
                for (int i = 0; i < currentMap.LayerCount; i++)   //对Map中的每个图层进行判断并加载名称
                {
                    if (currentMap.get_Layer(i) is GroupLayer)   //如果该图层为图层组类型,则分别对所包含的每个图层进行操作
                    {
                        ICompositeLayer compositeLayer = currentMap.get_Layer(i) as ICompositeLayer;   //使用ICompositeLayer接口进行遍历操作
                        for (int j = 0; j < compositeLayer.Count; j++)
                        {
                            layerName = compositeLayer.get_Layer(j).Name;
                            comboBoxLayerName.Items.Add(layerName);   //将图层的名称添加到comboBoxLayerName控件中
                        }
                    }
                    else   //如果图层不是图层组类型,则直接添加名称
                    {
                        layerName = currentMap.get_Layer(i).Name;
                        comboBoxLayerName.Items.Add(layerName);
                    }
                }
                comboBoxLayerName.SelectedIndex = 0;   //将comboBoxLayerName控件的默认选项设置为第一个图层的名称
                comboBoxSelectMethod.SelectedIndex = 0;   //将comboBoxSelectMethod控件的默认选项设置为第一种选择方式
            }
            catch { }   //抓捕错误信息

3.加载字段列表

            listBoxFields.Items.Clear();
            listBoxValues.Items.Clear();   //首先将字段列表和字段值列表清空
            IField field;   //设置临时变量存储使用IField接口的对象
            for (int i = 0; i < currentMap.LayerCount; i++)
            {
                if (currentMap.get_Layer(i) is GroupLayer)
                {
                    ICompositeLayer compositeLayer = currentMap.get_Layer(i) as ICompositeLayer;
                    for (int j = 0; j < compositeLayer.Count; j++)
                    {
                        if (compositeLayer.get_Layer(j).Name == comboBoxLayerName.SelectedItem.ToString())   //判断图层的名称是否与comboBoxLayerName控件中选择的图层名称相同
                        {
                            currentFeatureLayer = compositeLayer.get_Layer(j) as IFeatureLayer;   //如果相同则设置为整个窗体所使用的IFeatureLayer接口对象
                            break;   //中断循环
                        }
                    }
                }
                else
                {
                    if (currentMap.get_Layer(i).Name == comboBoxLayerName.SelectedItem.ToString())   //判断图层的名称是否与comboBoxLayerName中选择的图层名称相同
                    {
                        currentFeatureLayer = currentMap.get_Layer(i) as IFeatureLayer;   //如果相同则设置为整个窗体所使用的IFeatureLayer接口对象
                        break;   //中断循环
                    }
                }
            }
            for (int i = 0; i < currentFeatureLayer.FeatureClass.Fields.FieldCount; i++)   //使用IFeatureClass接口对该图层的所有属性字段进行遍历,并填充listBoxFields控件
            {
                field = currentFeatureLayer.FeatureClass.Fields.get_Field(i);   //根据索引值获取图层的字段
                if (field.Name.ToUpper() != "SHAPE")   //排除SHAPE字段,并在其它字段名称后添加字符
                    listBoxFields.Items.Add( field.Name );
            }
            labelwhere.Text = currentFeatureLayer.Name + " WHERE:";   //更新labelwhere控件中的图层名称信息
            textBoxWhere.Clear();   //将显示where语句的文本框内容清空

4.加载唯一值列表

try
            {
                IDataset dataset = (IDataset)currentFeatureLayer.FeatureClass;   //使用FeatureClass对象的IDataset接口来获取dataset和workspace的信息
                IQueryDef queryDef = ((IFeatureWorkspace)dataset.Workspace).CreateQueryDef();   //使用IQueryDef接口的对象来定义和查询属性信息。通过IWorkspace接口的CreateQueryDef()方法创建该对象。
                queryDef.Tables = dataset.Name;   //设置所需查询的表格名称为dataset的名称
                queryDef.SubFields = "DISTINCT (" + currentFieldName + ")";   //设置查询的字段名称。可以联合使用SQL语言的关键字,如查询唯一值可以使用DISTINCT关键字。
                ICursor cursor = queryDef.Evaluate();   //执行查询并返回ICursor接口的对象来访问整个结果的集合
                IFields fields = currentFeatureLayer.FeatureClass.Fields;   //使用IField接口获取当前所需要使用的字段的信息
                IField field = fields.get_Field(fields.FindField(currentFieldName));   //对整个结果集合进行遍历,从而添加所有的唯一值
                IRow row = cursor.NextRow();   //使用IRow接口来操作结果集合。首先定位到第一个查询结果。
                while (row != null)   //如果查询结果非空,则一直进行添加操作
                {
                    if (field.Type == esriFieldType.esriFieldTypeString)   //对String类型的字段,唯一值的前后添加'和',以符合SQL语句的要求
                    {
                        listBoxValues.Items.Add("\'" + row.get_Value(0).ToString() + "\'");
                    }
                    else
                    {
                        listBoxValues.Items.Add(row.get_Value(0).ToString());   //对不符合String类型的字段进行剔除
                    }
                    row = cursor.NextRow();   //继续执行下一个结果的添加
                }
            }
            catch(Exception ex)   //捕捉错误信息
            {
               
            }

5.定义currentmap等

private IMap currentMap;   //当前MapControl控件中的Map对象
private IFeatureLayer currentFeatureLayer;   //设置临时类变量来使用IFeatureLayer接口的当前图层对象
private string currentFieldName;   //设置临时类变量来存储字段名称
private IActiveView acview;   //声明变量IActiveView
public FormQueryByAttribute(IMap map)   //声明变量FormQueryByAttribute
{
            InitializeComponent();   //由系统生成的对于窗体界面的定义方法
            currentMap = map;   //进行赋值
        }

6.设置确定按钮

try
            {
                 SelectFeaturesByAttribute();
                this.Close();   //执行属性查询操作,并关闭窗体
            }
            catch { }   //捕捉错误信息
private void SelectFeaturesByAttribute()   //声明变量SelectFeaturesByAttribute
        {
            IFeatureSelection featureSelection = currentFeatureLayer as IFeatureSelection;   //使用FeatureLayer对象的IFeatureSelection接口来执行查询操作。这里有一个接口转换操作。
            IQueryFilter queryFilter = new QueryFilterClass();   //新建IQueryFilter接口的对象来进行where语句的定义
            queryFilter.WhereClause = textBoxWhere.Text;   //设置where语句内容
//通过接口转换使用Map对象的IActiveView接口来部分刷新地图窗口,从而高亮显示查询的结果
            switch (comboBoxSelectMethod.SelectedIndex)   //根据查询选择方式的不同,得到不同的选择集
            {
                case 0:   //在新建选择集的情况下
                    currentMap.ClearSelection();   //首先使用IMap接口的ClearSelection()方法清空地图选择集
                    featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);   //根据定义的where语句使用IFeatureSelection接口的SelectFeatures方法选择要素,并将其添加到选择集中
                    break;   //停止循环
                case 1:   //添加到当前选择集的情况
                    featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultAdd, false);
                    break;
                case 2:   //从当前选择集中删除的情况
                    featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultXOR, false);
                    break;
                case 3:   //从当前选择集中选择的情况
                    featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultAnd, false);
                    break;
                default:   //默认为新建选择集的情况
                    currentMap.ClearSelection();
                    featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    break;
            }
            IActiveView activeView = currentMap as IActiveView;   //对变量IActiveView进行赋值
            acview = activeView;
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeView.Extent);   //部分刷新操作,只刷新地理选择集的内容
        }

三、统计最大值、拉框放大代码

1.统计最大值

IFeatureLayer layer = axMapControl1.get_Layer(1) as IFeatureLayer;   //获取MapControl1中的要素
            IFeatureSelection selection = layer as IFeatureSelection;   //提供IFeatureSelection对layer中要素的访问
            selection.SelectFeatures(null, esriSelectionResultEnum.esriSelectionResultNew, false);   //规定所选要素的排列方式
            ICursor cursor = null;   //创建游标,提供对控制功能选择的成员的访问
            selection.SelectionSet.Search(null, false, out cursor);   //返回可用于检索查询指定的对象的游标在这个选择集上
            IDataStatistics datastatistics = new DataStatisticsClass();   //更新数据
            datastatistics.Field = "OBJECTID";   //收集统计信息的字段
            datastatistics.Cursor = cursor;   //生成统计信息的光标。
            IStatisticsResults statisticsResults = datastatistics.Statistics;   //提供对用于报告统计数据的成员的访问。
            StringBuilder strbuilder = new StringBuilder();   //初始化内存容量
            strbuilder.AppendLine(statisticsResults.Maximum.ToString());   //超出内存容量最大值时报错
            MessageBox.Show(strbuilder.ToString());   //弹出错误信息
            axMapControl1.Refresh();   //更新MapControl1控件内容

2.拉框放大

axMapControl1.CurrentTool = null;   //初始化MapControl1控件中当前使用的工具
            pMouseOperate = "ZoomIn";   //鼠标操作对应的ARCGIS程序命令
            axMapControl1.MousePointer = esriControlsMousePointer.esriPointerZoomIn;   //放大鼠标框选内容

  switch (pMouseOperate)
                {
                    #region 拉框放大
                    case "ZoomIn":   //定义ZoomIn事件
                        pEnvelope = axMapControl1.TrackRectangle();   //定义拉框范围
                        if (pEnvelope == null || pEnvelope.IsEmpty || pEnvelope.Height == 0 || pEnvelope.Width == 0)   //如果拉框范围为空则返回
                        {
                            return;
                        }
                        pActiveView.Extent = pEnvelope;   //如果有拉框范围,则放大到拉框范围
                        pActiveView.Refresh();   //更新拉框范围视图
                        break;   //中断循环
                    #endregion
                    }

四、鹰眼图代码

//鹰眼同步变量定义
        private bool bCanDrag;   //鹰眼地图上的矩形框可移动的标志
        private IPoint pMoveRectPoint;   //记录在移动鹰眼地图上的矩形框时鼠标的位置
        private IEnvelope pEnv;   //记录数据视图的Extent

//鹰眼地图初始化
axMapControl2.Extent = axMapControl1.FullExtent;   //设置鹰眼范围
pEnv = axMapControl2.Extent;   //定义变量pEnv内容
DrawRectangle(pEnv);  //绘制红色矩形框

//在鹰眼地图上面画矩形框
private void DrawRectangle(IEnvelope pEnvelope)
{
            IGraphicsContainer pGraphicsContainer = axMapControl2.Map as IGraphicsContainer;   //在绘制前,清除鹰眼中之前绘制的矩形框
            IActiveView pActiveView = pGraphicsContainer as IActiveView;
            pGraphicsContainer.DeleteAllElements();
            IRectangleElement pRectangleElement = new RectangleElementClass();   //得到当前视图范围
            IElement pElement = pRectangleElement as IElement;   //提供对框选内容的访问
            pElement.Geometry = pEnvelope;   //给变量pElement添加形状
            IRgbColor pColor = new RgbColorClass();   //设置矩形框(实质为中间透明度面)
            pColor = GetRgbColor(255, 0, 0);   //设置框颜色为红色
            pColor.Transparency = 255;   //设置Alpha混合值
            ILineSymbol pOutLine = new SimpleLineSymbolClass();   //设置线状符号
            pOutLine.Width = 2;   //线宽
            pOutLine.Color = pColor;   //线颜色
            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();   //设置填充
            pColor = new RgbColorClass();   //更新颜色
            pColor.Transparency = 0;   //设置Alpha混合值
            pFillSymbol.Color = pColor;   //填充颜色为红色
            pFillSymbol.Outline = pOutLine;   //填充轮廓的线符号
            IFillShapeElement pFillShapeElement = pElement as IFillShapeElement;   //向鹰眼中添加矩形框
            pFillShapeElement.Symbol = pFillSymbol;   //提供对控制填充形状元素的成员的访问
            pGraphicsContainer.AddElement((IElement)pFillShapeElement, 0);   //向图层添加新的图形元素。
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);   //刷新
        }

/// <summary>
        /// 获取RGB颜色
        /// </summary>
        /// <param name="intR">红</param>
        /// <param name="intG">绿</param>
        /// <param name="intB">蓝</param>
        /// <returns></returns>
        private IRgbColor GetRgbColor(int intR, int intG, int intB)   //控制颜色RGB配置
        {
            IRgbColor pRgbColor = null;   //初始化色彩
            if (intR < 0 || intR > 255 || intG < 0 || intG > 255 || intB < 0 || intB > 255)   //设置RGB范围
            {
                return pRgbColor;
            }
            pRgbColor = new RgbColorClass();   //更新色彩
            pRgbColor.Red = intR;   //声明RGB变量
            pRgbColor.Green = intG;
            pRgbColor.Blue = intB;
            return pRgbColor;   //输出颜色
        }

private void SynchronizeEagleEye()   //定义函数SynchronizeEagleEye
        {
            if (axMapControl2.LayerCount > 0)
            {
                axMapControl2.ClearLayers();   //清空MapControl2控件中的图层
            }
            axMapControl2.SpatialReference = axMapControl1.SpatialReference;   //设置鹰眼和主地图的坐标系统一致
            for (int i = axMapControl1.LayerCount - 1; i >= 0; i--)
            {
                ILayer pLayer = axMapControl1.get_Layer(i);   //使鹰眼视图与数据视图的图层上下顺序保持一致
                if (pLayer is IGroupLayer || pLayer is ICompositeLayer) 
                {
                    ICompositeLayer pCompositeLayer = (ICompositeLayer)pLayer;   //选择所使用的图层
                    for (int j = pCompositeLayer.Count - 1; j >= 0; j--)
                    {
                        ILayer pSubLayer = pCompositeLayer.get_Layer(j);
                        IFeatureLayer pFeatureLayer = pSubLayer as IFeatureLayer;   //获取当前图层内容
                        if (pFeatureLayer != null)
                        {
                            if (pFeatureLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint && pFeatureLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryMultipoint)   //由于鹰眼地图较小,所以过滤点图层不添加
                            {
                                axMapControl2.AddLayer(pLayer);   //在MapControl2添加图层
                            }
                        }
                    }
                }
                else
                {
                            axMapControl2.AddLayer(pLayer);   //在MapControl2添加图层
                }
                axMapControl2.Extent = axMapControl1.FullExtent;   //设置鹰眼地图全图显示
                pEnv = axMapControl1.Extent as IEnvelope;   //对axMapControl1图层方法和属性的访问
                DrawRectangle(pEnv);   //在鹰眼图画矩形
                axMapControl2.ActiveView.Refresh();   //刷新MapControl2控件内容
            }
        }

private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)   //设置MapControl2控件鼠标事件
        {
            if (axMapControl2.Map.LayerCount > 0)
            {
                if (e.button == 1)   //按下鼠标左键移动矩形框
                {
                    if (e.mapX > pEnv.XMin && e.mapY > pEnv.YMin && e.mapX < pEnv.XMax && e.mapY < pEnv.YMax)   //如果指针落在鹰眼的矩形框中
                    {
                        bCanDrag = true;   //标记可移动
                    }
                    pMoveRectPoint = new PointClass();
                    pMoveRectPoint.PutCoords(e.mapX, e.mapY);   //记录点击的第一个点的坐标
                }
                else if (e.button == 2)   //按下鼠标右键
                {
                    IEnvelope pEnvelope = axMapControl2.TrackRectangle();   //绘制矩形框
                    IPoint pTempPoint = new PointClass();   //更新位置
                    pTempPoint.PutCoords(pEnvelope.XMin + pEnvelope.Width / 2, pEnvelope.YMin + pEnvelope.Height / 2);
                    axMapControl2.Extent = pEnvelope;   //设置MapControl2控件地图范围
                    axMapControl2.CenterAt(pTempPoint);   //矩形框的高宽和数据试图的高宽不一定成正比,这里做一个中心调整
                }
            }
        }

private void axMapControl2_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)   //设置OnMouseUp事件
        {
            if (e.button == 1 && pMoveRectPoint != null)   //点击鼠标左键
            {
                if (e.mapX == pMoveRectPoint.X && e.mapY == pMoveRectPoint.Y)   //设置地图选择范围
                {
                    axMapControl1.CenterAt(pMoveRectPoint);   //设置地图显示中心
                }
                bCanDrag = false;   //矩形不可移动
            }
        }

private void axMapControl2_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)   //设置OnMouseMove事件
        {
            if (e.mapX > pEnv.XMin && e.mapY > pEnv.YMin && e.mapX < pEnv.XMax && e.mapY < pEnv.YMax)   //如果鼠标移动到矩形框中,
            {
                axMapControl2.MousePointer = esriControlsMousePointer.esriPointerHand;   //鼠标换成小手,表示可以拖动
                if (e.button == 2)  //如果在内部按下鼠标右键
                {
                    axMapControl2.MousePointer = esriControlsMousePointer.esriPointerDefault;   //将鼠标演示设置为默认样式
                }
            }
            else
            {
                axMapControl2.MousePointer = esriControlsMousePointer.esriPointerDefault;   //在其他位置将鼠标设为默认的样式
            }
            if (bCanDrag)   //如果矩形框可移动
            {
                double Dx, Dy;   //记录鼠标移动的距离
                Dx = e.mapX - pMoveRectPoint.X;
                Dy = e.mapY - pMoveRectPoint.Y;
                pEnv.Offset(Dx, Dy);   //根据偏移量更改 pEnv 位置
                pMoveRectPoint.PutCoords(e.mapX, e.mapY);   //定位
                DrawRectangle(pEnv);   //画矩形框
                axMapControl1.Extent = pEnv;   //设置MapControl1控件中地图范围
            }
        }

axMapControl1_OnExtentUpdated:   //MapControl1控件地图范围更新
            pEnv = (IEnvelope)e.newEnvelope;  //得到当前视图范围
            DrawRectangle(pEnv);   //画矩形
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yokon_D

您的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值