MapControlEx.cs 99 KB

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