MapControlEx.cs 106 KB

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