MapControlEx.cs 119 KB

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