MapControlEx.cs 129 KB

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