MapControlEx.cs 102 KB

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