MapControlEx.cs 120 KB

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