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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
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, nullnull);
            }
            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, nullnull);
                }
            }
            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, nullfalse);
                mapControl.Refresh(esriViewDrawPhase.esriViewGeoSelection, nullnull);
            }
            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);
            }
 
        }
    }
}
原文地址:https://www.cnblogs.com/janeaiai/p/4920600.html