MapControlEx.cs 101 KB

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