C#:MapControl基本操作代码整理

来自:http://www.cnblogs.com/shenchao/p/3591312.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;

namespace MapCtrol    //直接引用时需替换成自己当前的命名空间
{
    public class MapBaseOperate
    {
        /// <summary>
        /// 添加SHP文当
        /// </summary>
        /// <param name="mapControl"></param>
        public static void AddShapeFile(IMapControlDefault mapControl)
        {
            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Title = "添加shp图层文件";
            openfileDlg.Filter = "map document (*.shp)|*.shp";
            openfileDlg.ShowDialog();
            string filepath = openfileDlg.FileName;

            bool exist = File.Exists(filepath);
            if (!exist)
            {
                MessageBox.Show("路径不存在!");
                return;
            }

            string path;
            string filename;
            //int istart = filepath.LastIndexOf("\\");
            //int iend = filepath.LastIndexOf(".");
            //path = filepath.Substring(0, istart);
            //filename = filepath.Substring(istart + 1, iend - istart - 1);

            FileInfo fileinfo = new FileInfo(filepath);
            path = filepath.Substring(0, filepath.Length - fileinfo.Name.Length);
            filename = fileinfo.Name;
            try
            {
                //加载图层文件
                mapControl.AddShapeFile(path, filename);

                //设置MapControl的显示范围到数据的全局范围
                mapControl.Extent = mapControl.FullExtent;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("添加图层文件失败!" + ex.Message);
            }

        }

