MapControlEx.cs 102 KB

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