MapControlEx.cs 110 KB

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