MapControlEx.cs 113 KB

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