MapControlEx.cs 110 KB

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