MapControlEx.cs 115 KB

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