MapControlEx.cs 98 KB

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