MapControlEx.cs 106 KB

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