MapControlEx.cs 127 KB

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