MapControlEx.cs 105 KB

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