MapControlEx.cs 128 KB

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