MapControlEx.cs 100 KB

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