MapControlEx.cs 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565
  1. using DevExpress.Export.Xl;
  2. using DevExpress.Map;
  3. using DevExpress.Map.Native;
  4. using DevExpress.Utils;
  5. using DevExpress.Utils.Svg;
  6. using DevExpress.XtraBars;
  7. using DevExpress.XtraGrid;
  8. using DevExpress.XtraGrid.Columns;
  9. using DevExpress.XtraGrid.Views.Grid;
  10. using DevExpress.XtraMap;
  11. using DevExpress.XtraMap.ItemEditor;
  12. using DevExpress.XtraPrinting;
  13. using DxHelper;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.ComponentModel.DataAnnotations;
  17. using System.Data.Common;
  18. using System.Data.SQLite;
  19. using System.Drawing;
  20. using System.Drawing.Imaging;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Reflection;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Windows.Forms;
  27. using XdCxRhDW.Repostory;
  28. public enum GoogleMapType
  29. {
  30. /// <summary>
  31. /// 卫星地图
  32. /// </summary>
  33. Sat = 47626774,
  34. /// <summary>
  35. /// 地形图
  36. /// </summary>
  37. Landform = 370833361,
  38. /// <summary>
  39. /// 混合地图
  40. /// </summary>
  41. Mix = 1024577166,
  42. /// <summary>
  43. /// 普通地图
  44. /// </summary>
  45. Normal = 1818940751
  46. }
  47. /// <summary>
  48. /// MapControl扩展类,封装了常用的非业务基础功能.
  49. /// 内置了4个图层,ImageTileLayer、DrawLayer、FixedDrawLayer、PosLayer.
  50. /// 必须首先调用UseDefalutOptions函数
  51. /// </summary>
  52. public static class MapControlEx
  53. {
  54. class InnerData
  55. {
  56. internal GeoPoint _mapMenuGeoPoint;
  57. internal Dictionary<int, MapItem> _clusterCache = new Dictionary<int, MapItem>();
  58. internal Dictionary<PosData, MapItem> _dataCache = new Dictionary<PosData, MapItem>();
  59. internal BarManager barM;
  60. internal PopupMenu mapMenu;
  61. internal PopupMenu posMenu;
  62. internal PopupMenu rectMenu;
  63. internal Action<(double starLon, double startLat, double centerLon, double centerLat,
  64. double endLon, double endLat, double lonRange, double latRange)> mOnRectChanged;
  65. internal Action<(double Lon, double Lat)> onClickChanged;
  66. internal MapItemStorage mMapStorage;
  67. internal MapItemStorage mMapStorageFixed;
  68. internal MapPolyline distinctPath;
  69. internal MapDot hoverPoint;
  70. internal ToolTipControllerShowEventArgs hoverTip;
  71. internal ToolTipController mapToolTip;
  72. internal MapItemStorage posStorge;
  73. internal MapRectangle rangeItem;
  74. internal MapDot dotItem = new MapDot() { Tag = "DrawRect" };
  75. internal bool drawingRect = false;
  76. internal bool mouseLeftDown = false;
  77. internal (double starLon, double startLat, double centerLon, double centerLat,
  78. double endLon, double endLat, double lonRange, double latRange)
  79. CurrentRect;
  80. internal MapDot preSelectedItem;
  81. internal Type posDataType;
  82. }
  83. private static GoogleMapType mMapType = GoogleMapType.Normal;
  84. private static List<MapControl> listMapCtrl = new List<MapControl>();
  85. private const int _dotSize = 8;
  86. private const int _selectedDotSize = 12;
  87. public static MapControl SetMapLayerType(this MapControl ctrl, string wmsUrl)
  88. {
  89. if (!string.IsNullOrWhiteSpace(wmsUrl))
  90. {
  91. var provider = new WmsDataProvider();//地图瓦片提供者
  92. provider.ServerUri = wmsUrl;
  93. provider.ActiveLayerName = "OSM-WMS";
  94. ctrl.GetImageLayer().DataProvider = provider;
  95. }
  96. else
  97. {
  98. bool localGmdbDataEnable = false;//本地Data.Gmdb是否可用,可用时读取本地瓦片,否则执行Http请求资源
  99. var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
  100. if (files.Length > 0)
  101. {
  102. try
  103. {
  104. string conStr = string.Format("Data Source=\"{0}\";Page Size=32768", files[0]);
  105. var con = new SQLiteConnection(conStr);
  106. con.Open();
  107. con.Close();
  108. localGmdbDataEnable = true;
  109. }
  110. catch (Exception ex)
  111. {
  112. Console.Error.WriteLine(ex.Message);
  113. }
  114. }
  115. if (localGmdbDataEnable)
  116. {
  117. var provider = new ImageTileDataProvider();//地图瓦片提供者
  118. provider.TileSource = new ImageTileSource();//地图瓦片数据源接口实现
  119. ctrl.GetImageLayer().DataProvider = provider;
  120. }
  121. else
  122. {
  123. var provider = new HttpMapDataProvider();
  124. ctrl.GetImageLayer().DataProvider = provider;
  125. }
  126. }
  127. return ctrl;
  128. }
  129. /// <summary>
  130. /// <para>设置地图通用属性并创建4个Layer.</para>
  131. /// <para>ImageLayer:绘制地图瓦片</para>
  132. /// <para>DrawLayer:地图绘制图层,右键可以擦除</para>
  133. /// <para>FixedDrawLayer:地图绘制层,右键无法擦除</para>
  134. /// <para>PosLayer:定位点绘制专用图层</para>
  135. /// </summary>
  136. /// <param name="ctrl"></param>
  137. /// <returns></returns>
  138. public static MapControl UseDefalutOptions(this MapControl ctrl)
  139. {
  140. var barM = new BarManager();
  141. barM.BeginInit();
  142. barM.Form = ctrl;
  143. var mapMeun = new PopupMenu() { Manager = barM };
  144. var posMenu = new PopupMenu() { Manager = barM };
  145. var rectMenu = new PopupMenu() { Manager = barM };
  146. barM.EndInit();
  147. listMapCtrl.Add(ctrl);
  148. var innerData = new InnerData();
  149. innerData.barM = barM;
  150. innerData.mapMenu = mapMeun;
  151. innerData.posMenu = posMenu;
  152. innerData.rectMenu = rectMenu;
  153. innerData.mapToolTip = new ToolTipController();
  154. innerData.mapToolTip.InitialDelay = 10;
  155. innerData.mapToolTip.KeepWhileHovered = true;
  156. innerData.mapToolTip.ReshowDelay = 10;
  157. innerData.mapToolTip.ShowBeak = true;
  158. innerData.mapToolTip.ToolTipAnchor = DevExpress.Utils.ToolTipAnchor.Cursor;
  159. innerData.mapToolTip.ToolTipType = ToolTipType.SuperTip;
  160. ctrl.Tag = innerData;
  161. ctrl.ToolTipController = innerData.mapToolTip;
  162. ctrl.ToolTipController.BeforeShow += (sender, e) =>
  163. {
  164. if (e.SelectedObject == null) return;
  165. SuperToolTip superToolTip = new SuperToolTip();
  166. if (e.SelectedObject.ToString() == ItemsEditorPanelAction.AddRectangle.ToString())
  167. {
  168. e.ToolTip = "绘制矩形";
  169. return;
  170. }
  171. else if (e.SelectedObject is MapDot mapDot)
  172. {
  173. if (mapDot == null) return;
  174. var posItem = mapDot.Tag as PosData;
  175. if (mapDot == null || posItem == null) return;
  176. if (posItem.ClusterCount == 1)
  177. {
  178. var props = posItem.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
  179. var list = new List<(int Index, string Name, string Format, object Value)>();
  180. foreach (var prop in props)
  181. {
  182. var attrToolTip = prop.GetCustomAttribute<ToolTipAttribute>();
  183. if (attrToolTip == null) continue;
  184. string toolTipFormat = attrToolTip.Format;
  185. var val = prop.GetValue(posItem);
  186. string displayName = prop.Name;
  187. var attrDisplay = prop.GetCustomAttribute<DisplayAttribute>();
  188. if (attrDisplay != null && !string.IsNullOrWhiteSpace(attrDisplay.Name))
  189. displayName = attrDisplay.Name;
  190. int index = attrToolTip.Index;
  191. list.Add((index, displayName, toolTipFormat, val));
  192. }
  193. list = list.OrderBy(p => p.Index).ToList();
  194. foreach ((int Index, string Name, string Format, object val) in list)
  195. {
  196. string f = null;
  197. if (val is DateTime)
  198. {
  199. f = "yyyy-MM-dd HH:mm:ss";
  200. }
  201. else if (val is float || val is double || val is decimal)
  202. {
  203. f = "f4";
  204. }
  205. if (!string.IsNullOrWhiteSpace(Format))
  206. f = Format;
  207. string valStr;
  208. if (!string.IsNullOrWhiteSpace(f))
  209. valStr = ((dynamic)val).ToString(f);
  210. else
  211. valStr = val.ToString();
  212. ToolTipItem tipItem = new ToolTipItem();
  213. tipItem.Text = $"{Name}:{valStr}";
  214. superToolTip.Items.Add(tipItem);
  215. }
  216. }
  217. else
  218. {
  219. ToolTipItem tipItem = new ToolTipItem();
  220. tipItem.Text = $"当前位置附近有{posItem.ClusterCount}个定位点,放大可查看";
  221. superToolTip.Items.Add(tipItem);
  222. }
  223. e.SuperTip = superToolTip;
  224. }
  225. else if (e.SelectedObject is MapCustomElement ele)
  226. {
  227. var find = innerData.mMapStorageFixed.Items.Where(p => (p is MapCustomElement pp) && p != ele && pp.Location.Equals(ele.Location));
  228. StringBuilder sb = new StringBuilder();
  229. sb.Append(((object[])ele.Tag)[1]);
  230. foreach (var item in find)
  231. {
  232. sb.Append("\r\n");
  233. sb.Append("-------------------");
  234. sb.Append("\r\n");
  235. sb.Append(((object[])item.Tag)[1]);
  236. }
  237. ele.ToolTipPattern = sb.ToString();
  238. }
  239. };
  240. ctrl.MouseDown += (sender, e) =>
  241. {
  242. if (e.Button == MouseButtons.Right)
  243. {
  244. var hitInfo = ctrl.CalcHitInfo(e.Location);
  245. if (hitInfo.InMapRectangle && innerData.rangeItem != null)
  246. {
  247. rectMenu?.ShowPopup(Cursor.Position);
  248. }
  249. else if (hitInfo.InMapDot && hitInfo.MapDot.Tag is PosData)
  250. {
  251. var selectPos = (PosData)hitInfo.MapDot.Tag;
  252. if (!selectPos.Selected)
  253. {
  254. selectPos.Selected = true;
  255. ctrl.UpdatePosItem(selectPos);
  256. }
  257. if (selectPos.ClusterCount == 1)
  258. {
  259. posMenu?.ShowPopup(Cursor.Position);//选中了原始MapItem
  260. }
  261. else
  262. {
  263. //选中了聚合后的MapItem
  264. }
  265. }
  266. else
  267. {
  268. var geoPoint = ctrl.ScreenPointToCoordPoint(e.Location) as GeoPoint;
  269. innerData._mapMenuGeoPoint = geoPoint;
  270. innerData.mapMenu?.ShowPopup(Cursor.Position);
  271. }
  272. }
  273. else
  274. {
  275. innerData.mouseLeftDown = true;
  276. innerData.barM.CloseMenus();
  277. var hitInfo = ctrl.CalcHitInfo(e.Location);
  278. if (hitInfo.InMapDot && hitInfo.MapDot.Tag is PosData)
  279. {
  280. var selectPos = hitInfo.MapDot.Tag as PosData;
  281. if (!selectPos.Selected)
  282. {
  283. selectPos.Selected = true;
  284. ctrl.UpdatePosItem(selectPos);
  285. }
  286. }
  287. }
  288. };
  289. ctrl.MouseUp += (sender, e) =>
  290. {
  291. innerData.mouseLeftDown = false;
  292. };
  293. //中心点、缩放级别
  294. ctrl.MinZoomLevel = 3;
  295. ctrl.ZoomLevel = 5;
  296. ctrl.MaxZoomLevel = 14;
  297. ctrl.CenterPoint = new GeoPoint(18, 110);
  298. //禁用多余特效
  299. ctrl.EnableDelayedScrolling = true;
  300. ctrl.RenderMode = RenderMode.DirectX;
  301. ctrl.EnableAnimation = false;
  302. ctrl.EnableRotation = false;
  303. //ctrl.ShowSearchPanel = false;
  304. ctrl.SearchPanelOptions.Visible = false;
  305. ctrl.SelectionMode = ElementSelectionMode.Single;//只能单选图层上的元素
  306. ((GeoMapCoordinateSystem)ctrl.CoordinateSystem).CircularScrollingMode = CircularScrollingMode.TilesAndVectorItems;
  307. //地图下方导航栏
  308. ctrl.NavigationPanelOptions.Height = 35;
  309. ctrl.NavigationPanelOptions.BackgroundStyle.Fill = Color.Transparent;
  310. ctrl.NavigationPanelOptions.ShowScrollButtons = false;
  311. ctrl.NavigationPanelOptions.ShowZoomTrackbar = false;
  312. ctrl.NavigationPanelOptions.ShowCoordinates = true;
  313. ctrl.NavigationPanelOptions.ShowKilometersScale = false;
  314. ctrl.NavigationPanelOptions.ShowMilesScale = false;
  315. ctrl.NavigationPanelOptions.CoordinatesStyle.Font = new Font("微软雅黑", 10F);
  316. ctrl.NavigationPanelOptions.ScaleStyle.Font = new Font("微软雅黑", 10F);
  317. // Create ImageTileLayer
  318. ImageLayer layer = new ImageLayer() { Name = "ImageTileLayer" };
  319. //bool localGmdbDataEnable = false;//本地Data.Gmdb是否可用,可用时读取本地瓦片,否则执行Http请求资源
  320. //var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
  321. //if (files.Length > 0)
  322. //{
  323. // try
  324. // {
  325. // string conStr = string.Format("Data Source=\"{0}\";Page Size=32768", files[0]);
  326. // var con = new SQLiteConnection(conStr);
  327. // con.Open();
  328. // con.Close();
  329. // localGmdbDataEnable = true;
  330. // }
  331. // catch (Exception ex)
  332. // {
  333. // Console.Error.WriteLine(ex.Message);
  334. // }
  335. //}
  336. //if (localGmdbDataEnable)
  337. //{
  338. // var provider = new ImageTileDataProvider();//地图瓦片提供者
  339. // provider.TileSource = new ImageTileSource();//地图瓦片数据源接口实现
  340. // layer.DataProvider = provider;
  341. //}
  342. //else
  343. //{
  344. // var provider = new HttpMapDataProvider();
  345. // layer.DataProvider = provider;
  346. //}
  347. ctrl.Layers.Add(layer);
  348. //地图绘制加载(标点、测距、框选等元素载体图层).用来绘制可擦除的元素
  349. var layerDraw = new VectorItemsLayer() { Name = "DrawLayer" };
  350. var drawDataStorage = new MapItemStorage();
  351. layerDraw.Data = drawDataStorage;
  352. ctrl.Layers.Add(layerDraw);
  353. innerData.mMapStorage = drawDataStorage;
  354. //绘制图层,不可手动擦除,一般用来绘制卫星、参考站等固定元素
  355. var layerDrawFixed = new VectorItemsLayer() { Name = "FixedDrawLayer" };
  356. var drawDataStorageFixed = new MapItemStorage();
  357. layerDrawFixed.Data = drawDataStorageFixed;
  358. ctrl.Layers.Add(layerDrawFixed);
  359. innerData.mMapStorageFixed = drawDataStorageFixed;
  360. //定位点专用PosLayer
  361. var layerPos = new VectorItemsLayer() { Name = "PosLayer" };
  362. layerPos.ToolTipPattern = "Test";//随便给一个,不然不会显示定位点的tooltip
  363. layerPos.AllowEditItems = true;
  364. layerPos.EnableHighlighting = false;
  365. layerPos.EnableSelection = false;
  366. ctrl.Layers.Add(layerPos);
  367. var posStorge = new MapItemStorage();
  368. layerPos.Data = posStorge;
  369. innerData.posStorge = posStorge;
  370. return ctrl;
  371. }
  372. /// <summary>
  373. /// 在框选矩形上增加右键菜单
  374. /// </summary>
  375. /// <param name="ctrl"></param>
  376. /// <param name="caption"></param>
  377. /// <param name="img"></param>
  378. /// <param name="action">一个回调,参数为选中的定位点</param>
  379. /// <returns></returns>
  380. public static MapControl AddPosMenu<T>(this MapControl ctrl, string caption, SvgImage img, Action<T> action, Func<T, bool> showCondition = null) where T : PosData, new()
  381. {
  382. var btnCustom = new BarButtonItem() { Caption = caption };
  383. btnCustom.ImageOptions.SvgImage = img;
  384. btnCustom.Tag = ctrl;
  385. var innerData = ctrl.Tag as InnerData;
  386. btnCustom.ItemClick += (sender, e) =>
  387. {
  388. action((T)innerData.preSelectedItem.Tag);
  389. };
  390. innerData.barM.BeginInit();
  391. innerData.barM.Items.Add(btnCustom);
  392. innerData.posMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
  393. innerData.barM.EndInit();
  394. innerData.posMenu.BeforePopup += (sender, e) =>
  395. {
  396. if (showCondition == null)
  397. btnCustom.Visibility = BarItemVisibility.Always;
  398. else
  399. {
  400. bool showBtn = showCondition((T)innerData.preSelectedItem.Tag);
  401. if (showBtn)
  402. btnCustom.Visibility = BarItemVisibility.Always;
  403. else
  404. btnCustom.Visibility = BarItemVisibility.Never;
  405. }
  406. };
  407. return ctrl;
  408. }
  409. /// <summary>
  410. /// 在地图上增加右键菜单
  411. /// </summary>
  412. /// <param name="ctrl"></param>
  413. /// <param name="caption"></param>
  414. /// <param name="img"></param>
  415. /// <param name="action">一个回调,参数为点击位置的经纬度</param>
  416. /// <returns></returns>
  417. public static MapControl AddMapMenu(this MapControl ctrl, string caption, SvgImage img, Action<double, double> action)
  418. {
  419. var btnCustom = new BarButtonItem() { Caption = caption, Name = caption };
  420. btnCustom.ImageOptions.SvgImage = img;
  421. btnCustom.Tag = ctrl;
  422. var innerData = ctrl.Tag as InnerData;
  423. btnCustom.ItemClick += (sender, e) =>
  424. {
  425. action(innerData._mapMenuGeoPoint.Longitude, innerData._mapMenuGeoPoint.Latitude);
  426. };
  427. innerData.barM.BeginInit();
  428. innerData.barM.Items.Add(btnCustom);
  429. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
  430. innerData.barM.EndInit();
  431. return ctrl;
  432. }
  433. /// <summary>
  434. /// 在框选矩形上增加右键菜单
  435. /// </summary>
  436. /// <param name="ctrl"></param>
  437. /// <param name="caption"></param>
  438. /// <param name="img"></param>
  439. /// <param name="action">一个回调,参数为框选的定位点</param>
  440. /// <returns></returns>
  441. public static MapControl AddRectMenu<T>(this MapControl ctrl, string caption, SvgImage img, Action<IEnumerable<T>> action) where T : PosData, new()
  442. {
  443. var btnCustom = new BarButtonItem() { Caption = caption };
  444. btnCustom.ImageOptions.SvgImage = img;
  445. btnCustom.Tag = ctrl;
  446. btnCustom.ItemClick += (sender, e) =>
  447. {
  448. var data = ctrl.GetRectPosItem<T>();
  449. action(data);
  450. };
  451. var innerData = ctrl.Tag as InnerData;
  452. innerData.barM.BeginInit();
  453. innerData.barM.Items.Add(btnCustom);
  454. innerData.rectMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
  455. innerData.barM.EndInit();
  456. return ctrl;
  457. }
  458. /// <summary>
  459. /// 重新设置定位数据
  460. /// </summary>
  461. /// <typeparam name="T"></typeparam>
  462. /// <param name="items">数据源(指定null或空集合可以清空已有数据)</param>
  463. /// <param name="clearDrawLayer">是否清除DrawLayer上临时绘制的内容</param>
  464. public static void SetPosDataSource<T>(this MapControl ctrl, IEnumerable<T> items, bool clearDrawLayer = true) where T : PosData, new()
  465. {
  466. var innerData = ctrl.Tag as InnerData;
  467. innerData._dataCache.Clear();
  468. if (clearDrawLayer)
  469. ctrl.ClearDrawObj();
  470. innerData.posStorge.Items.Clear();
  471. if (items == null || !items.Any())
  472. {
  473. ctrl.Refresh();
  474. return;
  475. }
  476. List<MapDot> list = new List<MapDot>();
  477. for (int i = 0; i < items.Count(); i++)
  478. {
  479. var p = items.ElementAt(i);
  480. if (p.PosLon > 180) continue;
  481. var mapItem = new MapDot()
  482. {
  483. EnableHighlighting = DefaultBoolean.True,
  484. EnableSelection = DefaultBoolean.False,
  485. CanMove = false,
  486. Visible = p.Visible,
  487. IsHitTestVisible = true,
  488. Fill = ColorHelper.IsHtmlColor(p.ColorKey) ? ColorTranslator.FromHtml(p.ColorKey) : ColorHelper.GetColor(p.ColorKey),
  489. Size = _dotSize,
  490. Tag = items.ElementAt(i),
  491. Location = new GeoPoint(p.PosLat, p.PosLon)
  492. };
  493. list.Add(mapItem);
  494. innerData._dataCache.Add(p, mapItem);
  495. }
  496. innerData.posStorge.Items.AddRange(list);
  497. }
  498. /// <summary>
  499. /// 定位图层数据源添加一个定位点
  500. /// </summary>
  501. /// <typeparam name="T"></typeparam>
  502. /// <param name="item"></param>
  503. public static void AddPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
  504. {
  505. if (item.PosLon > 180) return;
  506. var innerData = ctrl.Tag as InnerData;
  507. var mapItem = new MapDot()
  508. {
  509. EnableHighlighting = DefaultBoolean.True,
  510. EnableSelection = DefaultBoolean.False,
  511. CanMove = false,
  512. Visible = item.Visible,
  513. IsHitTestVisible = true,
  514. Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey),
  515. Size = _dotSize,
  516. Tag = item,
  517. Location = new GeoPoint(item.PosLat, item.PosLon)
  518. };
  519. innerData._dataCache.Add(item, mapItem);
  520. innerData.posStorge.Items.Add(mapItem);
  521. }
  522. /// <summary>
  523. /// 定位图层数据源删除定位点
  524. /// </summary>
  525. /// <typeparam name="T"></typeparam>
  526. /// <param name="ctrl"></param>
  527. /// <param name="data"></param>
  528. public static void DelPosItem<T>(this MapControl ctrl, IEnumerable<T> data) where T : PosData, new()
  529. {
  530. if (data == null || !data.Any()) return;
  531. foreach (var item in data)
  532. {
  533. ctrl.DelPosItem(item);
  534. }
  535. ctrl.Refresh();
  536. }
  537. /// <summary>
  538. /// 定位图层数据源删除定位点
  539. /// </summary>
  540. /// <typeparam name="T"></typeparam>
  541. /// <param name="ctrl"></param>
  542. /// <param name="data"></param>
  543. public static void DelPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
  544. {
  545. if (item == null) return;
  546. var innerData = ctrl.Tag as InnerData;
  547. if (innerData._dataCache.ContainsKey(item))
  548. {
  549. innerData.posStorge.Items.Remove(innerData._dataCache[item]);
  550. innerData._dataCache.Remove(item);
  551. }
  552. ctrl.Refresh();
  553. }
  554. /// <summary>
  555. /// 定位图层数据源删除定位点
  556. /// </summary>
  557. /// <typeparam name="T"></typeparam>
  558. /// <param name="ctrl"></param>
  559. /// <param name="data"></param>
  560. public static void DelPosItem<T>(this MapControl ctrl, Func<T, bool> predicate) where T : PosData, new()
  561. {
  562. var innerData = ctrl.Tag as InnerData;
  563. List<PosData> keys = new List<PosData>();
  564. foreach (var item in innerData._dataCache.Keys)
  565. {
  566. if (predicate((T)item))
  567. keys.Add(item);
  568. }
  569. foreach (var item in keys)
  570. {
  571. ctrl.DelPosItem(item);
  572. }
  573. ctrl.Refresh();
  574. }
  575. /// <summary>
  576. /// 更新定位数据(可以更新可见性、颜色、经纬度、选中状态)
  577. /// </summary>
  578. /// <typeparam name="T"></typeparam>
  579. /// <param name="ctrl"></param>
  580. /// <param name="item"></param>
  581. /// <param name="setCenter">是否将这个点设置到地图中心显示</param>
  582. public static void UpdatePosItem<T>(this MapControl ctrl, T item, bool setCenter = false) where T : PosData, new()
  583. {
  584. if (item == null) return;
  585. var innerData = ctrl.Tag as InnerData;
  586. if (innerData._dataCache.ContainsKey(item))
  587. {
  588. var mapDot = innerData._dataCache[item] as MapDot;
  589. mapDot.Visible = item.Visible;//外部修改了可见性
  590. mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
  591. mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
  592. if (mapDot.Size != (item.Selected ? _selectedDotSize : _dotSize))//外部修改了选中状态
  593. {
  594. mapDot.Size = item.Selected ? _selectedDotSize : _dotSize;
  595. mapDot.StrokeWidth = item.Selected ? 0 : 1;
  596. if (item.ClusterCount > 1)
  597. {
  598. if (innerData._clusterCache.TryGetValue(item.ClusterKey, out MapItem clusterItem))
  599. {
  600. (clusterItem as MapDot).Size = item.Selected ? _selectedDotSize : _dotSize;
  601. }
  602. }
  603. if (mapDot.ClusteredItems.Any())
  604. (mapDot.ClusteredItems[0] as MapDot).Size = _selectedDotSize;
  605. if (item.Selected)
  606. {
  607. //让选中的Item在上层
  608. var idx = innerData.posStorge.Items.IndexOf(mapDot);
  609. innerData.posStorge.Items.Swap(idx, innerData.posStorge.Items.Count - 1);
  610. //innerData.posStorge.Items.Add(mapDot);
  611. //需要将上次选中的点设置为未选中
  612. if (innerData.preSelectedItem != null)
  613. {
  614. innerData.preSelectedItem.Size = _dotSize;
  615. (innerData.preSelectedItem.Tag as PosData).Selected = false;
  616. if ((innerData.preSelectedItem.Tag as PosData).ClusterCount > 1)
  617. {
  618. if (innerData._clusterCache.TryGetValue((innerData.preSelectedItem.Tag as PosData).ClusterKey, out MapItem clusterItem))
  619. {
  620. (clusterItem as MapDot).Size = _dotSize + 2;
  621. }
  622. }
  623. }
  624. innerData.preSelectedItem = mapDot;
  625. }
  626. }
  627. if (setCenter && item.Visible)
  628. ctrl.SetCenterPoint(item.PosLon, item.PosLat, false);
  629. }
  630. }
  631. /// <summary>
  632. /// 更新定位数据(可以更新可见性、颜色、经纬度)
  633. /// </summary>
  634. /// <typeparam name="T"></typeparam>
  635. /// <param name="ctrl"></param>
  636. /// <param name="item"></param>
  637. public static void UpdatePosItem<T>(this MapControl ctrl, IEnumerable<T> items) where T : PosData, new()
  638. {
  639. if (items == null || !items.Any()) return;
  640. var innerData = ctrl.Tag as InnerData;
  641. foreach (var item in items)
  642. {
  643. if (innerData._dataCache.ContainsKey(item))
  644. {
  645. var mapDot = innerData._dataCache[item] as MapDot;
  646. mapDot.Visible = item.Visible;//外部修改了可见性
  647. mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
  648. mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
  649. }
  650. }
  651. }
  652. /// <summary>
  653. /// 设置地图中心点
  654. /// </summary>
  655. /// <param name="ctrl"></param>
  656. /// <param name="lon"></param>
  657. /// <param name="lat"></param>
  658. /// <param name="animated">是否显示动画</param>
  659. /// <returns></returns>
  660. public static MapControl SetCenterPoint(this MapControl ctrl, double lon, double lat, bool animated = false)
  661. {
  662. ctrl.SetCenterPoint(new GeoPoint(lat, lon), animated);
  663. return ctrl;
  664. }
  665. /// <summary>
  666. /// 地图上添加图片
  667. /// </summary>
  668. /// <param name="ctrl"></param>
  669. /// <param name="tag"></param>
  670. /// <param name="imgLat"></param>
  671. /// <param name="imgLon"></param>
  672. /// <param name="img"></param>
  673. /// <param name="toolTip"></param>
  674. public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, Image img, string toolTip = "")
  675. {
  676. var innerData = ctrl.Tag as InnerData;
  677. var item = new MapCustomElement() { Tag =new object[] { tag, toolTip } };
  678. item.UseAnimation = false;
  679. item.BackgroundDrawingMode = ElementState.None;
  680. item.Location = new GeoPoint(imgLat, imgLon);
  681. item.Image = img;
  682. item.ToolTipPattern = toolTip;
  683. innerData.mMapStorageFixed.Items.Add(item);
  684. }
  685. /// <summary>
  686. /// 地图上添加指定大小图片
  687. /// </summary>
  688. /// <param name="ctrl"></param>
  689. /// <param name="tag"></param>
  690. /// <param name="imgLat"></param>
  691. /// <param name="imgLon"></param>
  692. /// <param name="img"></param>
  693. /// <param name="size"></param>
  694. /// <param name="toolTip"></param>
  695. public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, SvgImage img, string toolTip = "")
  696. {
  697. var innerData = ctrl.Tag as InnerData;
  698. var item = new MapCustomElement() { Tag =new object[] { tag, toolTip } };
  699. item.UseAnimation = false;
  700. item.BackgroundDrawingMode = ElementState.None;
  701. item.Location = new GeoPoint(imgLat, imgLon);
  702. item.SvgImage = img;
  703. item.ToolTipPattern = toolTip;
  704. innerData.mMapStorageFixed.Items.Add(item);
  705. }
  706. public static void DelFixedImg(this MapControl ctrl, string tag)
  707. {
  708. var innerData = ctrl.Tag as InnerData;
  709. var delItems = innerData.mMapStorageFixed.Items.ToList().FindAll(p => ((object[])p.Tag)[0].ToString() == tag);
  710. foreach (var item in delItems)
  711. {
  712. innerData.mMapStorageFixed.Items.Remove(item);
  713. }
  714. }
  715. /// <summary>
  716. /// 获取当前矩形框选的定位点
  717. /// </summary>
  718. /// <param name="ctrl"></param>
  719. /// <returns></returns>
  720. public static IEnumerable<T> GetRectPosItem<T>(this MapControl ctrl) where T : PosData, new()
  721. {
  722. var innerData = ctrl.Tag as InnerData;
  723. if (innerData.CurrentRect == default) return new List<T>();
  724. var rect = ctrl.GetCurrentRect();
  725. double startLon = rect.starLon;
  726. double startLat = rect.startLat;
  727. double endLon = rect.endLon;
  728. double endLat = rect.endLat;
  729. var temp = innerData._dataCache.Keys.Where(p => p.InRectangle(startLon, startLat, endLon, endLat));
  730. var res = temp.Select(p => (T)p);
  731. return res;
  732. }
  733. /// <summary>
  734. /// <para>设置地图瓦片Http地址.格式如http://192.168.100.63:58089</para>
  735. /// <para>当客户端本地运行目录或子目录存在Data.gmdb时Http接口不会被调用</para>
  736. /// </summary>
  737. /// <param name="ctrl"></param>
  738. /// <param name="httpAddr">such as http://192.168.100.63:58089</param>
  739. /// <returns></returns>
  740. public static MapControl SetMapDataHttpAddr(this MapControl ctrl, string httpAddr)
  741. {
  742. var provider = ctrl.GetImageLayer().DataProvider;
  743. if (provider is HttpMapDataProvider)
  744. {
  745. var tileSource = ((provider as HttpMapDataProvider).TileSource as HttpTileSource);
  746. tileSource.HttpServerAddr = httpAddr;
  747. }
  748. return ctrl;
  749. }
  750. /// <summary>
  751. /// 定位点使用内置聚合器
  752. /// </summary>
  753. /// <param name="ctrl"></param>
  754. /// <returns></returns>
  755. public static MapControl UseCluster(this MapControl ctrl)
  756. {
  757. var innerData = ctrl.Tag as InnerData;
  758. innerData.posStorge.Clusterer = new PosClusterer(ctrl);//定位点聚合器
  759. return ctrl;
  760. }
  761. /// <summary>
  762. /// 为地图添加右键测距功能
  763. /// </summary>
  764. /// <returns></returns>
  765. public static MapControl UseDistanceLine(this MapControl ctrl)
  766. {
  767. var btnDistance = new BarButtonItem() { Caption = "测距" };
  768. btnDistance.ImageOptions.SvgImage = SvgHelper.CreateDistanceLine();
  769. btnDistance.Tag = ctrl;
  770. btnDistance.ItemClick += DistanceLine_ItemClick;
  771. var innerData = ctrl.Tag as InnerData;
  772. innerData.barM.BeginInit();
  773. innerData.barM.Items.Add(btnDistance);
  774. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnDistance));
  775. innerData.barM.EndInit();
  776. return ctrl;
  777. }
  778. /// <summary>
  779. /// 使用航迹
  780. /// </summary>
  781. /// <param name="ctrl"></param>
  782. /// <param name="onClickChanged">点击事件返回当前经纬度</param>
  783. /// <returns></returns>
  784. public static MapControl UseHJ(this MapControl ctrl, Action<(double Lon, double Lat)> onClickChanged = null)
  785. {
  786. var btnHJ = new BarButtonItem() { Caption = "航迹" };
  787. btnHJ.ImageOptions.SvgImage = SvgHelper.CreateMarkDot();
  788. btnHJ.Tag = ctrl;
  789. var innerData = ctrl.Tag as InnerData;
  790. innerData.onClickChanged = onClickChanged;
  791. btnHJ.ItemClick += (sender, e) =>
  792. {
  793. ctrl.MapEditor.SetEditMode();
  794. ctrl.MouseClick += AddHJPoint;
  795. ctrl.DoubleClick += (sender1, e1) =>
  796. {
  797. ctrl.MouseClick -= AddHJPoint;
  798. };
  799. };
  800. innerData.barM.BeginInit();
  801. innerData.barM.Items.Add(btnHJ);
  802. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnHJ));
  803. innerData.barM.EndInit();
  804. return ctrl;
  805. }
  806. /// <summary>
  807. /// 添加航迹点
  808. /// </summary>
  809. /// <typeparam name="T"></typeparam>
  810. /// <param name="ctrl"></param>
  811. /// <param name="item"></param>
  812. public static void AddHJPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
  813. {
  814. if (item.PosLon > 180) return;
  815. var innerData = ctrl.Tag as InnerData;
  816. var mapItem = new MapDot()
  817. {
  818. EnableHighlighting = DefaultBoolean.True,
  819. EnableSelection = DefaultBoolean.False,
  820. CanMove = false,
  821. Visible = item.Visible,
  822. IsHitTestVisible = true,
  823. Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey),
  824. Size = _dotSize,
  825. Tag = item,
  826. Location = new GeoPoint(item.PosLat, item.PosLon),
  827. ToolTipPattern = "dd"
  828. };
  829. innerData.mMapStorage.Items.Add(mapItem);
  830. }
  831. private static void AddHJPoint(object sender, MouseEventArgs e)
  832. {
  833. var innerData = (sender as MapControl).Tag as InnerData;
  834. var ctrl = sender as MapControl;
  835. var geoPoint = ctrl.ScreenPointToCoordPoint(e.Location) as GeoPoint;
  836. innerData.onClickChanged?.Invoke((geoPoint.Longitude, geoPoint.Latitude));
  837. }
  838. /// <summary>
  839. /// 为地图添加右键标点功能
  840. /// </summary>
  841. /// <param name="ctrl"></param>
  842. /// <param name="menu"></param>
  843. /// <param name="item"></param>
  844. /// <returns></returns>
  845. public static MapControl UseMarkDot(this MapControl ctrl)
  846. {
  847. var btnMarkDot = new BarButtonItem() { Caption = "标点" };
  848. btnMarkDot.ImageOptions.SvgImage = SvgHelper.CreateMarkDot();
  849. btnMarkDot.Tag = ctrl;
  850. btnMarkDot.ItemClick += MarkDot_ItemClick;
  851. var innerData = ctrl.Tag as InnerData;
  852. innerData.barM.BeginInit();
  853. innerData.barM.Items.Add(btnMarkDot);
  854. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnMarkDot));
  855. innerData.barM.EndInit();
  856. return ctrl;
  857. }
  858. /// <summary>
  859. /// 为地图添加清除功能
  860. /// </summary>
  861. /// <param name="ctrl"></param>
  862. /// <param name="item"></param>
  863. /// <returns></returns>
  864. public static MapControl UseClearAll(this MapControl ctrl)
  865. {
  866. var btnClearAll = new BarButtonItem() { Caption = "清除" };
  867. btnClearAll.ImageOptions.SvgImage = SvgHelper.CreateClear();
  868. btnClearAll.Tag = ctrl;
  869. btnClearAll.ItemClick += (sender, e) => ctrl.ClearDrawObj();
  870. var innerData = ctrl.Tag as InnerData;
  871. innerData.barM.BeginInit();
  872. innerData.barM.Items.Add(btnClearAll);
  873. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnClearAll));
  874. innerData.barM.EndInit();
  875. return ctrl;
  876. }
  877. /// <summary>
  878. /// 为地图添加导出图片功能
  879. /// </summary>
  880. /// <param name="ctrl"></param>
  881. /// <param name="item"></param>
  882. /// <returns></returns>
  883. public static MapControl UseExportImg(this MapControl ctrl)
  884. {
  885. var btnExportImg = new BarButtonItem() { Caption = "导出图片" };
  886. btnExportImg.ImageOptions.SvgImage = SvgHelper.CreateExportImg();
  887. btnExportImg.Tag = ctrl;
  888. btnExportImg.ItemClick += ExportImg_ItemClick;
  889. var innerData = ctrl.Tag as InnerData;
  890. innerData.barM.BeginInit();
  891. innerData.barM.Items.Add(btnExportImg);
  892. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportImg));
  893. innerData.barM.EndInit();
  894. return ctrl;
  895. }
  896. /// <summary>
  897. /// 为地图添加导出图片功能
  898. /// </summary>
  899. /// <param name="ctrl"></param>
  900. /// <param name="item"></param>
  901. /// <returns></returns>
  902. public static MapControl UseExportCsv(this MapControl ctrl, bool exportHeader = true)
  903. {
  904. var innerData = ctrl.Tag as InnerData;
  905. var btnExportCsv = new BarButtonItem() { Caption = "导出Csv" };
  906. btnExportCsv.ImageOptions.SvgImage = SvgHelper.CreateExportCsv();
  907. btnExportCsv.Tag = ctrl;
  908. btnExportCsv.ItemClick += (sender, e) =>
  909. {
  910. if (!innerData._dataCache.Any()) return;
  911. bool exportSigTime = false;
  912. Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
  913. var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  914. List<(int ColumnIndex, PropertyInfo Prop, string Header)> listPorps = new List<(int, PropertyInfo, string)>();
  915. foreach (var prop in props)
  916. {
  917. ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
  918. if (attrExport == null) continue;
  919. if (prop.Name == nameof(PosData.SigTime))
  920. exportSigTime = true;
  921. if (!string.IsNullOrWhiteSpace(attrExport.Format))
  922. {
  923. cellFormats.Add(prop.Name, attrExport.Format);
  924. }
  925. if (attrExport.ColumnIndex == -1)
  926. attrExport.ColumnIndex = 10000;
  927. var attrDisplay = prop.GetCustomAttribute<DisplayAttribute>();
  928. if (attrDisplay != null && !string.IsNullOrWhiteSpace(attrDisplay.Name))
  929. listPorps.Add((attrExport.ColumnIndex, prop, attrDisplay.Name));
  930. else
  931. listPorps.Add((attrExport.ColumnIndex, prop, prop.Name));
  932. }
  933. listPorps = listPorps.OrderBy(p => p.ColumnIndex).ToList();
  934. using (var dialog = new SaveFileDialog())
  935. {
  936. dialog.Filter = "CSV文件|*.csv";
  937. dialog.AddExtension = true;
  938. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.csv";
  939. if (dialog.ShowDialog() == DialogResult.OK)
  940. {
  941. var list = innerData._dataCache.Keys as IEnumerable<PosData>;
  942. if (exportSigTime)
  943. list = list.OrderByDescending(p => p.SigTime);//如果导出了SigTime,则自动按照SigTime降序排列后导出
  944. StreamWriter sw = new StreamWriter(dialog.FileName, false, new UTF8Encoding(true));//utf8-bom
  945. if (exportHeader)
  946. {
  947. foreach (var prop in listPorps)
  948. {
  949. sw.Write($"{prop.Header},");
  950. }
  951. sw.WriteLine();
  952. }
  953. WaitHelper.ShowOverlayForm(ctrl);
  954. long count = list.Count() * listPorps.Count;
  955. int idx = 1;
  956. foreach (var item in list)
  957. {
  958. foreach (var prop in listPorps)
  959. {
  960. WaitHelper.UpdateOverlyText($"{idx * 100 / count}%");
  961. var value = prop.Prop.GetValue(item);
  962. string str = null;
  963. if (cellFormats.ContainsKey(prop.Prop.Name))
  964. {
  965. str = ((dynamic)value).ToString(cellFormats[prop.Prop.Name]);
  966. }
  967. else
  968. {
  969. if (value is DateTime)
  970. str = $"{(DateTime)value:yyyy-MM-dd HH:mm:ss}";
  971. else if (value is float || value is double || value is decimal)
  972. {
  973. dynamic valD = value;
  974. str = ((dynamic)value).ToString("f4");
  975. }
  976. }
  977. sw.Write($"{str},");
  978. idx++;
  979. }
  980. sw.WriteLine();
  981. }
  982. sw.Close();
  983. WaitHelper.CloseOverlayForm();
  984. }
  985. }
  986. GC.Collect();
  987. };
  988. innerData.barM.BeginInit();
  989. innerData.barM.Items.Add(btnExportCsv);
  990. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportCsv));
  991. innerData.barM.EndInit();
  992. return ctrl;
  993. }
  994. /// <summary>
  995. /// 为地图添加导出Excel数据功能
  996. /// </summary>
  997. /// <typeparam name="T"></typeparam>
  998. /// <param name="ctrl"></param>
  999. /// <param name="exportHeader">是否导出列头</param>
  1000. /// <returns></returns>
  1001. public static MapControl UseExportXlsx(this MapControl ctrl, bool exportHeader = true)
  1002. {
  1003. Action action = () =>
  1004. {
  1005. var btnExportXlsx = new BarButtonItem() { Caption = "导出Excel" };
  1006. btnExportXlsx.ImageOptions.SvgImage = SvgHelper.CreateExportXlsx();
  1007. var innerData = ctrl.Tag as InnerData;
  1008. innerData.barM.BeginInit();
  1009. innerData.barM.Items.Add(btnExportXlsx);
  1010. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportXlsx));
  1011. innerData.barM.EndInit();
  1012. btnExportXlsx.ItemClick += (sender, e) =>
  1013. {
  1014. if (!innerData._dataCache.Any()) return;
  1015. GridControl gc = new GridControl();
  1016. GridView view = new GridView();
  1017. view.GridControl = gc;
  1018. gc.MainView = view;
  1019. gc.ViewCollection.Add(view);
  1020. view.OptionsPrint.ShowPrintExportProgress = false;
  1021. bool exportSigTime = false;
  1022. Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
  1023. var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  1024. foreach (var prop in props)
  1025. {
  1026. ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
  1027. if (attrExport == null) continue;
  1028. if (prop.Name == nameof(PosData.SigTime))
  1029. exportSigTime = true;
  1030. if (!string.IsNullOrWhiteSpace(attrExport.Format))
  1031. {
  1032. cellFormats.Add(prop.Name, attrExport.Format);
  1033. }
  1034. var col = new GridColumn();
  1035. col.FieldName = prop.Name;
  1036. col.Visible = true;
  1037. var attr = prop.GetCustomAttribute<DisplayAttribute>();
  1038. if (attr != null && !string.IsNullOrWhiteSpace(attr.Name))
  1039. col.Caption = attr.Name;
  1040. else
  1041. col.Caption = prop.Name;
  1042. if (attrExport.ColumnIndex >= 0)
  1043. col.VisibleIndex = attrExport.ColumnIndex;
  1044. view.Columns.Add(col);
  1045. }
  1046. gc.Visible = false;
  1047. gc.Parent = ctrl.Parent;
  1048. using (var dialog = new SaveFileDialog())
  1049. {
  1050. dialog.Filter = "Excel文件|*.xlsx";
  1051. dialog.AddExtension = true;
  1052. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
  1053. if (dialog.ShowDialog() == DialogResult.OK)
  1054. {
  1055. var list = innerData._dataCache.Keys.ToList();
  1056. if (exportSigTime)
  1057. list = list.OrderByDescending(p => p.SigTime).ToList();//如果导出了SigTime,则自动按照SigTime降序排列后导出
  1058. gc.DataSource = list;
  1059. gc.Visible = true;
  1060. var exportType = DevExpress.Export.ExportSettings.DefaultExportType;
  1061. var options = new XlsxExportOptionsEx();
  1062. WaitHelper.ShowOverlayForm(ctrl);
  1063. options.ExportProgress += arg =>
  1064. {
  1065. WaitHelper.UpdateOverlyText($"{arg.ProgressPercentage}%");
  1066. if (arg.ProgressPercentage >= 100)
  1067. {
  1068. WaitHelper.CloseOverlayForm();
  1069. }
  1070. };
  1071. view.OptionsPrint.PrintHeader = exportHeader;
  1072. options.CustomizeCell += arg =>
  1073. {
  1074. arg.Handled = true;
  1075. var aligmentCenter = new XlCellAlignment()
  1076. {
  1077. HorizontalAlignment = XlHorizontalAlignment.Center,
  1078. VerticalAlignment = XlVerticalAlignment.Center
  1079. };
  1080. var aligmentLeft = new XlCellAlignment()
  1081. {
  1082. HorizontalAlignment = XlHorizontalAlignment.Left,
  1083. VerticalAlignment = XlVerticalAlignment.Center
  1084. };
  1085. if (arg.Value is bool)
  1086. {
  1087. arg.Formatting.Alignment = aligmentCenter;
  1088. arg.Value = ((bool)arg.Value) ? "☑" : "☐";
  1089. }
  1090. if (arg.Value is DateTime)
  1091. {
  1092. arg.Formatting.Alignment = aligmentLeft;
  1093. arg.Formatting.FormatType = FormatType.DateTime;
  1094. arg.Formatting.FormatString = "yyyy-MM-dd HH:mm:ss";
  1095. }
  1096. else if (arg.Value is float || arg.Value is double || arg.Value is decimal)
  1097. {
  1098. arg.Formatting.Alignment = aligmentLeft;
  1099. arg.Formatting.FormatType = FormatType.Numeric;
  1100. arg.Formatting.FormatString = "f4";
  1101. }
  1102. if (cellFormats.ContainsKey(arg.ColumnFieldName))
  1103. {
  1104. arg.Formatting.FormatString = cellFormats[arg.ColumnFieldName];
  1105. }
  1106. };
  1107. view.OptionsPrint.ShowPrintExportProgress = false;
  1108. DevExpress.Export.ExportSettings.DefaultExportType = DevExpress.Export.ExportType.DataAware;
  1109. gc.ExportToXlsx(dialog.FileName, options);
  1110. DevExpress.Export.ExportSettings.DefaultExportType = exportType;
  1111. gc.Visible = false;
  1112. }
  1113. }
  1114. gc.Parent = null;
  1115. gc.Dispose();
  1116. GC.Collect();
  1117. };
  1118. };
  1119. if (ctrl.Parent == null)
  1120. {
  1121. ctrl.ParentChanged += (sender, e) => action();
  1122. }
  1123. else
  1124. {
  1125. action();
  1126. }
  1127. return ctrl;
  1128. }
  1129. /// <summary>
  1130. /// 为地图添加矩形框选区域功能
  1131. /// </summary>
  1132. /// <returns></returns>
  1133. public static MapControl UseDrawRect(this MapControl ctrl, Action<(double starLon, double startLat, double centerLon, double centerLat,
  1134. double endLon, double endLat, double lonRange, double latRange)> onRectChanged = null)
  1135. {
  1136. var innerData = ctrl.Tag as InnerData;
  1137. innerData.mOnRectChanged = onRectChanged;
  1138. ctrl.MapEditor.ShowEditorPanel = true;
  1139. ctrl.MapEditor.PanelOptions.ShowAddCalloutButton = false;
  1140. ctrl.MapEditor.PanelOptions.ShowAddCustomElementButton = false;
  1141. ctrl.MapEditor.PanelOptions.ShowAddDotButton = false;
  1142. ctrl.MapEditor.PanelOptions.ShowAddEllipseButton = false;
  1143. ctrl.MapEditor.PanelOptions.ShowAddLineButton = false;
  1144. ctrl.MapEditor.PanelOptions.ShowAddPathButton = false;
  1145. ctrl.MapEditor.PanelOptions.ShowAddPolylineButton = false;
  1146. ctrl.MapEditor.PanelOptions.ShowAddPushpinButton = false;
  1147. ctrl.MapEditor.PanelOptions.ShowAddSplineButton = false;
  1148. ctrl.MapEditor.PanelOptions.ShowEditModeButton = false;
  1149. ctrl.MapEditor.PanelOptions.ShowTransformModeButton = false;
  1150. ctrl.MapEditor.PanelOptions.ShowUndoRedoButtons = false;
  1151. ctrl.MouseMove += DrawRect_MouseMove;
  1152. ctrl.MapEditor.MapItemCreating += (sender, e) =>
  1153. {
  1154. if (!innerData.mouseLeftDown)
  1155. {
  1156. e.Cancel = true;
  1157. return;
  1158. }
  1159. if (!(e.Item is MapRectangle)) return;
  1160. var items = innerData.mMapStorage.Items.ToList().FindAll(p => p.Tag != null && p.Tag.ToString() == "DrawRect");
  1161. ctrl.MapEditor.RemoveItems(items);
  1162. var item = e.Item as MapRectangle;
  1163. item.Tag = "DrawRect";
  1164. item.CanMove = false;
  1165. item.CanResize = false;
  1166. item.EnableSelection = DefaultBoolean.False;
  1167. item.EnableHighlighting = DefaultBoolean.True;
  1168. innerData.rangeItem = item;
  1169. if (innerData.rangeItem.Height == 0 && innerData.rangeItem.Width == 0)
  1170. {
  1171. innerData.rangeItem.Height = 5;
  1172. innerData.rangeItem.Width = 5;
  1173. }
  1174. item.Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209));
  1175. item.Stroke = Color.FromArgb(23, 107, 209);
  1176. item.StrokeWidth = 1;
  1177. innerData.dotItem.Fill = Color.Red;
  1178. innerData.dotItem.Size = 6;
  1179. innerData.dotItem.Location = innerData.rangeItem.GetCenter();
  1180. innerData.mMapStorage.Items.Add(innerData.rangeItem);
  1181. innerData.mMapStorage.Items.Add(innerData.dotItem);
  1182. DrawRect_MouseMove(ctrl, null);
  1183. var layer = ctrl.Layers.Find(p => p.Name == "");
  1184. if (layer != null) ctrl.Layers.Remove(layer);
  1185. };
  1186. ctrl.MapEditor.MapItemEdited += (sender, e) =>
  1187. {
  1188. innerData.drawingRect = e.Action == MapEditorAction.Create;
  1189. };
  1190. return ctrl;
  1191. }
  1192. /// <summary>
  1193. /// 绘制矩形
  1194. /// </summary>
  1195. /// <param name="ctrl"></param>
  1196. /// <param name="startLon"></param>
  1197. /// <param name="startLat"></param>
  1198. /// <param name="endLon"></param>
  1199. /// <param name="endLat"></param>
  1200. public static void DrawRect(this MapControl ctrl, double startLon, double startLat, double endLon, double endLat, bool recCallback = false)
  1201. {
  1202. var innerData = ctrl.Tag as InnerData;
  1203. if (innerData.rangeItem != null)
  1204. innerData.mMapStorage.Items.Remove(innerData.rangeItem);
  1205. if (innerData.dotItem != null)
  1206. innerData.mMapStorage.Items.Remove(innerData.dotItem);
  1207. double centerLon = (startLon + endLon) / 2;
  1208. double centerLat = (startLat + endLat) / 2;
  1209. var size = BoundingRectItemHelper.CalculateRectangleSize(ctrl.CoordinateSystem,
  1210. new GeoPoint(startLat, startLon),
  1211. new GeoPoint(endLat, endLon));
  1212. innerData.dotItem.Location = new GeoPoint(centerLat, centerLon);
  1213. innerData.dotItem.Fill = Color.Red;
  1214. innerData.dotItem.Size = 8;
  1215. var rect = new MapRectangle()
  1216. {
  1217. CanMove = false,
  1218. CanResize = false,
  1219. EnableSelection = DefaultBoolean.False,
  1220. EnableHighlighting = DefaultBoolean.True,
  1221. Tag = "DrawRect",
  1222. Width = size.Width,
  1223. Height = size.Height,
  1224. Location = new GeoPoint(startLat, startLon),
  1225. Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209)),
  1226. Stroke = Color.FromArgb(23, 107, 209),
  1227. StrokeWidth = 1
  1228. };
  1229. innerData.rangeItem = rect;
  1230. innerData.CurrentRect = (startLon, startLat, centerLon, centerLat, endLon, endLat, (endLon - startLon) / 2, (endLat - startLat) / 2);
  1231. innerData.mMapStorage.Items.Add(innerData.rangeItem);
  1232. innerData.mMapStorage.Items.Add(innerData.dotItem);
  1233. if (recCallback)
  1234. innerData.mOnRectChanged?.Invoke(ctrl.GetCurrentRect());
  1235. }
  1236. public static void DrawDtoPonit(this MapControl ctrl, string title, IEnumerable<(double lon, double lat)> lines)
  1237. {
  1238. string identify = "DrawPoint_";
  1239. if (lines == null || !lines.Any()) return;
  1240. var innerData = ctrl.Tag as InnerData;
  1241. List<MapDot> list = new List<MapDot>();
  1242. var color = ColorHelper.GetColor(title);
  1243. for (int i = 0; i < lines.Count(); i++)
  1244. {
  1245. var p = lines.ElementAt(i);
  1246. if (p.lon < -180 || p.lon > 180) continue;
  1247. if (p.lon == 0 && p.lon == 0) continue;
  1248. var mapItem = new MapDot()
  1249. {
  1250. EnableHighlighting = DefaultBoolean.True,
  1251. EnableSelection = DefaultBoolean.False,
  1252. CanMove = false,
  1253. Visible = true,
  1254. IsHitTestVisible = true,
  1255. Fill = color,
  1256. Size = 4,
  1257. Tag = $"{identify}{title}{lines.ElementAt(i).lon}",
  1258. Location = new GeoPoint(p.lat, p.lon),
  1259. ToolTipPattern = $"{title}",
  1260. };
  1261. list.Add(mapItem);
  1262. }
  1263. if (!list.Any()) return;
  1264. innerData.mMapStorage.Items.AddRange(list);
  1265. }
  1266. public static void DrawGdopLine(this MapControl ctrl, IEnumerable<(string wcKm, double lon, double lat)> lines)
  1267. {
  1268. if (lines == null || !lines.Any()) return;
  1269. var innerData = ctrl.Tag as InnerData;
  1270. var wcKm = lines.First().wcKm;
  1271. var polyLine = new MapPolyline()
  1272. {
  1273. Stroke = ColorHelper.GetColor(wcKm),
  1274. StrokeWidth = 2,
  1275. IsGeodesic = true,
  1276. CanResize = false,
  1277. CanEdit = false,
  1278. CanRotate = false,
  1279. IsHitTestVisible = true,
  1280. CanMove = false,
  1281. Tag = $"DrawGdopLine_{wcKm}",
  1282. };
  1283. polyLine.TitleOptions.Pattern = wcKm;
  1284. foreach (var item in lines)
  1285. {
  1286. if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
  1287. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1288. }
  1289. if (!polyLine.Points.Any()) return;
  1290. innerData.mMapStorage.Items.Add(polyLine);
  1291. }
  1292. /// <summary>
  1293. /// 绘制线
  1294. /// </summary>
  1295. /// <param name="ctrl"></param>
  1296. /// <param name="title"></param>
  1297. /// <param name="lines"></param>
  1298. /// <param name="isClear">是否清除上次绘制</param>
  1299. public static void DrawCXLine(this MapControl ctrl, string title, IEnumerable<(double lon, double lat)> lines, bool isClear = true)
  1300. {
  1301. string identify = "DrawCXLine_";
  1302. if (lines == null || !lines.Any()) return;
  1303. var innerData = ctrl.Tag as InnerData;
  1304. if (isClear)
  1305. {
  1306. var mapItem = innerData.mMapStorage.Items.Find(m => m.Tag.ToString().StartsWith(identify));
  1307. if (mapItem != null)
  1308. {
  1309. innerData.mMapStorage.Items.Remove(mapItem);
  1310. }
  1311. }
  1312. var polyLine = new MapPolyline()
  1313. {
  1314. Stroke = Color.Red,
  1315. StrokeWidth = 3,
  1316. CanMove = false,
  1317. Visible = true,
  1318. IsHitTestVisible = true,
  1319. Tag = $"{identify}{title}",
  1320. ToolTipPattern = title,
  1321. };
  1322. foreach (var item in lines)
  1323. {
  1324. if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
  1325. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1326. }
  1327. if (!polyLine.Points.Any()) return;
  1328. innerData.mMapStorage.Items.Add(polyLine);
  1329. }
  1330. public static void DrawErrEllipse(this MapControl ctrl, double r1, double r2, IEnumerable<(double lon, double lat)> lines)
  1331. {
  1332. if (lines == null || !lines.Any()) return;
  1333. var innerData = ctrl.Tag as InnerData;
  1334. //innerData.mMapStorage.Items.Clear();
  1335. var polyLine = new MapPolyline()
  1336. {
  1337. Stroke = Color.Red,
  1338. StrokeWidth = 4,
  1339. IsGeodesic = true,
  1340. CanResize = false,
  1341. CanEdit = false,
  1342. CanRotate = false,
  1343. IsHitTestVisible = true,
  1344. CanMove = false,
  1345. Tag = $"DrawErrEllipse",
  1346. };
  1347. //polyLine.ToolTipPattern = $"长轴:{r1:f1}km\r\n短轴:{r2:f1}km";
  1348. foreach (var item in lines)
  1349. {
  1350. if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
  1351. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1352. }
  1353. if (!polyLine.Points.Any()) return;
  1354. innerData.mMapStorage.Items.Add(polyLine);
  1355. var callout = new DevExpress.XtraMap.MapCallout()
  1356. {
  1357. Text = $"R1={r1:f1}km\r\nR2={r2:f1}km",
  1358. Location = polyLine.Points.First(),
  1359. CanMove = false,
  1360. IsHitTestVisible = false,
  1361. };
  1362. innerData.mMapStorage.Items.Add(callout);
  1363. }
  1364. /// <summary>
  1365. /// 绘制GDOP多条线 两个点绘制一个线段 1和2一个线段 3和4一个线段
  1366. /// </summary>
  1367. /// <param name="ctrl"></param>
  1368. /// <param name="wcKm"></param>
  1369. /// <param name="dots"></param>
  1370. /// <param name="patterncount"></param>
  1371. public static void DrawGdopLineTwo(this MapControl ctrl, string wcKm, IEnumerable<(double lon, double lat)> dots, int patterncount)
  1372. {
  1373. if (dots == null || !dots.Any()) return;
  1374. string identify = "DrawGdopLine_";
  1375. var innerData = ctrl.Tag as InnerData;
  1376. //多条线 两个点绘制一个线段 1和2一个线段 3和4一个线段
  1377. List<MapPolyline> polylines = new List<MapPolyline>();
  1378. int index = 0;
  1379. int count = dots.Count();
  1380. MapPolyline polyLine = null;
  1381. foreach (var item in dots)
  1382. {
  1383. if (index % 2 == 0)
  1384. {
  1385. if (polyLine != null)//添加线段
  1386. {
  1387. polylines.Add(polyLine);
  1388. }
  1389. polyLine = new MapPolyline()
  1390. {
  1391. Stroke = ColorHelper.GetColor(wcKm),
  1392. StrokeWidth = 2,
  1393. IsGeodesic = true,
  1394. CanResize = false,
  1395. CanEdit = false,
  1396. CanRotate = false,
  1397. IsHitTestVisible = true,
  1398. CanMove = false,
  1399. Tag = $"{identify}{wcKm}",
  1400. };
  1401. }
  1402. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1403. if (patterncount == index)//提示公里信息
  1404. {
  1405. polyLine.TitleOptions.Pattern = wcKm;
  1406. }
  1407. index++;
  1408. if (index == count)//添加最后一个线段
  1409. {
  1410. polylines.Add(polyLine);
  1411. }
  1412. }
  1413. if (!polyLine.Points.Any()) return;
  1414. innerData.mMapStorage.Items.AddRange(polylines);
  1415. }
  1416. /// <summary>
  1417. /// 绘制半径圆
  1418. /// </summary>
  1419. /// <param name="ctrl"></param>
  1420. /// <param name="lat"></param>
  1421. /// <param name="lon"></param>
  1422. /// <param name="radius"></param>
  1423. public static void DrawRadiusRound(this MapControl ctrl, double lat, double lon, int radius)
  1424. {
  1425. var innerData = ctrl.Tag as InnerData;
  1426. try
  1427. {
  1428. if (radius <= 0)
  1429. return;
  1430. CoordPointCollection latLngs = new CoordPointCollection();
  1431. MyLatLng centerLatLng = new MyLatLng(lon, lat);
  1432. // 0 - 360度 寻找半径为radius,圆心为centerP的圆上点的经纬度
  1433. for (int i = 0; i < 360; i++)
  1434. {
  1435. //获取目标经纬度
  1436. MyLatLng tempLatLng = getMyLatLng(centerLatLng, radius, i);
  1437. //将自定义的经纬度类 转换成 标准经纬度类
  1438. CoordPoint p = new GeoPoint(tempLatLng.m_Latitude, tempLatLng.m_Longitude);
  1439. latLngs.Add(p);
  1440. }
  1441. //安全性检查
  1442. if (latLngs.Count < 20)
  1443. {
  1444. return;
  1445. }
  1446. //通过绘制多边形的方式绘制圆
  1447. MapPolygon gpol = new MapPolygon();
  1448. gpol.Points = latLngs;
  1449. gpol.Stroke = Color.Red;
  1450. gpol.Fill = Color.FromArgb(50, Color.Red);
  1451. gpol.IsHitTestVisible = true;
  1452. innerData.mMapStorageFixed.Items.Add(gpol);
  1453. }
  1454. catch (Exception ex)
  1455. {
  1456. //Dialog.Error(ex);
  1457. }
  1458. }
  1459. /// <summary>
  1460. /// 度 转换成 弧度
  1461. /// </summary>
  1462. /// <param name="degrees"></param>
  1463. /// <returns></returns>
  1464. public static double DegreesToRadians(double degrees)
  1465. {
  1466. const double degToRadFactor = Math.PI / 180;
  1467. return degrees * degToRadFactor;
  1468. }
  1469. /// <summary>
  1470. /// 计算两个点之间的距离
  1471. /// </summary>
  1472. /// <param name="startlon">开始经度</param>
  1473. /// <param name="startlat">开始纬度</param>
  1474. /// <param name="endlon">结束经度</param>
  1475. /// <param name="endlat">结束纬度</param>
  1476. /// <returns></returns>
  1477. public static double CalcLineKm(double startlon, double startlat, double endlon, double endlat)
  1478. {
  1479. GeoPoint startPoint = new GeoPoint() { Longitude = startlon, Latitude = startlat };
  1480. GeoPoint endPoint = new GeoPoint() { Longitude = endlon, Latitude = endlat };
  1481. double result = 0;
  1482. MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
  1483. result = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
  1484. return result;
  1485. }
  1486. /// <summary>
  1487. /// 计算方向线坐标
  1488. /// </summary>
  1489. /// <param name="lon">经度</param>
  1490. /// <param name="lat">纬度</param>
  1491. /// <param name="deg"> 艏向角 角度制</param>
  1492. /// <param name="dis">长度 m</param>
  1493. /// <returns></returns>
  1494. public static (double, double) CalcSituation(double lon, double lat, double deg, double dis)
  1495. {
  1496. double arc = 6371.393 * 1000; //地球平均半径
  1497. double rad = deg * (Math.PI / 180); //角度转弧度
  1498. double c_lng = lon + dis * Math.Sin(rad) / (arc * Math.Cos(lat) * 2 * Math.PI / 360);
  1499. double c_lat = lat + dis * Math.Cos(rad) / (arc * 2 * Math.PI / 360);
  1500. return (c_lng, c_lat); //方向上的另一点坐标
  1501. }
  1502. /**
  1503. * 求B点经纬度
  1504. * @param A 已知点的经纬度,
  1505. * @param distance AB两地的距离 单位km
  1506. * @param angle AB连线与正北方向的夹角(0~360)
  1507. * @return B点的经纬度
  1508. */
  1509. private static MyLatLng getMyLatLng(MyLatLng A, double distance, double angle)
  1510. {
  1511. double dx = distance * 1000 * Math.Sin(DegreesToRadians(angle));
  1512. double dy = distance * 1000 * Math.Cos(DegreesToRadians(angle));
  1513. double bjd = (dx / A.Ed + A.m_RadLo) * 180 / Math.PI;
  1514. double bwd = (dy / A.Ec + A.m_RadLa) * 180 / Math.PI;
  1515. return new MyLatLng(bjd, bwd);
  1516. }
  1517. public static void ClearRect(this MapControl ctrl)
  1518. {
  1519. var innerDate = ctrl.Tag as InnerData;
  1520. if (innerDate.rangeItem != null)
  1521. innerDate.mMapStorage.Items.Remove(innerDate.rangeItem);
  1522. if (innerDate.dotItem != null)
  1523. innerDate.mMapStorage.Items.Remove(innerDate.dotItem);
  1524. }
  1525. /// <summary>
  1526. /// 获取地图框选的范围信息(可能为null)
  1527. /// </summary>
  1528. /// <param name="ctrl"></param>
  1529. /// <returns></returns>
  1530. public static (double starLon, double startLat, double centerLon, double centerLat,
  1531. double endLon, double endLat, double lonRange, double latRange) GetCurrentRect(this MapControl ctrl)
  1532. {
  1533. var innerData = ctrl.Tag as InnerData;
  1534. return innerData.CurrentRect;
  1535. }
  1536. /// <summary>
  1537. /// 获取地图瓦片图层
  1538. /// </summary>
  1539. /// <param name="ctrl"></param>
  1540. /// <returns></returns>
  1541. public static ImageLayer GetImageLayer(this MapControl ctrl)
  1542. {
  1543. if (ctrl.Layers == null) return null;
  1544. return (ImageLayer)ctrl.Layers["ImageTileLayer"];
  1545. }
  1546. /// <summary>
  1547. /// 获取地图绘制图层
  1548. /// </summary>
  1549. /// <param name="ctrl"></param>
  1550. /// <returns></returns>
  1551. public static VectorItemsLayer GetDrawLayer(this MapControl ctrl)
  1552. {
  1553. return (VectorItemsLayer)ctrl.Layers["DrawLayer"];
  1554. }
  1555. /// <summary>
  1556. /// 获取地图绘制图层
  1557. /// </summary>
  1558. /// <param name="ctrl"></param>
  1559. /// <returns></returns>
  1560. public static VectorItemsLayer GetPosLayer(this MapControl ctrl)
  1561. {
  1562. return (VectorItemsLayer)ctrl.Layers["PosLayer"];
  1563. }
  1564. /// <summary>
  1565. /// 获取地图绘制图层的数据仓库
  1566. /// </summary>
  1567. /// <param name="ctrl"></param>
  1568. /// <returns></returns>
  1569. public static MapItemStorage GetDrawStorage(this MapControl ctrl)
  1570. {
  1571. var innerData = ctrl.Tag as InnerData;
  1572. return innerData.mMapStorage;
  1573. }
  1574. /// <summary>
  1575. /// 设置地图类型.默认为Normal
  1576. /// 该方法为所有MapControl实例设置地图类型
  1577. /// </summary>
  1578. /// <param name="ctrl"></param>
  1579. /// <param name="mapType"></param>
  1580. public static void SetMapType(GoogleMapType mapType)
  1581. {
  1582. mMapType = mapType;
  1583. listMapCtrl.ForEach(t =>
  1584. {
  1585. if (t.GetImageLayer() == null) return;
  1586. var provider = t.GetImageLayer().DataProvider as MapTileDataProviderBase;
  1587. provider?.ClearCache();
  1588. t.Refresh();
  1589. });
  1590. }
  1591. #region private
  1592. private static void DrawRect_MouseMove(object sender, MouseEventArgs e)
  1593. {
  1594. var innerData = (sender as MapControl).Tag as InnerData;
  1595. if (!innerData.drawingRect) return;
  1596. innerData.dotItem.Location = innerData.rangeItem.GetCenter();
  1597. var startLon = Math.Round(innerData.rangeItem.Location.GetX(), 3);
  1598. var startLat = Math.Round(innerData.rangeItem.Location.GetY(), 3);
  1599. if (startLon >= 180)
  1600. {
  1601. startLon -= 360;
  1602. }
  1603. if (startLon <= -180)
  1604. {
  1605. startLon += 360;
  1606. }
  1607. var center = innerData.rangeItem.GetCenter();
  1608. var centerLon = Math.Round(center.GetX(), 3);
  1609. if (centerLon >= 180)
  1610. {
  1611. centerLon -= 360;
  1612. }
  1613. if (centerLon <= -180)
  1614. {
  1615. centerLon += 360;
  1616. }
  1617. var centerLat = Math.Round(center.GetY(), 3);
  1618. double endLon;
  1619. if (centerLon < 0 && startLon > 0)
  1620. endLon = startLon + 2 * (centerLon + 360 - startLon);
  1621. else
  1622. endLon = startLon + 2 * (centerLon - startLon);
  1623. var endLat = startLat + 2 * (centerLat - startLat);
  1624. var StartLon = Math.Min(startLon, endLon);
  1625. var StartLat = Math.Min(startLat, endLat);
  1626. var CenterLon = centerLon;
  1627. var CenterLat = centerLat;
  1628. var EndLon = Math.Max(startLon, endLon);
  1629. var EndLat = Math.Max(startLat, endLat);
  1630. double centerLonNew = CenterLon % 360;
  1631. CenterLon = centerLonNew;
  1632. //double LonRange = Math.Round((EndLon - StartLon) / 2, 3);
  1633. //double LatRange = Math.Round((EndLat - StartLat) / 2, 3);
  1634. double LonRange = Math.Round((EndLon - StartLon), 3);
  1635. double LatRange = Math.Round((EndLat - StartLat), 3);
  1636. if (LonRange >= 360)
  1637. {
  1638. }
  1639. innerData.CurrentRect = (StartLon, StartLat, CenterLon, CenterLat, EndLon, EndLat, LonRange, LatRange);
  1640. innerData.mOnRectChanged?.Invoke(innerData.CurrentRect);
  1641. }
  1642. private static void ExportImg_ItemClick(object sender, ItemClickEventArgs e)
  1643. {
  1644. var ctrl = e.Item.Tag as MapControl;
  1645. using (var dialog = new SaveFileDialog())
  1646. {
  1647. dialog.Filter = "PNG图片|*.png";
  1648. dialog.AddExtension = true;
  1649. dialog.FileName = $"Map{DateTime.Now:yyyyMMddHHmmss}.png";
  1650. if (dialog.ShowDialog() == DialogResult.OK)
  1651. {
  1652. ctrl.ExportToImage(dialog.FileName, ImageFormat.Png);
  1653. }
  1654. }
  1655. }
  1656. private static void ExportCsv_ItemClick(object sender, ItemClickEventArgs e)
  1657. {
  1658. var ctrl = e.Item.Tag as MapControl;
  1659. using (var dialog = new SaveFileDialog())
  1660. {
  1661. dialog.Filter = "CSV文件|*.csv";
  1662. dialog.AddExtension = true;
  1663. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
  1664. if (dialog.ShowDialog() == DialogResult.OK)
  1665. {
  1666. ctrl.ExportToXlsx(dialog.FileName);
  1667. }
  1668. }
  1669. }
  1670. private static void ClearDrawObj(this MapControl ctrl)
  1671. {
  1672. ctrl.Invoke(new Action(() =>
  1673. {
  1674. try
  1675. {
  1676. var innerData = ctrl.Tag as InnerData;
  1677. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1678. innerData.drawingRect = false;
  1679. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1680. innerData.rangeItem = null;
  1681. if (innerData.mMapStorage != null && innerData.mMapStorage.Items.Any())
  1682. {
  1683. innerData.mMapStorage.Items.Clear();
  1684. }
  1685. }
  1686. catch (Exception ex)
  1687. {
  1688. }
  1689. }));
  1690. }
  1691. private static void DistanceLine_ItemClick(object sender, ItemClickEventArgs e)
  1692. {
  1693. var ctrl = e.Item.Tag as MapControl;
  1694. var innerData = ctrl.Tag as InnerData;
  1695. ctrl.MapEditor.SetEditMode();
  1696. var items = innerData.mMapStorage.Items.ToArray();
  1697. foreach (var item in items)
  1698. {
  1699. if (item.Tag != null && item.Tag.ToString() == "DrawDistanceLine")
  1700. innerData.mMapStorage.Items.Remove(item);
  1701. }
  1702. if (innerData.distinctPath != null)
  1703. {
  1704. innerData.distinctPath.Points.Clear();
  1705. }
  1706. innerData.distinctPath = new MapPolyline()
  1707. {
  1708. Stroke = Color.FromArgb(127, 255, 0, 199),
  1709. StrokeWidth = 2,
  1710. IsGeodesic = true,
  1711. CanResize = false,
  1712. CanEdit = false,
  1713. CanRotate = false,
  1714. IsHitTestVisible = false,
  1715. CanMove = true,
  1716. Tag = "DrawDistanceLine"
  1717. };
  1718. innerData.mMapStorage.Items.Add(innerData.distinctPath);
  1719. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1720. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1721. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1722. innerData.hoverTip = CreateHoverTip();
  1723. ctrl.MouseClick += AddDistinctPoint;
  1724. ctrl.MouseMove += MovingDistinct;
  1725. ctrl.MouseLeave += MapControl_MouseLeave;
  1726. ctrl.MouseEnter += MapControl_MouseEnter;
  1727. ctrl.DoubleClick += EndDistinct;
  1728. }
  1729. private static void MarkDot_ItemClick(object sender, ItemClickEventArgs e)
  1730. {
  1731. var ctrl = e.Item.Tag as MapControl;
  1732. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1733. var innerData = ctrl.Tag as InnerData;
  1734. innerData.drawingRect = false;
  1735. using (var frm = new MapEditPointView())
  1736. {
  1737. if (frm.ShowDialog() != DialogResult.OK) return;
  1738. var locPoint = new GeoPoint(frm.Lat, frm.Lon);
  1739. MapCustomElement cusItem = new MapCustomElement()
  1740. {
  1741. Location = locPoint,
  1742. UseAnimation = true,
  1743. CanMove = false,
  1744. EnableHighlighting = DefaultBoolean.True,
  1745. EnableSelection = DefaultBoolean.False,
  1746. Text = "",
  1747. ToolTipPattern = $"{frm.Caption}",
  1748. SvgImage = SvgHelper.CreatePentagram(),
  1749. SvgImageSize = new Size(32, 32),
  1750. TextAlignment = DevExpress.XtraMap.TextAlignment.BottomCenter,
  1751. Tag = "DrawMarkDot"
  1752. };
  1753. innerData.mMapStorage.Items.Add(cusItem);
  1754. }
  1755. }
  1756. private static ToolTipControllerShowEventArgs CreateHoverTip()
  1757. {
  1758. ToolTipTitleItem titleItem1 = new ToolTipTitleItem() { Text = $"0千米" };
  1759. titleItem1.Appearance.ForeColor = SystemColors.GrayText;
  1760. titleItem1.Appearance.Font = new Font(AppearanceObject.DefaultFont.FontFamily, 12, FontStyle.Bold);
  1761. SuperToolTip superToolTip = new SuperToolTip();
  1762. superToolTip.Items.Add(titleItem1);
  1763. ToolTipSeparatorItem sepItem = new ToolTipSeparatorItem();
  1764. superToolTip.Items.Add(sepItem);
  1765. ToolTipItem textItem = new ToolTipItem() { Text = "单击添加测距点,双击结束测距" };
  1766. superToolTip.Items.Add(textItem);
  1767. ToolTipControllerShowEventArgs arg = new ToolTipControllerShowEventArgs();
  1768. arg.ShowBeak = true;
  1769. arg.SuperTip = superToolTip;
  1770. return arg;
  1771. }
  1772. private static void MapControl_MouseEnter(object sender, EventArgs e)
  1773. {
  1774. var innerData = (sender as MapControl).Tag as InnerData;
  1775. innerData.hoverPoint.Visible = true;
  1776. }
  1777. private static void MapControl_MouseLeave(object sender, EventArgs e)
  1778. {
  1779. var innerData = (sender as MapControl).Tag as InnerData;
  1780. innerData.hoverPoint.Visible = false;
  1781. }
  1782. private static void AddDistinctPoint(object sender, MouseEventArgs e)
  1783. {
  1784. var innerData = (sender as MapControl).Tag as InnerData;
  1785. var ctrl = sender as MapControl;
  1786. MapCallout disItem = new MapCallout { IsHitTestVisible = false, CanMove = false };
  1787. disItem.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1788. disItem.Text = $"{CalcLineKm(innerData):F2}千米";
  1789. disItem.Tag = "DrawDistanceLine";
  1790. innerData.mMapStorage.Items.Add(disItem);
  1791. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1792. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1793. innerData.hoverPoint.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1794. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1795. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1796. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1797. }
  1798. private static void MovingDistinct(object sender, MouseEventArgs e)
  1799. {
  1800. var innerData = (sender as MapControl).Tag as InnerData;
  1801. var ctrl = sender as MapControl;
  1802. var itemPoint = ctrl.ScreenPointToCoordPoint(e.Location);
  1803. innerData.hoverPoint.Location = itemPoint;
  1804. if (innerData.distinctPath.Points.Count > 0)
  1805. {
  1806. ctrl.MapEditor.SetEditMode();
  1807. innerData.distinctPath.Points[innerData.distinctPath.Points.Count - 1] = itemPoint;
  1808. (innerData.hoverTip.SuperTip.Items[0] as ToolTipTitleItem).Text = $"{CalcLineKm(innerData):F2}千米";
  1809. innerData.mapToolTip.ShowHint(innerData.hoverTip, ctrl.PointToScreen(e.Location));
  1810. }
  1811. }
  1812. private static double CalcLineKm(InnerData data)
  1813. {
  1814. double result = 0;
  1815. if (data.distinctPath.Points.Count < 2) return result;
  1816. for (int i = 0; i < data.distinctPath.Points.Count - 1; i++)
  1817. {
  1818. var startPoint = data.distinctPath.Points[i] as GeoPoint;
  1819. var endPoint = data.distinctPath.Points[i + 1] as GeoPoint;
  1820. MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
  1821. double partlength = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
  1822. result += partlength;
  1823. }
  1824. return result;
  1825. }
  1826. public static void ClearMap(this MapControl ctrl)
  1827. {
  1828. var innerData = ctrl.Tag as InnerData;
  1829. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1830. innerData.mMapStorage?.Items.Clear();
  1831. }
  1832. private static void EndDistinct(object sender, EventArgs e)
  1833. {
  1834. var ctrl = sender as MapControl;
  1835. var innerData = ctrl.Tag as InnerData;
  1836. innerData.mapToolTip.HideHint();
  1837. ctrl.MouseClick -= AddDistinctPoint;
  1838. ctrl.MouseMove -= MovingDistinct;
  1839. ctrl.DoubleClick -= EndDistinct;
  1840. ctrl.MouseLeave -= MapControl_MouseLeave;
  1841. ctrl.MouseEnter -= MapControl_MouseEnter;
  1842. }
  1843. class MapEditPointView : DevExpress.XtraEditors.XtraForm
  1844. {
  1845. private System.ComponentModel.IContainer components = null;
  1846. private DevExpress.XtraLayout.LayoutControl layoutControl1;
  1847. private DevExpress.XtraLayout.LayoutControlGroup Root;
  1848. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
  1849. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
  1850. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
  1851. private DevExpress.XtraEditors.ButtonEdit txtLon;
  1852. private DevExpress.XtraEditors.ButtonEdit txtLat;
  1853. private DevExpress.XtraEditors.TextEdit txtCaption;
  1854. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
  1855. private DevExpress.XtraEditors.SimpleButton btnCancel;
  1856. private DevExpress.XtraEditors.SimpleButton btnOk;
  1857. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
  1858. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
  1859. private DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider dxErrorProvider1;
  1860. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
  1861. private void InitializeComponent()
  1862. {
  1863. this.components = new System.ComponentModel.Container();
  1864. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions1 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1865. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject1 = new DevExpress.Utils.SerializableAppearanceObject();
  1866. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject2 = new DevExpress.Utils.SerializableAppearanceObject();
  1867. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject3 = new DevExpress.Utils.SerializableAppearanceObject();
  1868. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject4 = new DevExpress.Utils.SerializableAppearanceObject();
  1869. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions2 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1870. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject5 = new DevExpress.Utils.SerializableAppearanceObject();
  1871. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject6 = new DevExpress.Utils.SerializableAppearanceObject();
  1872. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject7 = new DevExpress.Utils.SerializableAppearanceObject();
  1873. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject8 = new DevExpress.Utils.SerializableAppearanceObject();
  1874. this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
  1875. this.txtCaption = new DevExpress.XtraEditors.TextEdit();
  1876. this.txtLon = new DevExpress.XtraEditors.ButtonEdit();
  1877. this.txtLat = new DevExpress.XtraEditors.ButtonEdit();
  1878. this.Root = new DevExpress.XtraLayout.LayoutControlGroup();
  1879. this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
  1880. this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
  1881. this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
  1882. this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
  1883. this.btnOk = new DevExpress.XtraEditors.SimpleButton();
  1884. this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
  1885. this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
  1886. this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
  1887. this.dxErrorProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(this.components);
  1888. this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem();
  1889. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
  1890. this.layoutControl1.SuspendLayout();
  1891. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).BeginInit();
  1892. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).BeginInit();
  1893. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).BeginInit();
  1894. ((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit();
  1895. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
  1896. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
  1897. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
  1898. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
  1899. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
  1900. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
  1901. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).BeginInit();
  1902. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit();
  1903. this.SuspendLayout();
  1904. //
  1905. // layoutControl1
  1906. //
  1907. this.layoutControl1.Controls.Add(this.btnCancel);
  1908. this.layoutControl1.Controls.Add(this.btnOk);
  1909. this.layoutControl1.Controls.Add(this.txtCaption);
  1910. this.layoutControl1.Controls.Add(this.txtLon);
  1911. this.layoutControl1.Controls.Add(this.txtLat);
  1912. this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
  1913. this.layoutControl1.Location = new System.Drawing.Point(0, 0);
  1914. this.layoutControl1.Name = "layoutControl1";
  1915. this.layoutControl1.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(689, 0, 650, 400);
  1916. this.layoutControl1.Root = this.Root;
  1917. this.layoutControl1.Size = new System.Drawing.Size(272, 208);
  1918. this.layoutControl1.TabIndex = 0;
  1919. this.layoutControl1.Text = "layoutControl1";
  1920. //
  1921. // txtCaption
  1922. //
  1923. this.txtCaption.Location = new System.Drawing.Point(12, 29);
  1924. this.txtCaption.Name = "txtCaption";
  1925. this.txtCaption.Properties.Appearance.Options.UseTextOptions = true;
  1926. this.txtCaption.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1927. this.txtCaption.Properties.AutoHeight = false;
  1928. this.txtCaption.Properties.MaxLength = 30;
  1929. this.txtCaption.Size = new System.Drawing.Size(248, 22);
  1930. this.txtCaption.StyleController = this.layoutControl1;
  1931. this.txtCaption.TabIndex = 9;
  1932. //
  1933. // txtLon
  1934. //
  1935. this.txtLon.Location = new System.Drawing.Point(12, 80);
  1936. this.txtLon.Name = "txtLon";
  1937. this.txtLon.Properties.Appearance.Options.UseTextOptions = true;
  1938. this.txtLon.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1939. this.txtLon.Properties.AutoHeight = false;
  1940. this.txtLon.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1941. new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, "°", -1, false, true, false, editorButtonImageOptions1, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppearanceObject1, serializableAppearanceObject2, serializableAppearanceObject3, serializableAppearanceObject4, "", null, null, DevExpress.Utils.ToolTipAnchor.Default)});
  1942. this.txtLon.Size = new System.Drawing.Size(248, 22);
  1943. this.txtLon.StyleController = this.layoutControl1;
  1944. this.txtLon.TabIndex = 4;
  1945. //
  1946. // txtLat
  1947. //
  1948. this.txtLat.Location = new System.Drawing.Point(12, 131);
  1949. this.txtLat.Name = "txtLat";
  1950. this.txtLat.Properties.Appearance.Options.UseTextOptions = true;
  1951. this.txtLat.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1952. this.txtLat.Properties.AutoHeight = false;
  1953. this.txtLat.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1954. new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, "°", -1, false, true, false, editorButtonImageOptions2, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppearanceObject5, serializableAppearanceObject6, serializableAppearanceObject7, serializableAppearanceObject8, "", null, null, DevExpress.Utils.ToolTipAnchor.Default)});
  1955. this.txtLat.Size = new System.Drawing.Size(248, 22);
  1956. this.txtLat.StyleController = this.layoutControl1;
  1957. this.txtLat.TabIndex = 5;
  1958. //
  1959. // Root
  1960. //
  1961. this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
  1962. this.Root.GroupBordersVisible = false;
  1963. this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
  1964. this.layoutControlItem1,
  1965. this.emptySpaceItem1,
  1966. this.layoutControlItem5,
  1967. this.layoutControlItem2,
  1968. this.layoutControlItem3,
  1969. this.layoutControlItem6,
  1970. this.emptySpaceItem2});
  1971. this.Root.Name = "Root";
  1972. this.Root.Size = new System.Drawing.Size(272, 208);
  1973. this.Root.TextVisible = false;
  1974. //
  1975. // layoutControlItem1
  1976. //
  1977. this.layoutControlItem1.Control = this.txtLon;
  1978. this.layoutControlItem1.Location = new System.Drawing.Point(0, 43);
  1979. this.layoutControlItem1.MaxSize = new System.Drawing.Size(0, 51);
  1980. this.layoutControlItem1.MinSize = new System.Drawing.Size(54, 51);
  1981. this.layoutControlItem1.Name = "layoutControlItem1";
  1982. this.layoutControlItem1.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  1983. this.layoutControlItem1.Size = new System.Drawing.Size(252, 51);
  1984. this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1985. this.layoutControlItem1.Text = "经度";
  1986. this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Top;
  1987. this.layoutControlItem1.TextSize = new System.Drawing.Size(24, 14);
  1988. //
  1989. // emptySpaceItem1
  1990. //
  1991. this.emptySpaceItem1.AllowHotTrack = false;
  1992. this.emptySpaceItem1.Location = new System.Drawing.Point(0, 162);
  1993. this.emptySpaceItem1.MaxSize = new System.Drawing.Size(0, 26);
  1994. this.emptySpaceItem1.MinSize = new System.Drawing.Size(104, 26);
  1995. this.emptySpaceItem1.Name = "emptySpaceItem1";
  1996. this.emptySpaceItem1.Size = new System.Drawing.Size(113, 26);
  1997. this.emptySpaceItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1998. this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
  1999. //
  2000. // layoutControlItem2
  2001. //
  2002. this.layoutControlItem2.Control = this.txtLat;
  2003. this.layoutControlItem2.Location = new System.Drawing.Point(0, 94);
  2004. this.layoutControlItem2.MaxSize = new System.Drawing.Size(0, 51);
  2005. this.layoutControlItem2.MinSize = new System.Drawing.Size(54, 51);
  2006. this.layoutControlItem2.Name = "layoutControlItem2";
  2007. this.layoutControlItem2.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  2008. this.layoutControlItem2.Size = new System.Drawing.Size(252, 51);
  2009. this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2010. this.layoutControlItem2.Text = "纬度";
  2011. this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Top;
  2012. this.layoutControlItem2.TextSize = new System.Drawing.Size(24, 14);
  2013. //
  2014. // layoutControlItem5
  2015. //
  2016. this.layoutControlItem5.Control = this.txtCaption;
  2017. this.layoutControlItem5.Location = new System.Drawing.Point(0, 0);
  2018. this.layoutControlItem5.MaxSize = new System.Drawing.Size(0, 43);
  2019. this.layoutControlItem5.MinSize = new System.Drawing.Size(54, 43);
  2020. this.layoutControlItem5.Name = "layoutControlItem5";
  2021. this.layoutControlItem5.Size = new System.Drawing.Size(252, 43);
  2022. this.layoutControlItem5.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2023. this.layoutControlItem5.Text = "标题";
  2024. this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Top;
  2025. this.layoutControlItem5.TextSize = new System.Drawing.Size(24, 14);
  2026. //
  2027. // btnOk
  2028. //
  2029. this.btnOk.Location = new System.Drawing.Point(125, 174);
  2030. this.btnOk.Name = "btnOk";
  2031. this.btnOk.Size = new System.Drawing.Size(65, 22);
  2032. this.btnOk.StyleController = this.layoutControl1;
  2033. this.btnOk.TabIndex = 10;
  2034. this.btnOk.Text = "确定";
  2035. this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
  2036. //
  2037. // layoutControlItem3
  2038. //
  2039. this.layoutControlItem3.Control = this.btnOk;
  2040. this.layoutControlItem3.Location = new System.Drawing.Point(113, 162);
  2041. this.layoutControlItem3.MaxSize = new System.Drawing.Size(69, 26);
  2042. this.layoutControlItem3.MinSize = new System.Drawing.Size(69, 26);
  2043. this.layoutControlItem3.Name = "layoutControlItem3";
  2044. this.layoutControlItem3.Size = new System.Drawing.Size(69, 26);
  2045. this.layoutControlItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2046. this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
  2047. this.layoutControlItem3.TextVisible = false;
  2048. //
  2049. // btnCancel
  2050. //
  2051. this.btnCancel.Location = new System.Drawing.Point(194, 174);
  2052. this.btnCancel.Name = "btnCancel";
  2053. this.btnCancel.Size = new System.Drawing.Size(66, 22);
  2054. this.btnCancel.StyleController = this.layoutControl1;
  2055. this.btnCancel.TabIndex = 11;
  2056. this.btnCancel.Text = "取消";
  2057. this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
  2058. //
  2059. // layoutControlItem6
  2060. //
  2061. this.layoutControlItem6.Control = this.btnCancel;
  2062. this.layoutControlItem6.Location = new System.Drawing.Point(182, 162);
  2063. this.layoutControlItem6.MaxSize = new System.Drawing.Size(70, 26);
  2064. this.layoutControlItem6.MinSize = new System.Drawing.Size(70, 26);
  2065. this.layoutControlItem6.Name = "layoutControlItem6";
  2066. this.layoutControlItem6.Size = new System.Drawing.Size(70, 26);
  2067. this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2068. this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
  2069. this.layoutControlItem6.TextVisible = false;
  2070. //
  2071. // dxErrorProvider1
  2072. //
  2073. this.dxErrorProvider1.ContainerControl = this;
  2074. //
  2075. // emptySpaceItem2
  2076. //
  2077. this.emptySpaceItem2.AllowHotTrack = false;
  2078. this.emptySpaceItem2.Location = new System.Drawing.Point(0, 145);
  2079. this.emptySpaceItem2.MinSize = new System.Drawing.Size(104, 1);
  2080. this.emptySpaceItem2.Name = "emptySpaceItem2";
  2081. this.emptySpaceItem2.Size = new System.Drawing.Size(252, 17);
  2082. this.emptySpaceItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2083. this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
  2084. //
  2085. // MapEditPointView
  2086. //
  2087. this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
  2088. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  2089. this.ClientSize = new System.Drawing.Size(272, 208);
  2090. this.Controls.Add(this.layoutControl1);
  2091. this.IconOptions.ShowIcon = false;
  2092. this.MaximizeBox = false;
  2093. this.MinimizeBox = false;
  2094. this.Name = "MapEditPointView";
  2095. this.ShowInTaskbar = false;
  2096. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
  2097. this.Text = "标点";
  2098. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
  2099. this.layoutControl1.ResumeLayout(false);
  2100. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).EndInit();
  2101. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).EndInit();
  2102. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).EndInit();
  2103. ((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit();
  2104. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
  2105. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
  2106. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
  2107. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
  2108. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
  2109. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
  2110. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).EndInit();
  2111. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit();
  2112. this.ResumeLayout(false);
  2113. }
  2114. protected override void Dispose(bool disposing)
  2115. {
  2116. if (disposing && (components != null))
  2117. {
  2118. components.Dispose();
  2119. }
  2120. base.Dispose(disposing);
  2121. }
  2122. public MapEditPointView()
  2123. {
  2124. InitializeComponent();
  2125. }
  2126. public string Caption
  2127. {
  2128. get
  2129. {
  2130. return txtCaption.Text.Trim();
  2131. }
  2132. set
  2133. {
  2134. txtCaption.Text = value;
  2135. }
  2136. }
  2137. public double Lon
  2138. {
  2139. get
  2140. {
  2141. return double.Parse(txtLon.Text.Trim());
  2142. }
  2143. set
  2144. {
  2145. txtLon.Text = value.ToString();
  2146. }
  2147. }
  2148. public double Lat
  2149. {
  2150. get
  2151. {
  2152. return double.Parse(txtLat.Text.Trim());
  2153. }
  2154. set
  2155. {
  2156. txtLat.Text = value.ToString();
  2157. }
  2158. }
  2159. private void btnOk_Click(object sender, EventArgs e)
  2160. {
  2161. dxErrorProvider1.ClearErrors();
  2162. double lon, lat;
  2163. if (!double.TryParse(txtLon.Text, out lon))
  2164. {
  2165. dxErrorProvider1.SetError(txtLon, "请设置正确的经度");
  2166. return;
  2167. }
  2168. if (!double.TryParse(txtLat.Text, out lat))
  2169. {
  2170. dxErrorProvider1.SetError(txtLat, "请设置正确的纬度");
  2171. return;
  2172. }
  2173. if (lon < -180 || lon > 180)
  2174. {
  2175. dxErrorProvider1.SetError(txtLon, "经度范围[-180,180]");
  2176. return;
  2177. }
  2178. if (lat < -90 || lat > 90)
  2179. {
  2180. dxErrorProvider1.SetError(txtLat, "纬度范围[-90,90]");
  2181. return;
  2182. }
  2183. this.DialogResult = DialogResult.OK;
  2184. }
  2185. private void btnCancel_Click(object sender, EventArgs e)
  2186. {
  2187. this.DialogResult = DialogResult.Cancel;
  2188. }
  2189. }
  2190. #endregion
  2191. #region 半径圆
  2192. public class MyLatLng
  2193. {
  2194. public double Rc = 6378137; //赤道半径
  2195. public double Rj = 6356725; //极半径
  2196. public double m_LoDeg, m_LoMin, m_LoSec;
  2197. public double m_LaDeg, m_LaMin, m_LaSec;
  2198. public double m_Longitude, m_Latitude;
  2199. public double m_RadLo, m_RadLa;
  2200. public double Ec;
  2201. public double Ed;
  2202. public MyLatLng(double longitude, double latitude)
  2203. {
  2204. m_LoDeg = (int)longitude;
  2205. m_LoMin = (int)((longitude - m_LoDeg) * 60);
  2206. m_LoSec = (longitude - m_LoDeg - m_LoMin / 60) * 3600;
  2207. m_LaDeg = (int)latitude;
  2208. m_LaMin = (int)((latitude - m_LaDeg) * 60);
  2209. m_LaSec = (latitude - m_LaDeg - m_LaMin / 60) * 3600;
  2210. m_Longitude = longitude;
  2211. m_Latitude = latitude;
  2212. m_RadLo = longitude * Math.PI / 180;
  2213. m_RadLa = latitude * Math.PI / 180;
  2214. Ec = Rj + (Rc - Rj) * (90 - m_Latitude) / 90;
  2215. Ed = Ec * Math.Cos(m_RadLa);
  2216. }
  2217. }
  2218. #endregion
  2219. #region ImageLayer数据源接口实现(本地和Http接口)
  2220. class ImageTileSource : IImageTileSource
  2221. {
  2222. SQLiteConnection con;
  2223. public ImageTileSource()
  2224. {
  2225. var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
  2226. if (files.Length > 0)
  2227. {
  2228. try
  2229. {
  2230. conStr = string.Format(conStr, files[0]);
  2231. con = new SQLiteConnection(conStr);
  2232. con.Open();
  2233. }
  2234. catch
  2235. {
  2236. conStr = null;
  2237. Console.WriteLine("Data.gmdb文件读取出错!");
  2238. }
  2239. }
  2240. else
  2241. {
  2242. conStr = null;
  2243. }
  2244. }
  2245. public string Name => "GMap地图瓦片";
  2246. public bool CanDisposeSourceImage => true;
  2247. public Image GetImage(int x, int y, int level, Size size)
  2248. {
  2249. var data = QueryTile(x, y, level, 0);
  2250. if (data == null) return null;
  2251. return Image.FromStream(new MemoryStream(data));
  2252. }
  2253. string QuerySql = "SELECT Tile FROM main.TilesData WHERE id = (SELECT id FROM main.Tiles WHERE X={0} AND Y={1} AND Zoom={2} AND Type={3})";
  2254. string conStr = "Data Source=\"{0}\";Page Size=32768";
  2255. byte[] QueryTile(int x, int y, int zoom, int type)
  2256. {
  2257. if (conStr == null) return null;
  2258. type = (int)mMapType;
  2259. if (type == 0) type = 1818940751;
  2260. using (DbCommand com = con.CreateCommand())
  2261. {
  2262. com.CommandText = string.Format(QuerySql, x, y, zoom, type);
  2263. using (DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
  2264. {
  2265. if (rd.Read())
  2266. {
  2267. long length = rd.GetBytes(0, 0, null, 0, 0);
  2268. byte[] tile = new byte[length];
  2269. rd.GetBytes(0, 0, tile, 0, tile.Length);
  2270. return tile;
  2271. }
  2272. }
  2273. }
  2274. return null;
  2275. }
  2276. }
  2277. class HttpMapDataProvider : MapDataProviderBase
  2278. {
  2279. public HttpMapDataProvider()
  2280. {
  2281. TileSource = new HttpTileSource(this);
  2282. }
  2283. public override MapSize GetMapSizeInPixels(double zoomLevel)
  2284. {
  2285. double imageSize;
  2286. imageSize = HttpTileSource.CalculateTotalImageSize(zoomLevel);
  2287. return new MapSize(imageSize, imageSize);
  2288. }
  2289. protected override Size BaseSizeInPixels
  2290. {
  2291. get { return new Size(Convert.ToInt32(HttpTileSource.tileSize * 2), Convert.ToInt32(HttpTileSource.tileSize * 2)); }
  2292. }
  2293. }
  2294. class HttpTileSource : MapTileSourceBase
  2295. {
  2296. public const int tileSize = 256;
  2297. public const int maxZoomLevel = 14;
  2298. public string HttpServerAddr { get; set; }
  2299. public GoogleMapType MapType { get; set; } = GoogleMapType.Normal;
  2300. internal static double CalculateTotalImageSize(double zoomLevel)
  2301. {
  2302. if (zoomLevel < 1.0)
  2303. return zoomLevel * tileSize * 2;
  2304. return Math.Pow(2.0, zoomLevel) * tileSize;
  2305. }
  2306. public HttpTileSource(ICacheOptionsProvider cacheOptionsProvider) :
  2307. base((int)CalculateTotalImageSize(maxZoomLevel), (int)CalculateTotalImageSize(maxZoomLevel), tileSize, tileSize, cacheOptionsProvider)
  2308. {
  2309. }
  2310. public override Uri GetTileByZoomLevel(int zoomLevel, int tilePositionX, int tilePositionY)
  2311. {
  2312. if (string.IsNullOrWhiteSpace(HttpServerAddr)) return null;
  2313. try
  2314. {
  2315. if (zoomLevel <= maxZoomLevel)
  2316. {
  2317. string imgUrl = $"{HttpServerAddr}/{(int)MapType}/{zoomLevel}/{tilePositionX}/{tilePositionY}";
  2318. //string imgUrl = string.Format("http://192.168.0.214:58089/{0}/{1}/{2}/{3}", (int)GoogleMapType.Normal, zoomLevel, tilePositionX, tilePositionY);
  2319. Uri u = new Uri(imgUrl);
  2320. return u;
  2321. }
  2322. return null;
  2323. }
  2324. catch
  2325. {
  2326. Console.WriteLine($"加载地图数据出错,无法连接到{HttpServerAddr}");
  2327. return null;
  2328. }
  2329. }
  2330. }
  2331. #endregion
  2332. //定位点聚合器
  2333. class PosClusterer : IClusterer
  2334. {
  2335. private MapControl ctrl;
  2336. private IMapDataAdapter owner;
  2337. private MapViewport preViewPoint;
  2338. private DebounceDispatcher dispatcher = new DebounceDispatcher();
  2339. public bool IsBusy { get; private set; }
  2340. public MapItemCollection Items { get; private set; }
  2341. public PosClusterer(MapControl ctrl)
  2342. {
  2343. this.ctrl = ctrl;
  2344. }
  2345. public void SetOwner(IMapDataAdapter owner)
  2346. {
  2347. this.owner = owner;
  2348. Items = new MapItemCollection(owner);
  2349. }
  2350. public void Clusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2351. {
  2352. IsBusy = true;
  2353. if (sourceChanged)
  2354. DoClusterize(sourceItems, viewport, sourceChanged);
  2355. else
  2356. dispatcher.Debounce(100, () => DoClusterize(sourceItems, viewport, sourceChanged));
  2357. }
  2358. private void DoClusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2359. {
  2360. if (preViewPoint == null)
  2361. {
  2362. preViewPoint = viewport;
  2363. return;
  2364. }
  2365. if (!sourceChanged && preViewPoint.ZoomLevel == viewport.ZoomLevel)//地图移动或者MapControl大小发生了改变时直接操作Items避免闪烁
  2366. {
  2367. preViewPoint = viewport;
  2368. }
  2369. else//地图进行了缩放
  2370. {
  2371. Items.Clear();
  2372. var cache = new Dictionary<int, List<MapItem>>();
  2373. foreach (MapDot item in sourceItems)
  2374. {
  2375. var point = ctrl.CoordPointToScreenPoint(item.Location);
  2376. int pointX = (int)point.X;
  2377. int pointY = (int)point.Y;
  2378. bool visible = true;
  2379. if (pointX <= _dotSize || pointX > ctrl.Width - _dotSize)
  2380. visible = false;
  2381. else if (pointY <= _dotSize || pointY > ctrl.Height - _dotSize)
  2382. visible = false;
  2383. pointX /= (_dotSize * 2);
  2384. pointY /= (_dotSize * 2);
  2385. var key = pointX << 16 | pointY;
  2386. if (!visible)
  2387. key = -key;
  2388. if (!cache.ContainsKey(key))
  2389. cache.Add(key, new List<MapItem>());
  2390. cache[key].Add(item);
  2391. }
  2392. var innerData = ctrl.Tag as InnerData;
  2393. innerData._clusterCache.Clear();
  2394. LinkedList<MapItem> temp = new LinkedList<MapItem>();
  2395. foreach (var kv in cache)
  2396. {
  2397. var firstDot = kv.Value[0] as MapDot;
  2398. var firstObj = firstDot.Tag as PosData;
  2399. firstDot.Size = kv.Value.Count > 1 ? _dotSize + 2 : _dotSize;
  2400. firstObj.ClusterCount = kv.Value.Count;
  2401. firstObj.ClusterKey = kv.Key;
  2402. innerData._clusterCache.Add(kv.Key, firstDot);
  2403. temp.AddLast(firstDot);
  2404. }
  2405. Items.AddRange(temp);
  2406. cache.Clear();
  2407. preViewPoint = viewport;
  2408. owner.OnClustered();
  2409. }
  2410. this.IsBusy = false;
  2411. }
  2412. //计算多个坐标的中心位置
  2413. public GeoPoint GetCenterPointFromListOfCoordinates(List<MapItem> geoCoordinateList)
  2414. {
  2415. int total = geoCoordinateList.Count;
  2416. double lat = 0, lon = 0;
  2417. foreach (MapDot g in geoCoordinateList)
  2418. {
  2419. lat += (g.Location as GeoPoint).Latitude * Math.PI / 180;
  2420. lon += (g.Location as GeoPoint).Longitude * Math.PI / 180;
  2421. }
  2422. lat /= total;
  2423. lon /= total;
  2424. return new GeoPoint(lat * 180 / Math.PI, lon * 180 / Math.PI);
  2425. }
  2426. }
  2427. }