MapControlEx.cs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  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 AddMapMenu(this MapControl ctrl, string caption, SvgImage img, Action<double, double> action)
  497. {
  498. var btnCustom = new BarButtonItem() { Caption = caption, Name = caption };
  499. btnCustom.ImageOptions.SvgImage = img;
  500. btnCustom.Tag = ctrl;
  501. var innerData = ctrl.Tag as InnerData;
  502. btnCustom.ItemClick += (sender, e) =>
  503. {
  504. action(innerData._mapMenuGeoPoint.Longitude, innerData._mapMenuGeoPoint.Latitude);
  505. };
  506. innerData.barM.BeginInit();
  507. innerData.barM.Items.Add(btnCustom);
  508. innerData.mapMenu.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 AddRectMenu<T>(this MapControl ctrl, string caption, SvgImage img, Action<IEnumerable<T>> action) where T : PosData, new()
  521. {
  522. var btnCustom = new BarButtonItem() { Caption = caption };
  523. btnCustom.ImageOptions.SvgImage = img;
  524. btnCustom.Tag = ctrl;
  525. btnCustom.ItemClick += (sender, e) =>
  526. {
  527. var data = ctrl.GetRectPosItem<T>();
  528. action(data);
  529. };
  530. var innerData = ctrl.Tag as InnerData;
  531. innerData.barM.BeginInit();
  532. innerData.barM.Items.Add(btnCustom);
  533. innerData.rectMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
  534. innerData.barM.EndInit();
  535. return ctrl;
  536. }
  537. /// <summary>
  538. /// 重新设置定位数据
  539. /// </summary>
  540. /// <typeparam name="T"></typeparam>
  541. /// <param name="items">数据源(指定null或空集合可以清空已有数据)</param>
  542. /// <param name="clearDrawLayer">是否清除DrawLayer上临时绘制的内容</param>
  543. public static void SetPosDataSource<T>(this MapControl ctrl, IEnumerable<T> items, bool clearDrawLayer = true) where T : PosData, new()
  544. {
  545. var innerData = ctrl.Tag as InnerData;
  546. innerData._dataCache.Clear();
  547. if (clearDrawLayer)
  548. ctrl.ClearDrawObj();
  549. innerData.posStorge.Items.Clear();
  550. if (items == null || !items.Any()) return;
  551. List<MapDot> list = new List<MapDot>();
  552. for (int i = 0; i < items.Count(); i++)
  553. {
  554. var p = items.ElementAt(i);
  555. var mapItem = new MapDot()
  556. {
  557. EnableHighlighting = DefaultBoolean.True,
  558. EnableSelection = DefaultBoolean.False,
  559. CanMove = false,
  560. Visible = p.Visible,
  561. IsHitTestVisible = true,
  562. Fill = ColorHelper.IsHtmlColor(p.ColorKey) ? ColorTranslator.FromHtml(p.ColorKey) : ColorHelper.GetColor(p.ColorKey),
  563. Size = _dotSize,
  564. Tag = items.ElementAt(i),
  565. Location = new GeoPoint(p.PosLat, p.PosLon)
  566. };
  567. list.Add(mapItem);
  568. innerData._dataCache.Add(p, mapItem);
  569. }
  570. innerData.posStorge.Items.AddRange(list);
  571. }
  572. /// <summary>
  573. /// 定位图层数据源添加一个定位点
  574. /// </summary>
  575. /// <typeparam name="T"></typeparam>
  576. /// <param name="item"></param>
  577. public static void AddPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
  578. {
  579. if (item.PosLon > 180) return;
  580. var innerData = ctrl.Tag as InnerData;
  581. var mapItem = new MapDot()
  582. {
  583. EnableHighlighting = DefaultBoolean.True,
  584. EnableSelection = DefaultBoolean.False,
  585. CanMove = false,
  586. Visible = item.Visible,
  587. IsHitTestVisible = true,
  588. Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey),
  589. Size = _dotSize,
  590. Tag = item,
  591. Location = new GeoPoint(item.PosLat, item.PosLon)
  592. };
  593. innerData._dataCache.Add(item, mapItem);
  594. innerData.posStorge.Items.Add(mapItem);
  595. }
  596. /// <summary>
  597. /// 定位图层数据源删除定位点
  598. /// </summary>
  599. /// <typeparam name="T"></typeparam>
  600. /// <param name="ctrl"></param>
  601. /// <param name="data"></param>
  602. public static void DelPosItem<T>(this MapControl ctrl, IEnumerable<T> data) where T : PosData, new()
  603. {
  604. if (data == null || !data.Any()) return;
  605. foreach (var item in data)
  606. {
  607. ctrl.DelPosItem(item);
  608. }
  609. ctrl.Refresh();
  610. }
  611. /// <summary>
  612. /// 定位图层数据源删除定位点
  613. /// </summary>
  614. /// <typeparam name="T"></typeparam>
  615. /// <param name="ctrl"></param>
  616. /// <param name="data"></param>
  617. public static void DelPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
  618. {
  619. if (item == null) return;
  620. var innerData = ctrl.Tag as InnerData;
  621. if (innerData._dataCache.ContainsKey(item))
  622. {
  623. innerData.posStorge.Items.Remove(innerData._dataCache[item]);
  624. innerData._dataCache.Remove(item);
  625. }
  626. ctrl.Refresh();
  627. }
  628. /// <summary>
  629. /// 定位图层数据源删除定位点
  630. /// </summary>
  631. /// <typeparam name="T"></typeparam>
  632. /// <param name="ctrl"></param>
  633. /// <param name="data"></param>
  634. public static void DelPosItem<T>(this MapControl ctrl, Func<T, bool> predicate) where T : PosData, new()
  635. {
  636. var innerData = ctrl.Tag as InnerData;
  637. List<PosData> keys = new List<PosData>();
  638. foreach (var item in innerData._dataCache.Keys)
  639. {
  640. if (predicate((T)item))
  641. keys.Add(item);
  642. }
  643. foreach (var item in keys)
  644. {
  645. ctrl.DelPosItem(item);
  646. }
  647. ctrl.Refresh();
  648. }
  649. /// <summary>
  650. /// 更新定位数据(可以更新可见性、颜色、经纬度、选中状态)
  651. /// </summary>
  652. /// <typeparam name="T"></typeparam>
  653. /// <param name="ctrl"></param>
  654. /// <param name="item"></param>
  655. /// <param name="setCenter">是否将这个点设置到地图中心显示</param>
  656. public static void UpdatePosItem<T>(this MapControl ctrl, T item, bool setCenter = false) where T : PosData, new()
  657. {
  658. if (item == null) return;
  659. var innerData = ctrl.Tag as InnerData;
  660. if (innerData._dataCache.ContainsKey(item))
  661. {
  662. var mapDot = innerData._dataCache[item] as MapDot;
  663. mapDot.Visible = item.Visible;//外部修改了可见性
  664. mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
  665. mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
  666. if (mapDot.Size != (item.Selected ? _selectedDotSize : _dotSize))//外部修改了选中状态
  667. {
  668. mapDot.Size = item.Selected ? _selectedDotSize : _dotSize;
  669. mapDot.StrokeWidth = item.Selected ? 0 : 1;
  670. if (item.ClusterCount > 1)
  671. {
  672. if (innerData._clusterCache.TryGetValue(item.ClusterKey, out MapItem clusterItem))
  673. {
  674. (clusterItem as MapDot).Size = item.Selected ? _selectedDotSize : _dotSize;
  675. }
  676. }
  677. if (mapDot.ClusteredItems.Any())
  678. (mapDot.ClusteredItems[0] as MapDot).Size = _selectedDotSize;
  679. if (item.Selected)
  680. {
  681. //让选中的Item在上层
  682. var idx = innerData.posStorge.Items.IndexOf(mapDot);
  683. innerData.posStorge.Items.Swap(idx, innerData.posStorge.Items.Count - 1);
  684. //innerData.posStorge.Items.Add(mapDot);
  685. //需要将上次选中的点设置为未选中
  686. if (innerData.preSelectedItem != null)
  687. {
  688. innerData.preSelectedItem.Size = _dotSize;
  689. (innerData.preSelectedItem.Tag as PosData).Selected = false;
  690. if ((innerData.preSelectedItem.Tag as PosData).ClusterCount > 1)
  691. {
  692. if (innerData._clusterCache.TryGetValue((innerData.preSelectedItem.Tag as PosData).ClusterKey, out MapItem clusterItem))
  693. {
  694. (clusterItem as MapDot).Size = _dotSize + 2;
  695. }
  696. }
  697. }
  698. innerData.preSelectedItem = mapDot;
  699. }
  700. }
  701. if (setCenter && item.Visible)
  702. ctrl.SetCenterPoint(item.PosLon, item.PosLat, false);
  703. }
  704. }
  705. /// <summary>
  706. /// 更新定位数据(可以更新可见性、颜色、经纬度)
  707. /// </summary>
  708. /// <typeparam name="T"></typeparam>
  709. /// <param name="ctrl"></param>
  710. /// <param name="item"></param>
  711. public static void UpdatePosItem<T>(this MapControl ctrl, IEnumerable<T> items) where T : PosData, new()
  712. {
  713. if (items == null || !items.Any()) return;
  714. var innerData = ctrl.Tag as InnerData;
  715. foreach (var item in items)
  716. {
  717. if (innerData._dataCache.ContainsKey(item))
  718. {
  719. var mapDot = innerData._dataCache[item] as MapDot;
  720. mapDot.Visible = item.Visible;//外部修改了可见性
  721. mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
  722. mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
  723. }
  724. }
  725. }
  726. /// <summary>
  727. /// 设置地图中心点
  728. /// </summary>
  729. /// <param name="ctrl"></param>
  730. /// <param name="lon"></param>
  731. /// <param name="lat"></param>
  732. /// <param name="animated">是否显示动画</param>
  733. /// <returns></returns>
  734. public static MapControl SetCenterPoint(this MapControl ctrl, double lon, double lat, bool animated = false)
  735. {
  736. ctrl.SetCenterPoint(new GeoPoint(lat, lon), animated);
  737. return ctrl;
  738. }
  739. public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, Image img, string toolTip = "")
  740. {
  741. var innerData = ctrl.Tag as InnerData;
  742. var item = new MapCustomElement() { Tag = tag };
  743. item.UseAnimation = false;
  744. item.BackgroundDrawingMode = ElementState.None;
  745. item.Location = new GeoPoint(imgLat, imgLon);
  746. item.Image = img;
  747. item.ToolTipPattern = toolTip;
  748. innerData.mMapStorageFixed.Items.Add(item);
  749. }
  750. public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, SvgImage img, Size size, string toolTip = "")
  751. {
  752. var innerData = ctrl.Tag as InnerData;
  753. var item = new MapCustomElement() { Tag = tag };
  754. item.UseAnimation = false;
  755. item.BackgroundDrawingMode = ElementState.None;
  756. item.Location = new GeoPoint(imgLat, imgLon);
  757. item.SvgImage = img;
  758. item.SvgImageSize = size;
  759. item.ToolTipPattern = toolTip;
  760. innerData.mMapStorageFixed.Items.Add(item);
  761. }
  762. public static void DelFixedImg(this MapControl ctrl, string tag)
  763. {
  764. var innerData = ctrl.Tag as InnerData;
  765. var delItems = innerData.mMapStorageFixed.Items.ToList().FindAll(p => p.Tag.ToString() == tag);
  766. foreach (var item in delItems)
  767. {
  768. innerData.mMapStorageFixed.Items.Remove(item);
  769. }
  770. }
  771. /// <summary>
  772. /// 获取当前矩形框选的定位点
  773. /// </summary>
  774. /// <param name="ctrl"></param>
  775. /// <returns></returns>
  776. public static IEnumerable<T> GetRectPosItem<T>(this MapControl ctrl) where T : PosData, new()
  777. {
  778. var innerData = ctrl.Tag as InnerData;
  779. if (innerData.CurrentRect == default) return new List<T>();
  780. var rect = ctrl.GetCurrentRect();
  781. double startLon = rect.starLon;
  782. double startLat = rect.startLat;
  783. double endLon = rect.endLon;
  784. double endLat = rect.endLat;
  785. var temp = innerData._dataCache.Keys.Where(p => p.InRectangle(startLon, startLat, endLon, endLat));
  786. var res = temp.Select(p => (T)p);
  787. return res;
  788. }
  789. /// <summary>
  790. /// <para>设置地图瓦片Http地址.格式如http://192.168.100.63:58089</para>
  791. /// <para>当客户端本地运行目录或子目录存在Data.gmdb时Http接口不会被调用</para>
  792. /// </summary>
  793. /// <param name="ctrl"></param>
  794. /// <param name="httpAddr">such as http://192.168.100.63:58089</param>
  795. /// <returns></returns>
  796. public static MapControl SetMapDataHttpAddr(this MapControl ctrl, string httpAddr)
  797. {
  798. var provider = ctrl.GetImageLayer().DataProvider;
  799. if (provider is HttpMapDataProvider)
  800. {
  801. var tileSource = ((provider as HttpMapDataProvider).TileSource as HttpTileSource);
  802. tileSource.HttpServerAddr = httpAddr;
  803. }
  804. return ctrl;
  805. }
  806. /// <summary>
  807. /// 定位点使用内置聚合器
  808. /// </summary>
  809. /// <param name="ctrl"></param>
  810. /// <returns></returns>
  811. public static MapControl UseCluster(this MapControl ctrl)
  812. {
  813. var innerData = ctrl.Tag as InnerData;
  814. innerData.posStorge.Clusterer = new PosClusterer(ctrl);//定位点聚合器
  815. return ctrl;
  816. }
  817. /// <summary>
  818. /// 为地图添加右键测距功能
  819. /// </summary>
  820. /// <returns></returns>
  821. public static MapControl UseDistanceLine(this MapControl ctrl)
  822. {
  823. var btnDistance = new BarButtonItem() { Caption = "测距" };
  824. btnDistance.ImageOptions.SvgImage = SvgHelper.CreateDistanceLine();
  825. btnDistance.Tag = ctrl;
  826. btnDistance.ItemClick += DistanceLine_ItemClick;
  827. var innerData = ctrl.Tag as InnerData;
  828. innerData.barM.BeginInit();
  829. innerData.barM.Items.Add(btnDistance);
  830. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnDistance));
  831. innerData.barM.EndInit();
  832. return ctrl;
  833. }
  834. /// <summary>
  835. /// 为地图添加右键标点功能
  836. /// </summary>
  837. /// <param name="ctrl"></param>
  838. /// <param name="menu"></param>
  839. /// <param name="item"></param>
  840. /// <returns></returns>
  841. public static MapControl UseMarkDot(this MapControl ctrl)
  842. {
  843. var btnMarkDot = new BarButtonItem() { Caption = "标点" };
  844. btnMarkDot.ImageOptions.SvgImage = SvgHelper.CreateMarkDot();
  845. btnMarkDot.Tag = ctrl;
  846. btnMarkDot.ItemClick += MarkDot_ItemClick;
  847. var innerData = ctrl.Tag as InnerData;
  848. innerData.barM.BeginInit();
  849. innerData.barM.Items.Add(btnMarkDot);
  850. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnMarkDot));
  851. innerData.barM.EndInit();
  852. return ctrl;
  853. }
  854. /// <summary>
  855. /// 为地图添加清除功能
  856. /// </summary>
  857. /// <param name="ctrl"></param>
  858. /// <param name="item"></param>
  859. /// <returns></returns>
  860. public static MapControl UseClearAll(this MapControl ctrl)
  861. {
  862. var btnClearAll = new BarButtonItem() { Caption = "清除" };
  863. btnClearAll.ImageOptions.SvgImage = SvgHelper.CreateClear();
  864. btnClearAll.Tag = ctrl;
  865. btnClearAll.ItemClick += (sender, e) => ctrl.ClearDrawObj();
  866. var innerData = ctrl.Tag as InnerData;
  867. innerData.barM.BeginInit();
  868. innerData.barM.Items.Add(btnClearAll);
  869. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnClearAll));
  870. innerData.barM.EndInit();
  871. return ctrl;
  872. }
  873. /// <summary>
  874. /// 为地图添加导出图片功能
  875. /// </summary>
  876. /// <param name="ctrl"></param>
  877. /// <param name="item"></param>
  878. /// <returns></returns>
  879. public static MapControl UseExportImg(this MapControl ctrl)
  880. {
  881. var btnExportImg = new BarButtonItem() { Caption = "导出图片" };
  882. btnExportImg.ImageOptions.SvgImage = SvgHelper.CreateExportImg();
  883. btnExportImg.Tag = ctrl;
  884. btnExportImg.ItemClick += ExportImg_ItemClick;
  885. var innerData = ctrl.Tag as InnerData;
  886. innerData.barM.BeginInit();
  887. innerData.barM.Items.Add(btnExportImg);
  888. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportImg));
  889. innerData.barM.EndInit();
  890. return ctrl;
  891. }
  892. /// <summary>
  893. /// 为地图添加导出图片功能
  894. /// </summary>
  895. /// <param name="ctrl"></param>
  896. /// <param name="item"></param>
  897. /// <returns></returns>
  898. public static MapControl UseExportCsv(this MapControl ctrl, bool exportHeader = true)
  899. {
  900. var innerData = ctrl.Tag as InnerData;
  901. var btnExportCsv = new BarButtonItem() { Caption = "导出Csv" };
  902. btnExportCsv.ImageOptions.SvgImage = SvgHelper.CreateExportCsv();
  903. btnExportCsv.Tag = ctrl;
  904. btnExportCsv.ItemClick += (sender, e) =>
  905. {
  906. if (!innerData._dataCache.Any()) return;
  907. bool exportSigTime = false;
  908. Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
  909. var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  910. List<(int ColumnIndex, PropertyInfo Prop, string Header)> listPorps = new List<(int, PropertyInfo, string)>();
  911. foreach (var prop in props)
  912. {
  913. ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
  914. if (attrExport == null) continue;
  915. if (prop.Name == nameof(PosData.SigTime))
  916. exportSigTime = true;
  917. if (!string.IsNullOrWhiteSpace(attrExport.Format))
  918. {
  919. cellFormats.Add(prop.Name, attrExport.Format);
  920. }
  921. if (attrExport.ColumnIndex == -1)
  922. attrExport.ColumnIndex = 10000;
  923. var attrDisplay = prop.GetCustomAttribute<DisplayAttribute>();
  924. if (attrDisplay != null && !string.IsNullOrWhiteSpace(attrDisplay.Name))
  925. listPorps.Add((attrExport.ColumnIndex, prop, attrDisplay.Name));
  926. else
  927. listPorps.Add((attrExport.ColumnIndex, prop, prop.Name));
  928. }
  929. listPorps = listPorps.OrderBy(p => p.ColumnIndex).ToList();
  930. using (var dialog = new SaveFileDialog())
  931. {
  932. dialog.Filter = "CSV文件|*.csv";
  933. dialog.AddExtension = true;
  934. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.csv";
  935. if (dialog.ShowDialog() == DialogResult.OK)
  936. {
  937. var list = innerData._dataCache.Keys as IEnumerable<PosData>;
  938. if (exportSigTime)
  939. list = list.OrderByDescending(p => p.SigTime);//如果导出了SigTime,则自动按照SigTime降序排列后导出
  940. StreamWriter sw = new StreamWriter(dialog.FileName, false, new UTF8Encoding(true));//utf8-bom
  941. if (exportHeader)
  942. {
  943. foreach (var prop in listPorps)
  944. {
  945. sw.Write($"{prop.Header},");
  946. }
  947. sw.WriteLine();
  948. }
  949. WaitHelper.ShowOverlayForm(ctrl);
  950. long count = list.Count() * listPorps.Count;
  951. int idx = 1;
  952. foreach (var item in list)
  953. {
  954. foreach (var prop in listPorps)
  955. {
  956. WaitHelper.UpdateOverlyText($"{idx * 100 / count}%");
  957. var value = prop.Prop.GetValue(item);
  958. string str = null;
  959. if (cellFormats.ContainsKey(prop.Prop.Name))
  960. {
  961. str = ((dynamic)value).ToString(cellFormats[prop.Prop.Name]);
  962. }
  963. else
  964. {
  965. if (value is DateTime)
  966. str = $"{(DateTime)value:yyyy-MM-dd HH:mm:ss}";
  967. else if (value is float || value is double || value is decimal)
  968. {
  969. dynamic valD = value;
  970. str = ((dynamic)value).ToString("f4");
  971. }
  972. }
  973. sw.Write($"{str},");
  974. idx++;
  975. }
  976. sw.WriteLine();
  977. }
  978. sw.Close();
  979. WaitHelper.CloseOverlayForm();
  980. }
  981. }
  982. GC.Collect();
  983. };
  984. innerData.barM.BeginInit();
  985. innerData.barM.Items.Add(btnExportCsv);
  986. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportCsv));
  987. innerData.barM.EndInit();
  988. return ctrl;
  989. }
  990. /// <summary>
  991. /// 为地图添加导出Excel数据功能
  992. /// </summary>
  993. /// <typeparam name="T"></typeparam>
  994. /// <param name="ctrl"></param>
  995. /// <param name="exportHeader">是否导出列头</param>
  996. /// <returns></returns>
  997. public static MapControl UseExportXlsx(this MapControl ctrl, bool exportHeader = true)
  998. {
  999. Action action = () =>
  1000. {
  1001. var btnExportXlsx = new BarButtonItem() { Caption = "导出Excel" };
  1002. btnExportXlsx.ImageOptions.SvgImage = SvgHelper.CreateExportXlsx();
  1003. var innerData = ctrl.Tag as InnerData;
  1004. innerData.barM.BeginInit();
  1005. innerData.barM.Items.Add(btnExportXlsx);
  1006. innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportXlsx));
  1007. innerData.barM.EndInit();
  1008. btnExportXlsx.ItemClick += (sender, e) =>
  1009. {
  1010. if (!innerData._dataCache.Any()) return;
  1011. GridControl gc = new GridControl();
  1012. GridView view = new GridView();
  1013. view.GridControl = gc;
  1014. gc.MainView = view;
  1015. gc.ViewCollection.Add(view);
  1016. view.OptionsPrint.ShowPrintExportProgress = false;
  1017. bool exportSigTime = false;
  1018. Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
  1019. var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  1020. foreach (var prop in props)
  1021. {
  1022. ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
  1023. if (attrExport == null) continue;
  1024. if (prop.Name == nameof(PosData.SigTime))
  1025. exportSigTime = true;
  1026. if (!string.IsNullOrWhiteSpace(attrExport.Format))
  1027. {
  1028. cellFormats.Add(prop.Name, attrExport.Format);
  1029. }
  1030. var col = new GridColumn();
  1031. col.FieldName = prop.Name;
  1032. col.Visible = true;
  1033. var attr = prop.GetCustomAttribute<DisplayAttribute>();
  1034. if (attr != null && !string.IsNullOrWhiteSpace(attr.Name))
  1035. col.Caption = attr.Name;
  1036. else
  1037. col.Caption = prop.Name;
  1038. if (attrExport.ColumnIndex >= 0)
  1039. col.VisibleIndex = attrExport.ColumnIndex;
  1040. view.Columns.Add(col);
  1041. }
  1042. gc.Visible = false;
  1043. gc.Parent = ctrl.Parent;
  1044. using (var dialog = new SaveFileDialog())
  1045. {
  1046. dialog.Filter = "Excel文件|*.xlsx";
  1047. dialog.AddExtension = true;
  1048. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
  1049. if (dialog.ShowDialog() == DialogResult.OK)
  1050. {
  1051. var list = innerData._dataCache.Keys.ToList();
  1052. if (exportSigTime)
  1053. list = list.OrderByDescending(p => p.SigTime).ToList();//如果导出了SigTime,则自动按照SigTime降序排列后导出
  1054. gc.DataSource = list;
  1055. gc.Visible = true;
  1056. var exportType = DevExpress.Export.ExportSettings.DefaultExportType;
  1057. var options = new XlsxExportOptionsEx();
  1058. WaitHelper.ShowOverlayForm(ctrl);
  1059. options.ExportProgress += arg =>
  1060. {
  1061. WaitHelper.UpdateOverlyText($"{arg.ProgressPercentage}%");
  1062. if (arg.ProgressPercentage >= 100)
  1063. {
  1064. WaitHelper.CloseOverlayForm();
  1065. }
  1066. };
  1067. view.OptionsPrint.PrintHeader = exportHeader;
  1068. options.CustomizeCell += arg =>
  1069. {
  1070. arg.Handled = true;
  1071. var aligmentCenter = new XlCellAlignment()
  1072. {
  1073. HorizontalAlignment = XlHorizontalAlignment.Center,
  1074. VerticalAlignment = XlVerticalAlignment.Center
  1075. };
  1076. var aligmentLeft = new XlCellAlignment()
  1077. {
  1078. HorizontalAlignment = XlHorizontalAlignment.Left,
  1079. VerticalAlignment = XlVerticalAlignment.Center
  1080. };
  1081. if (arg.Value is bool)
  1082. {
  1083. arg.Formatting.Alignment = aligmentCenter;
  1084. arg.Value = ((bool)arg.Value) ? "☑" : "☐";
  1085. }
  1086. if (arg.Value is DateTime)
  1087. {
  1088. arg.Formatting.Alignment = aligmentLeft;
  1089. arg.Formatting.FormatType = FormatType.DateTime;
  1090. arg.Formatting.FormatString = "yyyy-MM-dd HH:mm:ss";
  1091. }
  1092. else if (arg.Value is float || arg.Value is double || arg.Value is decimal)
  1093. {
  1094. arg.Formatting.Alignment = aligmentLeft;
  1095. arg.Formatting.FormatType = FormatType.Numeric;
  1096. arg.Formatting.FormatString = "f4";
  1097. }
  1098. if (cellFormats.ContainsKey(arg.ColumnFieldName))
  1099. {
  1100. arg.Formatting.FormatString = cellFormats[arg.ColumnFieldName];
  1101. }
  1102. };
  1103. view.OptionsPrint.ShowPrintExportProgress = false;
  1104. DevExpress.Export.ExportSettings.DefaultExportType = DevExpress.Export.ExportType.DataAware;
  1105. gc.ExportToXlsx(dialog.FileName, options);
  1106. DevExpress.Export.ExportSettings.DefaultExportType = exportType;
  1107. gc.Visible = false;
  1108. }
  1109. }
  1110. gc.Parent = null;
  1111. gc.Dispose();
  1112. GC.Collect();
  1113. };
  1114. };
  1115. if (ctrl.Parent == null)
  1116. {
  1117. ctrl.ParentChanged += (sender, e) => action();
  1118. }
  1119. else
  1120. {
  1121. action();
  1122. }
  1123. return ctrl;
  1124. }
  1125. /// <summary>
  1126. /// 为地图添加矩形框选区域功能
  1127. /// </summary>
  1128. /// <returns></returns>
  1129. public static MapControl UseDrawRect(this MapControl ctrl, Action<(double starLon, double startLat, double centerLon, double centerLat,
  1130. double endLon, double endLat, double lonRange, double latRange)> onRectChanged = null)
  1131. {
  1132. var innerData = ctrl.Tag as InnerData;
  1133. innerData.mOnRectChanged = onRectChanged;
  1134. ctrl.MapEditor.ShowEditorPanel = true;
  1135. ctrl.MapEditor.PanelOptions.ShowAddCalloutButton = false;
  1136. ctrl.MapEditor.PanelOptions.ShowAddCustomElementButton = false;
  1137. ctrl.MapEditor.PanelOptions.ShowAddDotButton = false;
  1138. ctrl.MapEditor.PanelOptions.ShowAddEllipseButton = false;
  1139. ctrl.MapEditor.PanelOptions.ShowAddLineButton = false;
  1140. ctrl.MapEditor.PanelOptions.ShowAddPathButton = false;
  1141. ctrl.MapEditor.PanelOptions.ShowAddPolylineButton = false;
  1142. ctrl.MapEditor.PanelOptions.ShowAddPushpinButton = false;
  1143. ctrl.MapEditor.PanelOptions.ShowAddSplineButton = false;
  1144. ctrl.MapEditor.PanelOptions.ShowEditModeButton = false;
  1145. ctrl.MapEditor.PanelOptions.ShowTransformModeButton = false;
  1146. ctrl.MapEditor.PanelOptions.ShowUndoRedoButtons = false;
  1147. ctrl.MouseMove += DrawRect_MouseMove;
  1148. ctrl.MapEditor.MapItemCreating += (sender, e) =>
  1149. {
  1150. if (!innerData.mouseLeftDown)
  1151. {
  1152. e.Cancel = true;
  1153. return;
  1154. }
  1155. if (!(e.Item is MapRectangle)) return;
  1156. var items = innerData.mMapStorage.Items.ToList().FindAll(p => p.Tag != null && p.Tag.ToString() == "DrawRect");
  1157. ctrl.MapEditor.RemoveItems(items);
  1158. var item = e.Item as MapRectangle;
  1159. item.Tag = "DrawRect";
  1160. item.CanMove = false;
  1161. item.CanResize = false;
  1162. item.EnableSelection = DefaultBoolean.False;
  1163. item.EnableHighlighting = DefaultBoolean.True;
  1164. innerData.rangeItem = item;
  1165. if (innerData.rangeItem.Height == 0 && innerData.rangeItem.Width == 0)
  1166. {
  1167. innerData.rangeItem.Height = 5;
  1168. innerData.rangeItem.Width = 5;
  1169. }
  1170. item.Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209));
  1171. item.Stroke = Color.FromArgb(23, 107, 209);
  1172. item.StrokeWidth = 1;
  1173. innerData.dotItem.Fill = Color.Red;
  1174. innerData.dotItem.Size = 6;
  1175. innerData.dotItem.Location = innerData.rangeItem.GetCenter();
  1176. innerData.mMapStorage.Items.Add(innerData.rangeItem);
  1177. innerData.mMapStorage.Items.Add(innerData.dotItem);
  1178. DrawRect_MouseMove(ctrl, null);
  1179. var layer = ctrl.Layers.Find(p => p.Name == "");
  1180. if (layer != null) ctrl.Layers.Remove(layer);
  1181. };
  1182. ctrl.MapEditor.MapItemEdited += (sender, e) =>
  1183. {
  1184. innerData.drawingRect = e.Action == MapEditorAction.Create;
  1185. };
  1186. return ctrl;
  1187. }
  1188. /// <summary>
  1189. /// 绘制矩形
  1190. /// </summary>
  1191. /// <param name="ctrl"></param>
  1192. /// <param name="startLon"></param>
  1193. /// <param name="startLat"></param>
  1194. /// <param name="endLon"></param>
  1195. /// <param name="endLat"></param>
  1196. public static void DrawRect(this MapControl ctrl, double startLon, double startLat, double endLon, double endLat, bool recCallback = false)
  1197. {
  1198. var innerData = ctrl.Tag as InnerData;
  1199. if (innerData.rangeItem != null)
  1200. innerData.mMapStorage.Items.Remove(innerData.rangeItem);
  1201. if (innerData.dotItem != null)
  1202. innerData.mMapStorage.Items.Remove(innerData.dotItem);
  1203. double centerLon = (startLon + endLon) / 2;
  1204. double centerLat = (startLat + endLat) / 2;
  1205. var size = BoundingRectItemHelper.CalculateRectangleSize(ctrl.CoordinateSystem,
  1206. new GeoPoint(startLat, startLon),
  1207. new GeoPoint(endLat, endLon));
  1208. innerData.dotItem.Location = new GeoPoint(centerLat, centerLon);
  1209. innerData.dotItem.Fill = Color.Red;
  1210. innerData.dotItem.Size = 8;
  1211. var rect = new MapRectangle()
  1212. {
  1213. CanMove = false,
  1214. CanResize = false,
  1215. EnableSelection = DefaultBoolean.False,
  1216. EnableHighlighting = DefaultBoolean.True,
  1217. Tag = "DrawRect",
  1218. Width = size.Width,
  1219. Height = size.Height,
  1220. Location = new GeoPoint(startLat, startLon),
  1221. Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209)),
  1222. Stroke = Color.FromArgb(23, 107, 209),
  1223. StrokeWidth = 1
  1224. };
  1225. innerData.rangeItem = rect;
  1226. innerData.CurrentRect = (startLon, startLat, centerLon, centerLat, endLon, endLat, (endLon - startLon) / 2, (endLat - startLat) / 2);
  1227. innerData.mMapStorage.Items.Add(innerData.rangeItem);
  1228. innerData.mMapStorage.Items.Add(innerData.dotItem);
  1229. if (recCallback)
  1230. innerData.mOnRectChanged?.Invoke(ctrl.GetCurrentRect());
  1231. }
  1232. public static void DrawGdopLine(this MapControl ctrl, IEnumerable<(string wcKm, double lon, double lat)> lines)
  1233. {
  1234. if (lines == null || !lines.Any()) return;
  1235. var innerData = ctrl.Tag as InnerData;
  1236. var wcKm = lines.First().wcKm;
  1237. var polyLine = new MapPolyline()
  1238. {
  1239. Stroke = ColorHelper.GetColor(wcKm),
  1240. StrokeWidth = 2,
  1241. IsGeodesic = true,
  1242. CanResize = false,
  1243. CanEdit = false,
  1244. CanRotate = false,
  1245. IsHitTestVisible = true,
  1246. CanMove = false,
  1247. Tag = $"DrawGdopLine_{wcKm}",
  1248. };
  1249. polyLine.TitleOptions.Pattern = wcKm;
  1250. foreach (var item in lines)
  1251. {
  1252. if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
  1253. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1254. }
  1255. if (!polyLine.Points.Any()) return;
  1256. innerData.mMapStorage.Items.Add(polyLine);
  1257. }
  1258. public static void DrawErrEllipse(this MapControl ctrl, double r1, double r2, IEnumerable<(double lon, double lat)> lines)
  1259. {
  1260. if (lines == null || !lines.Any()) return;
  1261. var innerData = ctrl.Tag as InnerData;
  1262. //innerData.mMapStorage.Items.Clear();
  1263. var polyLine = new MapPolyline()
  1264. {
  1265. Stroke = Color.Red,
  1266. StrokeWidth = 4,
  1267. IsGeodesic = true,
  1268. CanResize = false,
  1269. CanEdit = false,
  1270. CanRotate = false,
  1271. IsHitTestVisible = true,
  1272. CanMove = false,
  1273. Tag = $"DrawErrEllipse",
  1274. };
  1275. //polyLine.ToolTipPattern = $"长轴:{r1:f1}km\r\n短轴:{r2:f1}km";
  1276. foreach (var item in lines)
  1277. {
  1278. if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
  1279. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1280. }
  1281. if (!polyLine.Points.Any()) return;
  1282. innerData.mMapStorage.Items.Add(polyLine);
  1283. var callout = new DevExpress.XtraMap.MapCallout()
  1284. {
  1285. Text = $"R1={r1:f1}km\r\nR2={r2:f1}km",
  1286. Location = polyLine.Points.First(),
  1287. CanMove = false,
  1288. IsHitTestVisible = false,
  1289. };
  1290. innerData.mMapStorage.Items.Add(callout);
  1291. }
  1292. public static void ClearRect(this MapControl ctrl)
  1293. {
  1294. var innerDate = ctrl.Tag as InnerData;
  1295. if (innerDate.rangeItem != null)
  1296. innerDate.mMapStorage.Items.Remove(innerDate.rangeItem);
  1297. if (innerDate.dotItem != null)
  1298. innerDate.mMapStorage.Items.Remove(innerDate.dotItem);
  1299. }
  1300. /// <summary>
  1301. /// 获取地图框选的范围信息(可能为null)
  1302. /// </summary>
  1303. /// <param name="ctrl"></param>
  1304. /// <returns></returns>
  1305. public static (double starLon, double startLat, double centerLon, double centerLat,
  1306. double endLon, double endLat, double lonRange, double latRange) GetCurrentRect(this MapControl ctrl)
  1307. {
  1308. var innerData = ctrl.Tag as InnerData;
  1309. return innerData.CurrentRect;
  1310. }
  1311. /// <summary>
  1312. /// 获取地图瓦片图层
  1313. /// </summary>
  1314. /// <param name="ctrl"></param>
  1315. /// <returns></returns>
  1316. public static ImageLayer GetImageLayer(this MapControl ctrl)
  1317. {
  1318. if (ctrl.Layers == null) return null;
  1319. return (ImageLayer)ctrl.Layers["ImageTileLayer"];
  1320. }
  1321. /// <summary>
  1322. /// 获取地图绘制图层
  1323. /// </summary>
  1324. /// <param name="ctrl"></param>
  1325. /// <returns></returns>
  1326. public static VectorItemsLayer GetDrawLayer(this MapControl ctrl)
  1327. {
  1328. return (VectorItemsLayer)ctrl.Layers["DrawLayer"];
  1329. }
  1330. /// <summary>
  1331. /// 获取地图绘制图层
  1332. /// </summary>
  1333. /// <param name="ctrl"></param>
  1334. /// <returns></returns>
  1335. public static VectorItemsLayer GetPosLayer(this MapControl ctrl)
  1336. {
  1337. return (VectorItemsLayer)ctrl.Layers["PosLayer"];
  1338. }
  1339. /// <summary>
  1340. /// 获取地图绘制图层的数据仓库
  1341. /// </summary>
  1342. /// <param name="ctrl"></param>
  1343. /// <returns></returns>
  1344. public static MapItemStorage GetDrawStorage(this MapControl ctrl)
  1345. {
  1346. var innerData = ctrl.Tag as InnerData;
  1347. return innerData.mMapStorage;
  1348. }
  1349. /// <summary>
  1350. /// 设置地图类型.默认为Normal
  1351. /// 该方法为所有MapControl实例设置地图类型
  1352. /// </summary>
  1353. /// <param name="ctrl"></param>
  1354. /// <param name="mapType"></param>
  1355. public static void SetMapType(GoogleMapType mapType)
  1356. {
  1357. mMapType = mapType;
  1358. listMapCtrl.ForEach(t =>
  1359. {
  1360. if (t.GetImageLayer() == null) return;
  1361. var provider = t.GetImageLayer().DataProvider as MapTileDataProviderBase;
  1362. provider?.ClearCache();
  1363. t.Refresh();
  1364. });
  1365. }
  1366. #region private
  1367. private static void DrawRect_MouseMove(object sender, MouseEventArgs e)
  1368. {
  1369. var innerData = (sender as MapControl).Tag as InnerData;
  1370. if (!innerData.drawingRect) return;
  1371. innerData.dotItem.Location = innerData.rangeItem.GetCenter();
  1372. var startLon = Math.Round(innerData.rangeItem.Location.GetX(), 3);
  1373. var startLat = Math.Round(innerData.rangeItem.Location.GetY(), 3);
  1374. if (startLon >= 180)
  1375. {
  1376. startLon -= 360;
  1377. }
  1378. if (startLon <= -180)
  1379. {
  1380. startLon += 360;
  1381. }
  1382. var center = innerData.rangeItem.GetCenter();
  1383. var centerLon = Math.Round(center.GetX(), 3);
  1384. if (centerLon >= 180)
  1385. {
  1386. centerLon -= 360;
  1387. }
  1388. if (centerLon <= -180)
  1389. {
  1390. centerLon += 360;
  1391. }
  1392. var centerLat = Math.Round(center.GetY(), 3);
  1393. double endLon;
  1394. if (centerLon < 0 && startLon > 0)
  1395. endLon = startLon + 2 * (centerLon + 360 - startLon);
  1396. else
  1397. endLon = startLon + 2 * (centerLon - startLon);
  1398. var endLat = startLat + 2 * (centerLat - startLat);
  1399. var StartLon = Math.Min(startLon, endLon);
  1400. var StartLat = Math.Min(startLat, endLat);
  1401. var CenterLon = centerLon;
  1402. var CenterLat = centerLat;
  1403. var EndLon = Math.Max(startLon, endLon);
  1404. var EndLat = Math.Max(startLat, endLat);
  1405. double centerLonNew = CenterLon % 360;
  1406. CenterLon = centerLonNew;
  1407. //double LonRange = Math.Round((EndLon - StartLon) / 2, 3);
  1408. //double LatRange = Math.Round((EndLat - StartLat) / 2, 3);
  1409. double LonRange = Math.Round((EndLon - StartLon), 3);
  1410. double LatRange = Math.Round((EndLat - StartLat), 3);
  1411. if (LonRange >= 360)
  1412. {
  1413. }
  1414. innerData.CurrentRect = (StartLon, StartLat, CenterLon, CenterLat, EndLon, EndLat, LonRange, LatRange);
  1415. innerData.mOnRectChanged?.Invoke(innerData.CurrentRect);
  1416. }
  1417. private static void ExportImg_ItemClick(object sender, ItemClickEventArgs e)
  1418. {
  1419. var ctrl = e.Item.Tag as MapControl;
  1420. using (var dialog = new SaveFileDialog())
  1421. {
  1422. dialog.Filter = "PNG图片|*.png";
  1423. dialog.AddExtension = true;
  1424. dialog.FileName = $"Map{DateTime.Now:yyyyMMddHHmmss}.png";
  1425. if (dialog.ShowDialog() == DialogResult.OK)
  1426. {
  1427. ctrl.ExportToImage(dialog.FileName, ImageFormat.Png);
  1428. }
  1429. }
  1430. }
  1431. private static void ExportCsv_ItemClick(object sender, ItemClickEventArgs e)
  1432. {
  1433. var ctrl = e.Item.Tag as MapControl;
  1434. using (var dialog = new SaveFileDialog())
  1435. {
  1436. dialog.Filter = "CSV文件|*.csv";
  1437. dialog.AddExtension = true;
  1438. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
  1439. if (dialog.ShowDialog() == DialogResult.OK)
  1440. {
  1441. ctrl.ExportToXlsx(dialog.FileName);
  1442. }
  1443. }
  1444. }
  1445. private static void ClearDrawObj(this MapControl ctrl)
  1446. {
  1447. ctrl.Invoke(new Action(() =>
  1448. {
  1449. try
  1450. {
  1451. var innerData = ctrl.Tag as InnerData;
  1452. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1453. innerData.drawingRect = false;
  1454. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1455. innerData.rangeItem = null;
  1456. if (innerData.mMapStorage != null && innerData.mMapStorage.Items.Any())
  1457. {
  1458. innerData.mMapStorage.Items.Clear();
  1459. }
  1460. //临时
  1461. if (innerData.mMapStorageFixed != null && innerData.mMapStorageFixed.Items.Any())
  1462. innerData.mMapStorageFixed.Items.Clear();
  1463. }
  1464. catch (Exception ex)
  1465. {
  1466. }
  1467. }));
  1468. }
  1469. private static void DistanceLine_ItemClick(object sender, ItemClickEventArgs e)
  1470. {
  1471. var ctrl = e.Item.Tag as MapControl;
  1472. var innerData = ctrl.Tag as InnerData;
  1473. ctrl.MapEditor.SetEditMode();
  1474. var items = innerData.mMapStorage.Items.ToArray();
  1475. foreach (var item in items)
  1476. {
  1477. if (item.Tag != null && item.Tag.ToString() == "DrawDistanceLine")
  1478. innerData.mMapStorage.Items.Remove(item);
  1479. }
  1480. if (innerData.distinctPath != null)
  1481. {
  1482. innerData.distinctPath.Points.Clear();
  1483. }
  1484. innerData.distinctPath = new MapPolyline()
  1485. {
  1486. Stroke = Color.FromArgb(127, 255, 0, 199),
  1487. StrokeWidth = 2,
  1488. IsGeodesic = true,
  1489. CanResize = false,
  1490. CanEdit = false,
  1491. CanRotate = false,
  1492. IsHitTestVisible = false,
  1493. CanMove = true,
  1494. Tag = "DrawDistanceLine"
  1495. };
  1496. innerData.mMapStorage.Items.Add(innerData.distinctPath);
  1497. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1498. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1499. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1500. innerData.hoverTip = CreateHoverTip();
  1501. ctrl.MouseClick += AddDistinctPoint;
  1502. ctrl.MouseMove += MovingDistinct;
  1503. ctrl.MouseLeave += MapControl_MouseLeave;
  1504. ctrl.MouseEnter += MapControl_MouseEnter;
  1505. ctrl.DoubleClick += EndDistinct;
  1506. }
  1507. private static void MarkDot_ItemClick(object sender, ItemClickEventArgs e)
  1508. {
  1509. var ctrl = e.Item.Tag as MapControl;
  1510. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1511. var innerData = ctrl.Tag as InnerData;
  1512. innerData.drawingRect = false;
  1513. using (var frm = new MapEditPointView())
  1514. {
  1515. if (frm.ShowDialog() != DialogResult.OK) return;
  1516. var locPoint = new GeoPoint(frm.Lat, frm.Lon);
  1517. MapCustomElement cusItem = new MapCustomElement()
  1518. {
  1519. Location = locPoint,
  1520. UseAnimation = true,
  1521. CanMove = false,
  1522. EnableHighlighting = DefaultBoolean.True,
  1523. EnableSelection = DefaultBoolean.False,
  1524. Text = "",
  1525. ToolTipPattern = $"{frm.Caption}",
  1526. SvgImage = SvgHelper.CreatePentagram(),
  1527. SvgImageSize = new Size(32, 32),
  1528. TextAlignment = DevExpress.XtraMap.TextAlignment.BottomCenter,
  1529. Tag = "DrawMarkDot"
  1530. };
  1531. innerData.mMapStorage.Items.Add(cusItem);
  1532. }
  1533. }
  1534. private static ToolTipControllerShowEventArgs CreateHoverTip()
  1535. {
  1536. ToolTipTitleItem titleItem1 = new ToolTipTitleItem() { Text = $"0千米" };
  1537. titleItem1.Appearance.ForeColor = SystemColors.GrayText;
  1538. titleItem1.Appearance.Font = new Font(AppearanceObject.DefaultFont.FontFamily, 12, FontStyle.Bold);
  1539. SuperToolTip superToolTip = new SuperToolTip();
  1540. superToolTip.Items.Add(titleItem1);
  1541. ToolTipSeparatorItem sepItem = new ToolTipSeparatorItem();
  1542. superToolTip.Items.Add(sepItem);
  1543. ToolTipItem textItem = new ToolTipItem() { Text = "单击添加测距点,双击结束测距" };
  1544. superToolTip.Items.Add(textItem);
  1545. ToolTipControllerShowEventArgs arg = new ToolTipControllerShowEventArgs();
  1546. arg.ShowBeak = true;
  1547. arg.SuperTip = superToolTip;
  1548. return arg;
  1549. }
  1550. private static void MapControl_MouseEnter(object sender, EventArgs e)
  1551. {
  1552. var innerData = (sender as MapControl).Tag as InnerData;
  1553. innerData.hoverPoint.Visible = true;
  1554. }
  1555. private static void MapControl_MouseLeave(object sender, EventArgs e)
  1556. {
  1557. var innerData = (sender as MapControl).Tag as InnerData;
  1558. innerData.hoverPoint.Visible = false;
  1559. }
  1560. private static void AddDistinctPoint(object sender, MouseEventArgs e)
  1561. {
  1562. var innerData = (sender as MapControl).Tag as InnerData;
  1563. var ctrl = sender as MapControl;
  1564. MapCallout disItem = new MapCallout { IsHitTestVisible = false, CanMove = false };
  1565. disItem.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1566. disItem.Text = $"{CalcLineKm(innerData):F2}千米";
  1567. disItem.Tag = "DrawDistanceLine";
  1568. innerData.mMapStorage.Items.Add(disItem);
  1569. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1570. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1571. innerData.hoverPoint.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1572. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1573. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1574. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1575. }
  1576. private static void MovingDistinct(object sender, MouseEventArgs e)
  1577. {
  1578. var innerData = (sender as MapControl).Tag as InnerData;
  1579. var ctrl = sender as MapControl;
  1580. var itemPoint = ctrl.ScreenPointToCoordPoint(e.Location);
  1581. innerData.hoverPoint.Location = itemPoint;
  1582. if (innerData.distinctPath.Points.Count > 0)
  1583. {
  1584. ctrl.MapEditor.SetEditMode();
  1585. innerData.distinctPath.Points[innerData.distinctPath.Points.Count - 1] = itemPoint;
  1586. (innerData.hoverTip.SuperTip.Items[0] as ToolTipTitleItem).Text = $"{CalcLineKm(innerData):F2}千米";
  1587. innerData.mapToolTip.ShowHint(innerData.hoverTip, ctrl.PointToScreen(e.Location));
  1588. }
  1589. }
  1590. private static double CalcLineKm(InnerData data)
  1591. {
  1592. double result = 0;
  1593. if (data.distinctPath.Points.Count < 2) return result;
  1594. for (int i = 0; i < data.distinctPath.Points.Count - 1; i++)
  1595. {
  1596. var startPoint = data.distinctPath.Points[i] as GeoPoint;
  1597. var endPoint = data.distinctPath.Points[i + 1] as GeoPoint;
  1598. MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
  1599. double partlength = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
  1600. result += partlength;
  1601. }
  1602. return result;
  1603. }
  1604. public static void ClearMap(this MapControl ctrl)
  1605. {
  1606. var innerData = ctrl.Tag as InnerData;
  1607. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1608. innerData.mMapStorage?.Items.Clear();
  1609. }
  1610. private static void EndDistinct(object sender, EventArgs e)
  1611. {
  1612. var ctrl = sender as MapControl;
  1613. var innerData = ctrl.Tag as InnerData;
  1614. innerData.mapToolTip.HideHint();
  1615. ctrl.MouseClick -= AddDistinctPoint;
  1616. ctrl.MouseMove -= MovingDistinct;
  1617. ctrl.DoubleClick -= EndDistinct;
  1618. ctrl.MouseLeave -= MapControl_MouseLeave;
  1619. ctrl.MouseEnter -= MapControl_MouseEnter;
  1620. }
  1621. class MapEditPointView : DevExpress.XtraEditors.XtraForm
  1622. {
  1623. private System.ComponentModel.IContainer components = null;
  1624. private DevExpress.XtraLayout.LayoutControl layoutControl1;
  1625. private DevExpress.XtraLayout.LayoutControlGroup Root;
  1626. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
  1627. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
  1628. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
  1629. private DevExpress.XtraEditors.ButtonEdit txtLon;
  1630. private DevExpress.XtraEditors.ButtonEdit txtLat;
  1631. private DevExpress.XtraEditors.TextEdit txtCaption;
  1632. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
  1633. private DevExpress.XtraEditors.SimpleButton btnCancel;
  1634. private DevExpress.XtraEditors.SimpleButton btnOk;
  1635. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
  1636. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
  1637. private DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider dxErrorProvider1;
  1638. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
  1639. private void InitializeComponent()
  1640. {
  1641. this.components = new System.ComponentModel.Container();
  1642. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions1 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1643. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject1 = new DevExpress.Utils.SerializableAppearanceObject();
  1644. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject2 = new DevExpress.Utils.SerializableAppearanceObject();
  1645. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject3 = new DevExpress.Utils.SerializableAppearanceObject();
  1646. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject4 = new DevExpress.Utils.SerializableAppearanceObject();
  1647. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions2 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1648. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject5 = new DevExpress.Utils.SerializableAppearanceObject();
  1649. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject6 = new DevExpress.Utils.SerializableAppearanceObject();
  1650. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject7 = new DevExpress.Utils.SerializableAppearanceObject();
  1651. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject8 = new DevExpress.Utils.SerializableAppearanceObject();
  1652. this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
  1653. this.txtCaption = new DevExpress.XtraEditors.TextEdit();
  1654. this.txtLon = new DevExpress.XtraEditors.ButtonEdit();
  1655. this.txtLat = new DevExpress.XtraEditors.ButtonEdit();
  1656. this.Root = new DevExpress.XtraLayout.LayoutControlGroup();
  1657. this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
  1658. this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
  1659. this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
  1660. this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
  1661. this.btnOk = new DevExpress.XtraEditors.SimpleButton();
  1662. this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
  1663. this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
  1664. this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
  1665. this.dxErrorProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(this.components);
  1666. this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem();
  1667. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
  1668. this.layoutControl1.SuspendLayout();
  1669. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).BeginInit();
  1670. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).BeginInit();
  1671. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).BeginInit();
  1672. ((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit();
  1673. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
  1674. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
  1675. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
  1676. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
  1677. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
  1678. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
  1679. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).BeginInit();
  1680. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit();
  1681. this.SuspendLayout();
  1682. //
  1683. // layoutControl1
  1684. //
  1685. this.layoutControl1.Controls.Add(this.btnCancel);
  1686. this.layoutControl1.Controls.Add(this.btnOk);
  1687. this.layoutControl1.Controls.Add(this.txtCaption);
  1688. this.layoutControl1.Controls.Add(this.txtLon);
  1689. this.layoutControl1.Controls.Add(this.txtLat);
  1690. this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
  1691. this.layoutControl1.Location = new System.Drawing.Point(0, 0);
  1692. this.layoutControl1.Name = "layoutControl1";
  1693. this.layoutControl1.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(689, 0, 650, 400);
  1694. this.layoutControl1.Root = this.Root;
  1695. this.layoutControl1.Size = new System.Drawing.Size(272, 208);
  1696. this.layoutControl1.TabIndex = 0;
  1697. this.layoutControl1.Text = "layoutControl1";
  1698. //
  1699. // txtCaption
  1700. //
  1701. this.txtCaption.Location = new System.Drawing.Point(12, 29);
  1702. this.txtCaption.Name = "txtCaption";
  1703. this.txtCaption.Properties.Appearance.Options.UseTextOptions = true;
  1704. this.txtCaption.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1705. this.txtCaption.Properties.AutoHeight = false;
  1706. this.txtCaption.Properties.MaxLength = 30;
  1707. this.txtCaption.Size = new System.Drawing.Size(248, 22);
  1708. this.txtCaption.StyleController = this.layoutControl1;
  1709. this.txtCaption.TabIndex = 9;
  1710. //
  1711. // txtLon
  1712. //
  1713. this.txtLon.Location = new System.Drawing.Point(12, 80);
  1714. this.txtLon.Name = "txtLon";
  1715. this.txtLon.Properties.Appearance.Options.UseTextOptions = true;
  1716. this.txtLon.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1717. this.txtLon.Properties.AutoHeight = false;
  1718. this.txtLon.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1719. 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)});
  1720. this.txtLon.Size = new System.Drawing.Size(248, 22);
  1721. this.txtLon.StyleController = this.layoutControl1;
  1722. this.txtLon.TabIndex = 4;
  1723. //
  1724. // txtLat
  1725. //
  1726. this.txtLat.Location = new System.Drawing.Point(12, 131);
  1727. this.txtLat.Name = "txtLat";
  1728. this.txtLat.Properties.Appearance.Options.UseTextOptions = true;
  1729. this.txtLat.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1730. this.txtLat.Properties.AutoHeight = false;
  1731. this.txtLat.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1732. 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)});
  1733. this.txtLat.Size = new System.Drawing.Size(248, 22);
  1734. this.txtLat.StyleController = this.layoutControl1;
  1735. this.txtLat.TabIndex = 5;
  1736. //
  1737. // Root
  1738. //
  1739. this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
  1740. this.Root.GroupBordersVisible = false;
  1741. this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
  1742. this.layoutControlItem1,
  1743. this.emptySpaceItem1,
  1744. this.layoutControlItem5,
  1745. this.layoutControlItem2,
  1746. this.layoutControlItem3,
  1747. this.layoutControlItem6,
  1748. this.emptySpaceItem2});
  1749. this.Root.Name = "Root";
  1750. this.Root.Size = new System.Drawing.Size(272, 208);
  1751. this.Root.TextVisible = false;
  1752. //
  1753. // layoutControlItem1
  1754. //
  1755. this.layoutControlItem1.Control = this.txtLon;
  1756. this.layoutControlItem1.Location = new System.Drawing.Point(0, 43);
  1757. this.layoutControlItem1.MaxSize = new System.Drawing.Size(0, 51);
  1758. this.layoutControlItem1.MinSize = new System.Drawing.Size(54, 51);
  1759. this.layoutControlItem1.Name = "layoutControlItem1";
  1760. this.layoutControlItem1.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  1761. this.layoutControlItem1.Size = new System.Drawing.Size(252, 51);
  1762. this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1763. this.layoutControlItem1.Text = "经度";
  1764. this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Top;
  1765. this.layoutControlItem1.TextSize = new System.Drawing.Size(24, 14);
  1766. //
  1767. // emptySpaceItem1
  1768. //
  1769. this.emptySpaceItem1.AllowHotTrack = false;
  1770. this.emptySpaceItem1.Location = new System.Drawing.Point(0, 162);
  1771. this.emptySpaceItem1.MaxSize = new System.Drawing.Size(0, 26);
  1772. this.emptySpaceItem1.MinSize = new System.Drawing.Size(104, 26);
  1773. this.emptySpaceItem1.Name = "emptySpaceItem1";
  1774. this.emptySpaceItem1.Size = new System.Drawing.Size(113, 26);
  1775. this.emptySpaceItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1776. this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
  1777. //
  1778. // layoutControlItem2
  1779. //
  1780. this.layoutControlItem2.Control = this.txtLat;
  1781. this.layoutControlItem2.Location = new System.Drawing.Point(0, 94);
  1782. this.layoutControlItem2.MaxSize = new System.Drawing.Size(0, 51);
  1783. this.layoutControlItem2.MinSize = new System.Drawing.Size(54, 51);
  1784. this.layoutControlItem2.Name = "layoutControlItem2";
  1785. this.layoutControlItem2.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  1786. this.layoutControlItem2.Size = new System.Drawing.Size(252, 51);
  1787. this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1788. this.layoutControlItem2.Text = "纬度";
  1789. this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Top;
  1790. this.layoutControlItem2.TextSize = new System.Drawing.Size(24, 14);
  1791. //
  1792. // layoutControlItem5
  1793. //
  1794. this.layoutControlItem5.Control = this.txtCaption;
  1795. this.layoutControlItem5.Location = new System.Drawing.Point(0, 0);
  1796. this.layoutControlItem5.MaxSize = new System.Drawing.Size(0, 43);
  1797. this.layoutControlItem5.MinSize = new System.Drawing.Size(54, 43);
  1798. this.layoutControlItem5.Name = "layoutControlItem5";
  1799. this.layoutControlItem5.Size = new System.Drawing.Size(252, 43);
  1800. this.layoutControlItem5.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1801. this.layoutControlItem5.Text = "标题";
  1802. this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Top;
  1803. this.layoutControlItem5.TextSize = new System.Drawing.Size(24, 14);
  1804. //
  1805. // btnOk
  1806. //
  1807. this.btnOk.Location = new System.Drawing.Point(125, 174);
  1808. this.btnOk.Name = "btnOk";
  1809. this.btnOk.Size = new System.Drawing.Size(65, 22);
  1810. this.btnOk.StyleController = this.layoutControl1;
  1811. this.btnOk.TabIndex = 10;
  1812. this.btnOk.Text = "确定";
  1813. this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
  1814. //
  1815. // layoutControlItem3
  1816. //
  1817. this.layoutControlItem3.Control = this.btnOk;
  1818. this.layoutControlItem3.Location = new System.Drawing.Point(113, 162);
  1819. this.layoutControlItem3.MaxSize = new System.Drawing.Size(69, 26);
  1820. this.layoutControlItem3.MinSize = new System.Drawing.Size(69, 26);
  1821. this.layoutControlItem3.Name = "layoutControlItem3";
  1822. this.layoutControlItem3.Size = new System.Drawing.Size(69, 26);
  1823. this.layoutControlItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1824. this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
  1825. this.layoutControlItem3.TextVisible = false;
  1826. //
  1827. // btnCancel
  1828. //
  1829. this.btnCancel.Location = new System.Drawing.Point(194, 174);
  1830. this.btnCancel.Name = "btnCancel";
  1831. this.btnCancel.Size = new System.Drawing.Size(66, 22);
  1832. this.btnCancel.StyleController = this.layoutControl1;
  1833. this.btnCancel.TabIndex = 11;
  1834. this.btnCancel.Text = "取消";
  1835. this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
  1836. //
  1837. // layoutControlItem6
  1838. //
  1839. this.layoutControlItem6.Control = this.btnCancel;
  1840. this.layoutControlItem6.Location = new System.Drawing.Point(182, 162);
  1841. this.layoutControlItem6.MaxSize = new System.Drawing.Size(70, 26);
  1842. this.layoutControlItem6.MinSize = new System.Drawing.Size(70, 26);
  1843. this.layoutControlItem6.Name = "layoutControlItem6";
  1844. this.layoutControlItem6.Size = new System.Drawing.Size(70, 26);
  1845. this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1846. this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
  1847. this.layoutControlItem6.TextVisible = false;
  1848. //
  1849. // dxErrorProvider1
  1850. //
  1851. this.dxErrorProvider1.ContainerControl = this;
  1852. //
  1853. // emptySpaceItem2
  1854. //
  1855. this.emptySpaceItem2.AllowHotTrack = false;
  1856. this.emptySpaceItem2.Location = new System.Drawing.Point(0, 145);
  1857. this.emptySpaceItem2.MinSize = new System.Drawing.Size(104, 1);
  1858. this.emptySpaceItem2.Name = "emptySpaceItem2";
  1859. this.emptySpaceItem2.Size = new System.Drawing.Size(252, 17);
  1860. this.emptySpaceItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1861. this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
  1862. //
  1863. // MapEditPointView
  1864. //
  1865. this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
  1866. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  1867. this.ClientSize = new System.Drawing.Size(272, 208);
  1868. this.Controls.Add(this.layoutControl1);
  1869. this.IconOptions.ShowIcon = false;
  1870. this.MaximizeBox = false;
  1871. this.MinimizeBox = false;
  1872. this.Name = "MapEditPointView";
  1873. this.ShowInTaskbar = false;
  1874. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
  1875. this.Text = "标点";
  1876. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
  1877. this.layoutControl1.ResumeLayout(false);
  1878. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).EndInit();
  1879. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).EndInit();
  1880. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).EndInit();
  1881. ((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit();
  1882. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
  1883. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
  1884. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
  1885. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
  1886. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
  1887. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
  1888. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).EndInit();
  1889. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit();
  1890. this.ResumeLayout(false);
  1891. }
  1892. protected override void Dispose(bool disposing)
  1893. {
  1894. if (disposing && (components != null))
  1895. {
  1896. components.Dispose();
  1897. }
  1898. base.Dispose(disposing);
  1899. }
  1900. public MapEditPointView()
  1901. {
  1902. InitializeComponent();
  1903. }
  1904. public string Caption
  1905. {
  1906. get
  1907. {
  1908. return txtCaption.Text.Trim();
  1909. }
  1910. set
  1911. {
  1912. txtCaption.Text = value;
  1913. }
  1914. }
  1915. public double Lon
  1916. {
  1917. get
  1918. {
  1919. return double.Parse(txtLon.Text.Trim());
  1920. }
  1921. set
  1922. {
  1923. txtLon.Text = value.ToString();
  1924. }
  1925. }
  1926. public double Lat
  1927. {
  1928. get
  1929. {
  1930. return double.Parse(txtLat.Text.Trim());
  1931. }
  1932. set
  1933. {
  1934. txtLat.Text = value.ToString();
  1935. }
  1936. }
  1937. private void btnOk_Click(object sender, EventArgs e)
  1938. {
  1939. dxErrorProvider1.ClearErrors();
  1940. double lon, lat;
  1941. if (!double.TryParse(txtLon.Text, out lon))
  1942. {
  1943. dxErrorProvider1.SetError(txtLon, "请设置正确的经度");
  1944. return;
  1945. }
  1946. if (!double.TryParse(txtLat.Text, out lat))
  1947. {
  1948. dxErrorProvider1.SetError(txtLat, "请设置正确的纬度");
  1949. return;
  1950. }
  1951. if (lon < -180 || lon > 180)
  1952. {
  1953. dxErrorProvider1.SetError(txtLon, "经度范围[-180,180]");
  1954. return;
  1955. }
  1956. if (lat < -90 || lat > 90)
  1957. {
  1958. dxErrorProvider1.SetError(txtLat, "纬度范围[-90,90]");
  1959. return;
  1960. }
  1961. this.DialogResult = DialogResult.OK;
  1962. }
  1963. private void btnCancel_Click(object sender, EventArgs e)
  1964. {
  1965. this.DialogResult = DialogResult.Cancel;
  1966. }
  1967. }
  1968. #endregion
  1969. #region ImageLayer数据源接口实现(本地和Http接口)
  1970. class ImageTileSource : IImageTileSource
  1971. {
  1972. SQLiteConnection con;
  1973. public ImageTileSource()
  1974. {
  1975. var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
  1976. if (files.Length > 0)
  1977. {
  1978. try
  1979. {
  1980. conStr = string.Format(conStr, files[0]);
  1981. con = new SQLiteConnection(conStr);
  1982. con.Open();
  1983. }
  1984. catch
  1985. {
  1986. conStr = null;
  1987. Console.WriteLine("Data.gmdb文件读取出错!");
  1988. }
  1989. }
  1990. else
  1991. {
  1992. conStr = null;
  1993. }
  1994. }
  1995. public string Name => "GMap地图瓦片";
  1996. public bool CanDisposeSourceImage => true;
  1997. public Image GetImage(int x, int y, int level, Size size)
  1998. {
  1999. var data = QueryTile(x, y, level, 0);
  2000. if (data == null) return null;
  2001. return Image.FromStream(new MemoryStream(data));
  2002. }
  2003. 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})";
  2004. string conStr = "Data Source=\"{0}\";Page Size=32768";
  2005. byte[] QueryTile(int x, int y, int zoom, int type)
  2006. {
  2007. if (conStr == null) return null;
  2008. type = (int)mMapType;
  2009. if (type == 0) type = 1818940751;
  2010. using (DbCommand com = con.CreateCommand())
  2011. {
  2012. com.CommandText = string.Format(QuerySql, x, y, zoom, type);
  2013. using (DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
  2014. {
  2015. if (rd.Read())
  2016. {
  2017. long length = rd.GetBytes(0, 0, null, 0, 0);
  2018. byte[] tile = new byte[length];
  2019. rd.GetBytes(0, 0, tile, 0, tile.Length);
  2020. return tile;
  2021. }
  2022. }
  2023. }
  2024. return null;
  2025. }
  2026. }
  2027. class HttpMapDataProvider : MapDataProviderBase
  2028. {
  2029. public HttpMapDataProvider()
  2030. {
  2031. TileSource = new HttpTileSource(this);
  2032. }
  2033. public override MapSize GetMapSizeInPixels(double zoomLevel)
  2034. {
  2035. double imageSize;
  2036. imageSize = HttpTileSource.CalculateTotalImageSize(zoomLevel);
  2037. return new MapSize(imageSize, imageSize);
  2038. }
  2039. protected override Size BaseSizeInPixels
  2040. {
  2041. get { return new Size(Convert.ToInt32(HttpTileSource.tileSize * 2), Convert.ToInt32(HttpTileSource.tileSize * 2)); }
  2042. }
  2043. }
  2044. class HttpTileSource : MapTileSourceBase
  2045. {
  2046. public const int tileSize = 256;
  2047. public const int maxZoomLevel = 14;
  2048. public string HttpServerAddr { get; set; }
  2049. public GoogleMapType MapType { get; set; } = GoogleMapType.Normal;
  2050. internal static double CalculateTotalImageSize(double zoomLevel)
  2051. {
  2052. if (zoomLevel < 1.0)
  2053. return zoomLevel * tileSize * 2;
  2054. return Math.Pow(2.0, zoomLevel) * tileSize;
  2055. }
  2056. public HttpTileSource(ICacheOptionsProvider cacheOptionsProvider) :
  2057. base((int)CalculateTotalImageSize(maxZoomLevel), (int)CalculateTotalImageSize(maxZoomLevel), tileSize, tileSize, cacheOptionsProvider)
  2058. {
  2059. }
  2060. public override Uri GetTileByZoomLevel(int zoomLevel, int tilePositionX, int tilePositionY)
  2061. {
  2062. if (string.IsNullOrWhiteSpace(HttpServerAddr)) return null;
  2063. try
  2064. {
  2065. if (zoomLevel <= maxZoomLevel)
  2066. {
  2067. string imgUrl = $"{HttpServerAddr}/{(int)MapType}/{zoomLevel}/{tilePositionX}/{tilePositionY}";
  2068. //string imgUrl = string.Format("http://192.168.0.214:58089/{0}/{1}/{2}/{3}", (int)GoogleMapType.Normal, zoomLevel, tilePositionX, tilePositionY);
  2069. Uri u = new Uri(imgUrl);
  2070. return u;
  2071. }
  2072. return null;
  2073. }
  2074. catch
  2075. {
  2076. Console.WriteLine($"加载地图数据出错,无法连接到{HttpServerAddr}");
  2077. return null;
  2078. }
  2079. }
  2080. }
  2081. #endregion
  2082. //定位点聚合器
  2083. class PosClusterer : IClusterer
  2084. {
  2085. private MapControl ctrl;
  2086. private IMapDataAdapter owner;
  2087. private MapViewport preViewPoint;
  2088. private DebounceDispatcher dispatcher = new DebounceDispatcher();
  2089. public bool IsBusy { get; private set; }
  2090. public MapItemCollection Items { get; private set; }
  2091. public PosClusterer(MapControl ctrl)
  2092. {
  2093. this.ctrl = ctrl;
  2094. }
  2095. public void SetOwner(IMapDataAdapter owner)
  2096. {
  2097. this.owner = owner;
  2098. Items = new MapItemCollection(owner);
  2099. }
  2100. public void Clusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2101. {
  2102. IsBusy = true;
  2103. if (sourceChanged)
  2104. DoClusterize(sourceItems, viewport, sourceChanged);
  2105. else
  2106. dispatcher.Debounce(100, () => DoClusterize(sourceItems, viewport, sourceChanged));
  2107. }
  2108. private void DoClusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2109. {
  2110. if (preViewPoint == null)
  2111. {
  2112. preViewPoint = viewport;
  2113. return;
  2114. }
  2115. if (!sourceChanged && preViewPoint.ZoomLevel == viewport.ZoomLevel)//地图移动或者MapControl大小发生了改变时直接操作Items避免闪烁
  2116. {
  2117. preViewPoint = viewport;
  2118. }
  2119. else//地图进行了缩放
  2120. {
  2121. Items.Clear();
  2122. var cache = new Dictionary<int, List<MapItem>>();
  2123. foreach (MapDot item in sourceItems)
  2124. {
  2125. var point = ctrl.CoordPointToScreenPoint(item.Location);
  2126. int pointX = (int)point.X;
  2127. int pointY = (int)point.Y;
  2128. bool visible = true;
  2129. if (pointX <= _dotSize || pointX > ctrl.Width - _dotSize)
  2130. visible = false;
  2131. else if (pointY <= _dotSize || pointY > ctrl.Height - _dotSize)
  2132. visible = false;
  2133. pointX /= (_dotSize * 2);
  2134. pointY /= (_dotSize * 2);
  2135. var key = pointX << 16 | pointY;
  2136. if (!visible)
  2137. key = -key;
  2138. if (!cache.ContainsKey(key))
  2139. cache.Add(key, new List<MapItem>());
  2140. cache[key].Add(item);
  2141. }
  2142. var innerData = ctrl.Tag as InnerData;
  2143. innerData._clusterCache.Clear();
  2144. LinkedList<MapItem> temp = new LinkedList<MapItem>();
  2145. foreach (var kv in cache)
  2146. {
  2147. var firstDot = kv.Value[0] as MapDot;
  2148. var firstObj = firstDot.Tag as PosData;
  2149. firstDot.Size = kv.Value.Count > 1 ? _dotSize + 2 : _dotSize;
  2150. firstObj.ClusterCount = kv.Value.Count;
  2151. firstObj.ClusterKey = kv.Key;
  2152. innerData._clusterCache.Add(kv.Key, firstDot);
  2153. temp.AddLast(firstDot);
  2154. }
  2155. Items.AddRange(temp);
  2156. cache.Clear();
  2157. preViewPoint = viewport;
  2158. owner.OnClustered();
  2159. }
  2160. this.IsBusy = false;
  2161. }
  2162. //计算多个坐标的中心位置
  2163. public GeoPoint GetCenterPointFromListOfCoordinates(List<MapItem> geoCoordinateList)
  2164. {
  2165. int total = geoCoordinateList.Count;
  2166. double lat = 0, lon = 0;
  2167. foreach (MapDot g in geoCoordinateList)
  2168. {
  2169. lat += (g.Location as GeoPoint).Latitude * Math.PI / 180;
  2170. lon += (g.Location as GeoPoint).Longitude * Math.PI / 180;
  2171. }
  2172. lat /= total;
  2173. lon /= total;
  2174. return new GeoPoint(lat * 180 / Math.PI, lon * 180 / Math.PI);
  2175. }
  2176. }
  2177. }