MapControlEx.cs 126 KB

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