MapControlEx.cs 106 KB

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