MapControlEx.cs 111 KB

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