MapControlEx.cs 105 KB

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