MapControlEx.cs 122 KB

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