MapControlEx.cs 109 KB

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