        /// <summary>
        /// 添加LYR文当
        /// </summary>
        /// <param name="mapControl"></param>
        public static void AddLayerFile(IMapControlDefault mapControl)
        {
            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Title = "添加lyr图层文件";
            openfileDlg.Filter = "map documents (*.lyr)|*.lyr";
            openfileDlg.ShowDialog();
            string filepath = openfileDlg.FileName;

            bool exist = File.Exists(filepath);
            if (!exist)
            {
                MessageBox.Show("路径不存在!");
                return;
            }
            try
            {
                mapControl.AddLayerFromFile(filepath);

                //设置MapControl的显示范围到数据的全局范围
                mapControl.Extent = mapControl.FullExtent;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("添加图层文件失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 删除地图所有图层
        /// </summary>
        public static void DeleteAllLayers(IMapControlDefault mapControl)
        {
            try
            {
                for (int i = mapControl.LayerCount - 1; i >= 0; i-- )
                {
                    mapControl.DeleteLayer(i);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("删除图层失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 将最底图层,移动到最上层
        /// </summary>
        public static void MoveLayerToTop(IMapControlDefault mapControl)
        {

            try
            {
                if (mapControl.LayerCount > 0)
                {
                    mapControl.MoveLayerTo(mapControl.LayerCount - 1, 0);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("移动图层失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 加载地图文当
        /// </summary>
        /// <param name="mapControl"></param>
        public static void LoadMapDocument(IMapControlDefault mapControl)
        {
            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Title = "加载地图文当";
            openfileDlg.Filter = "map document (*.mxd)|*.mxd";
            openfileDlg.ShowDialog();
            string filepath = openfileDlg.FileName;
            if (mapControl.CheckMxFile(filepath))
            {
                mapControl.MousePointer = esriControlsMousePointer.esriPointerHourglass;
                mapControl.LoadMxFile(filepath, 0, Type.Missing);
                mapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
            else
            {
                MessageBox.Show(filepath + "不是有效的地图文当!");
            }
        }

        /// <summary>
        /// 加载特定地图文当
        /// </summary>
        /// <param name="mapControl"></param>
        public static void LoadSpecificMapDocument(IMapControlDefault mapControl, string specificMapName)
        {
            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Title = "加载特定地图文当";
            openfileDlg.Filter = "map document (*.mxd)|*.mxd";
            openfileDlg.ShowDialog();
            string filepath = openfileDlg.FileName;

            if (mapControl.CheckMxFile(filepath))
            {
                if (string.IsNullOrWhiteSpace(specificMapName))
                {
                    int istart = filepath.LastIndexOf("\\");
                    int iend = filepath.LastIndexOf(".");
                    specificMapName = filepath.Substring(istart + 1, iend - istart - 1);
                }

                IArray arrayMap = mapControl.ReadMxMaps(filepath, Type.Missing);
                for (int i = 0; i < arrayMap.Count; i++)
                {
                    IMap map = arrayMap.get_Element(i) as IMap;
                    if (specificMapName == map.Name)
                    {
                        mapControl.MousePointer = esriControlsMousePointer.esriPointerHourglass;
                        mapControl.LoadMxFile(filepath, 0, Type.Missing);
                        mapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
                        break;
                    }
                }
            }
            else
            {
                MessageBox.Show(filepath + "不是有效的地图文当!");
            }
        }

        /// <summary>
        /// By MapDocument
        /// </summary>
        public static IMapDocument LoadMapDoc(IMapControlDefault mapControl)
        {
            MapDocument mapdoc = new MapDocument();

            try
            {
                OpenFileDialog openfileDlg = new OpenFileDialog();
                openfileDlg.Title = "加载地图文当";
                openfileDlg.Filter = "map document (*.mxd)|*.mxd";
                openfileDlg.ShowDialog();
                string filepath = openfileDlg.FileName;

                mapdoc.Open(filepath, "");

                for (int i = 0; i < mapdoc.MapCount; i++ )
                {
                    mapControl.Map = mapdoc.get_Map(i);
                }
                mapControl.Refresh();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("加载地图文当失败" + ex.Message);
                mapdoc = null;
            }
            return mapdoc;

        }

        /// <summary>
        /// By MapDocument
        /// </summary>
        /// <param name="mapDoc"></param>
        public static void SaveMapDoc(IMapDocument mapDoc)
        {
            if (null == mapDoc)
            {
                MessageBox.Show("保存地图文档失败!");
                return;
            }

            if (mapDoc.get_IsReadOnly(mapDoc.DocumentFilename) == true)
            {
                MessageBox.Show("文档只读无法保存!");
            }

            try
            {
                mapDoc.Save(mapDoc.UsesRelativePaths,true);
                MessageBox.Show("保存地图文档成功!");

            }
            catch (System.Exception ex)
            {
                 MessageBox.Show("保存地图文档失败!" + ex.Message);
            }

        }

        /// <summary>
        /// By MapDocument
        /// </summary>
        /// <param name="mapDoc"></param>
        public static void SaveAsMapDoc(IMapDocument mapDoc)
        {
            if (null == mapDoc)
            {
                MessageBox.Show("保存地图文档失败!");
                return;
            }

            if (mapDoc.get_IsReadOnly(mapDoc.DocumentFilename) == true)
            {
                MessageBox.Show("文档只读无法保存!");
            }

            SaveFileDialog savefiledlg = new SaveFileDialog();
            savefiledlg.Title = "保存地图文当";
            savefiledlg.Filter = "map document (*.mxd)|*.mxd";
            savefiledlg.ShowDialog();
            string filepath = savefiledlg.FileName;
            try
            {
                mapDoc.SaveAs(filepath,mapDoc.UsesRelativePaths,true);
                MessageBox.Show("保存地图文档成功!");

            }
            catch (System.Exception ex)
            {
                 MessageBox.Show("保存地图文档失败!" + ex.Message);
            }

        }

        /// <summary>
        /// 缩小
        /// </summary>
        /// <param name="mapControl"></param>
        public static void ZoomOut(IMapControlDefault mapControl)
        {
            try
            {
               mapControl.MousePointer = esriControlsMousePointer.esriPointerPageZoomOut;
              //IEnvelope ipEnv = mapControl.TrackRectangle();
              IEnvelope ipEnv = mapControl.Extent;
              ipEnv.Expand(2, 2, true);
              mapControl.Extent = ipEnv;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("缩小失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 放大
        /// </summary>
        /// <param name="mapControl"></param>
        public static void ZoomIn(IMapControlDefault mapControl)
        {
            try
            {
               mapControl.MousePointer = esriControlsMousePointer.esriPointerPageZoomIn;
              IEnvelope ipEnv = mapControl.TrackRectangle();
              if (ipEnv.IsEmpty)
              {
                  ipEnv = mapControl.Extent;
                  ipEnv.Expand(0.5, 0.5, true);
              }
              mapControl.Extent = ipEnv;                  
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("放大失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 漫游
        /// </summary>
        /// <param name="mapControl"></param>
        public static void Pan(IMapControlDefault mapControl)
        {
            try
            {
                mapControl.MousePointer = esriControlsMousePointer.esriPointerPagePan;
                //IEnvelope ipEnv = mapControl.Extent;
                mapControl.Pan();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("漫游失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 全图
        /// </summary>
        /// <param name="mapControl"></param>
        public static void FullExtent(IMapControlDefault mapControl)
        {
            try
            {
                mapControl.Extent = mapControl.FullExtent;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("全图失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 写文字(待优化)
        /// </summary>
        /// <param name="mapControl"></param>
        /// <param name="pGeom"></param>
        /// <param name="pColor"></param>
        /// <param name="text"></param>
        public static void DrawMapText(IMapControlDefault mapControl, IGeometry pGeom, IRgbColor pColor, string text)
        {
            try
            {
                if (null == pColor)
                {
                    pColor = new RgbColorClass();
                    pColor.Red = 255;
                    pColor.Green = 0;
                    pColor.Blue = 0;
                }
                ITextSymbol textsymbol = new TextSymbolClass();
                textsymbol.Color = pColor;
                if (null == text)
                {
                    text = "Draw Text";
                }
                textsymbol.Text = "Text";
                object symbol = textsymbol;
                mapControl.DrawText(pGeom, text, ref symbol);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("写文字失败!" + ex);
            }

        }

        /// <summary>
        /// 画图
        /// </summary>
        /// <param name="mapControl"></param>
        /// <param name="pGeom"></param>
        /// <param name="pColor"></param>
        /// <param name="width"></param>
        public static void DrawMapShape(IMapControlDefault mapControl, IGeometry pGeom, IRgbColor pColor, int width)
        {
            try
            {
                if (null == pColor)
                {
                    pColor = new RgbColorClass();
                    pColor.Red = 255;
                    pColor.Green = 255;
                    pColor.Blue = 0;
                }

                if (width < 1 || width > 20)
                {
                    width = 5;
                }
                object symbol = null;
                if (pGeom.GeometryType == esriGeometryType.esriGeometryPolyline)
                {
                    ISimpleLineSymbol simpleLine = new SimpleLineSymbolClass();
                    simpleLine.Color = pColor;
                    simpleLine.Width = width;
                    symbol = simpleLine;
                }
                else
                {
                    ISimpleFillSymbol simpleFill = new SimpleFillSymbolClass();
                    simpleFill.Color = pColor;
                    symbol = simpleFill;
                }

                mapControl.DrawShape(pGeom, ref symbol);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("画图失败!" + ex);
            }
        }

        /// <summary>
        /// 颜色
        /// </summary>
        /// <param name="r"></param>
        /// <param name="g"></param>
        /// <param name="b"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static IRgbColor GetColor(int r, int g, int b, int t)
        {
            IRgbColor rgbcolor = new RgbColorClass();
            rgbcolor.Red = r;
            rgbcolor.Green = g;
            rgbcolor.Blue = b;
            rgbcolor.Transparency = (byte)t;
            return rgbcolor;
        }

        /// <summary>
        /// 框选指定区域(鹰眼功能)
        /// </summary>
        /// <param name="envelope">e.NewEnvelope</param>
        /// <param name="mapControl"></param>
        public static void ShowRectangleByEnvelope(IEnvelope envelope, IMapControlDefault mapControl)
        {
            try
            {
                IGraphicsContainer graphicsContainer = mapControl.Map as IGraphicsContainer;
                IActiveView activeView = graphicsContainer as IActiveView;

                //在绘制前,清除axMapControl2中的任何图像元素
                graphicsContainer.DeleteAllElements();
                IElement element = new RectangleElementClass();
                element.Geometry = envelope;
                //设置鹰眼中的红线
                //产生一个符号对象
                ILineSymbol outLineSymbol = new SimpleLineSymbolClass();
                outLineSymbol.Width = 2;
                outLineSymbol.Color = GetColor(255, 0, 0, 255);

                //设置颜色属性
                //设置填充符号属性
                IFillSymbol fillsymbol = new SimpleFillSymbolClass();
                fillsymbol.Color = GetColor(9, 0, 0, 0);
                fillsymbol.Outline = outLineSymbol;
                IFillShapeElement fillShapeElement = element as IFillShapeElement;
                fillShapeElement.Symbol = fillsymbol;
                graphicsContainer.AddElement((IElement)fillShapeElement, 0);
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("框选指定区域失败!" + ex);
            }
        }

        /// <summary>
        /// 清除选择
        /// </summary>
        /// <param name="mapControl"></param>
        public static void ClearSelection(IMapControlDefault mapControl)
        {
            try
            {
                IActiveView activeView = (IActiveView)mapControl.Map;
                //清除数据集前必须先刷新
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, mapControl.get_Layer(0), null);
                mapControl.Map.ClearSelection();
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, mapControl.get_Layer(0), null);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("清除选择失败!" + ex);
            }
        }

        /// <summary>
        /// 名称查询
        /// </summary>
        /// <param name="mapControl"></param>
        /// <param name="value"></param>
        public static void SelectByName(IMapControlDefault mapControl, string field, string value)
        {
            try
            {
                string selectName = value.Trim();
                ILayer layer = mapControl.Map.get_Layer(0);
                IFeatureLayer featureLayer = layer as IFeatureLayer;
                IFeatureClass featureClass = featureLayer.FeatureClass;
                IQueryFilter queryFilter = new QueryFilterClass();
                IFeatureCursor featureCursor;
                IFeature feature = null; ;
                queryFilter.WhereClause = field + " = " + value;
                featureCursor = featureClass.Search(queryFilter, true);
                feature = featureCursor.NextFeature();
                if (null != feature)
                {
                    mapControl.Map.SelectFeature(layer, feature);
                    mapControl.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("依据名称查询选中要素失败!" + ex);
            }
        }

        /// <summary>
        /// 依据指定的Geometry(Shape)选中要素
        /// </summary>
        /// <param name="mapControl"></param>
        /// <param name="geometry"></param>
        public static void SelectByShape(IMapControlDefault mapControl, IGeometry geometry)
        {
            try
            {
                mapControl.Map.SelectByShape(geometry, null, false);
                mapControl.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("依据指定的Geometry(Shape)选中要素失败!" + ex);
            }
        }

        /// <summary>
        /// 同步到MapControl控件
        /// </summary>
        public static void CopyToMapControl(IMapControlDefault mapControl, IMapControlDefault toMapControl)
        {
            try
            {
                IObjectCopy objCopy = new ObjectCopyClass();
                object copyFromMap = mapControl.Map;
                object copyMap = objCopy.Copy(copyFromMap);
                object copyToMap = toMapControl.ActiveView.FocusMap;
                objCopy.Overwrite(copyMap, ref copyToMap);
                toMapControl.Extent = mapControl.FullExtent;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Map间数据同步失败!" + ex);
            }

        }

        /// <summary>
        /// 同步到PageLayout控件
        /// </summary>
        public static void CopyToPageLayout(IMapControlDefault mapControl, IPageLayoutControlDefault pageLayoutControl)
        {
            try
            {
                IObjectCopy objCopy = new ObjectCopyClass();
                object copyFromMap = mapControl.Map;
                object copyMap = objCopy.Copy(copyFromMap);
                object copyToMap = pageLayoutControl.ActiveView.FocusMap;
                objCopy.Overwrite(copyMap, ref copyToMap);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Map与PageLayout数据同步失败!" + ex);
            }

        }

        /// <summary>
        /// 屏幕变化后刷新屏幕
        /// </summary>
        /// <param name="mapControl"></param>
        public static void AfterScreenDraw(IMapControlDefault mapControl)
        {
            try
            {
                IActiveView activeView = (IActiveView)mapControl.ActiveView.FocusMap;
                IDisplayTransformation displayTransformation = activeView.ScreenDisplay.DisplayTransformation;
                displayTransformation.VisibleBounds = mapControl.Extent;
                mapControl.ActiveView.Refresh();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("刷新屏幕失败!" + ex);
            }

        }
    }
}
时间: 2024-10-08 00:24:41

C#:MapControl基本操作代码整理的相关文章

常用代码整理(重要)

常用代码整理: 1.判断邮箱格式是否正确的代码: //利用正则表达式验证 -(BOOL)isValidateEmail:(NSString *)email { NSString *emailRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATC

css代码整理、收集

整理了一下之前用到过的css代码,实现一种效果或许有许多种写法,我这里整理了一下我个人认为兼容性比较好,结构比较简洁的代码……如有写得不对的地方敬请前辈们指点赐教一下,小弟不胜感激!此学习笔记是动态的——我日后发现有好的代码段会陆陆续续整理添加上去. css:ellipsis省略号 <style> .news{width:320px; text-overflow:ellipsis; -o-text-overflow:ellipsis; -moz-binding:url('ellipsis.xm

Chrome应用技巧之代码整理。

我们有时候在看别人网站代码时往往是经过压缩的,代码都在一行上了,调试很是困难,今天给大家介绍一种基本Chrome浏览器的代码整理方法.请看图:

bootstrap 新手学习笔记 代码整理

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Bootstrap 实例 - 滚动监听(Scrollspy)插件方法</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/jqu

关于UIImagePickerViewController拍摄video的分辨率和方向的一些代码整理

近期项目由于要使用拍摄视频,用的是UIImagePickerViewController,要求是分辨率640x480,但是试了各种 imagePickerController.videoQuality 拍出来的视频导出来依然达不到640x480. 并且旋转设备拍摄后拍摄出来的视频导出来也是反的. 最后查阅了各种网站找了各种资料之后,看到国外大牛在视频拍摄完成之后使用AVFoundation做的压缩和视频调整.整理了一下代码做了部分调整,感觉到AVfoundation的强大之处,哈哈 这些代码用在

常用js代码整理、收集

个人整理了一下个人常用到的一些js代码,以方便学习以及日后使用,或许有一些是个人之前从网上摘下来的,但是不记得是具体从哪里来的了,如果你看到有一段代码跟你的文章很相似甚至一样,请不要气愤,请告诉我,我必定加上版权链接. 清除输入框默然提示文字 1 <input type="text" name="word" value='请输入关键字' style="color:#ccc;" /> 2 <script> 3 /* 4 *清

Smtp邮件发送系统公用代码整理—总结

1.前言 a.在软件开发中,我们经常能够遇到给用户或者客户推送邮件,推送邮件也分为很多方式,比如:推送一句话,推送一个网页等等.那么在系统开发中我们一般在什么情况下会使用邮件发送呢?下面我简单总结了一下:总结不全,纯属于整理封装的类. (1):用户注册(推送邮件,提示用户注册成功,牢记用户名密码) (2):修改密码(推送邮件,提示用户密码修改成功) (3):下订单(推送邮件,提示用户订单已下) (4):物流跟踪(推送邮件,跟踪物流信息) (5):广告推送(推送广告,提示用户近来公司近况或者新的商

sui picker,datetimepicker,citypicker代码整理

将sui中的sm.js sm.css 整理拆分删除了大量代码整理出来. picker.css picker.js datetimepicker.js city-picker.js 附件:http://down.51cto.com/data/2437983 具体使用方式如下: <html>    <head>       <meta charset="utf-8">       <meta http-equiv="X-UA-Compat

html Css PC 移动端 公用部分样式代码整理

css常用公用部分样式代码整理: body, html, div, blockquote, img, label, p, h1, h2, h3, h4, h5, h6, pre, ul, ol, li, dl, dt, dd, form, a, fieldset, input, th, td {margin: 0; padding: 0; border: 0; outline: none;} ul, ol{list-style: none;} a{color: black;text-decora