MapControlEx.cs 105 KB

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