MapControlEx.cs 105 KB

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