MapControlEx.cs 98 KB

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