MapControlEx.cs 120 KB

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