MapControlEx.cs 105 KB

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