MapControlEx.cs 107 KB

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