MapControlEx.cs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  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, bool isClear = true)
  1351. {
  1352. if (dots == null || !dots.Any()) return;
  1353. string identify = "DrawGdopLine_";
  1354. var innerData = ctrl.Tag as InnerData;
  1355. if (isClear)
  1356. {
  1357. var mapItem = innerData.mMapStorage.Items.Find(m => m.Tag.ToString().StartsWith(identify));
  1358. if (mapItem != null)
  1359. {
  1360. innerData.mMapStorage.Items.Remove(mapItem);
  1361. }
  1362. }
  1363. //多条线 两个点绘制一个线段 1和2一个线段 3和4一个线段
  1364. List<MapPolyline> polylines = new List<MapPolyline>();
  1365. int index = 0;
  1366. int count = dots.Count();
  1367. MapPolyline polyLine = null;
  1368. foreach (var item in dots)
  1369. {
  1370. if (index % 2 == 0)
  1371. {
  1372. if (polyLine != null)//添加线段
  1373. {
  1374. polylines.Add(polyLine);
  1375. }
  1376. polyLine = new MapPolyline()
  1377. {
  1378. Stroke = ColorHelper.GetColor(wcKm),
  1379. StrokeWidth = 2,
  1380. IsGeodesic = true,
  1381. CanResize = false,
  1382. CanEdit = false,
  1383. CanRotate = false,
  1384. IsHitTestVisible = true,
  1385. CanMove = false,
  1386. Tag = $"{identify}{wcKm}",
  1387. };
  1388. }
  1389. polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
  1390. if (patterncount == index)//提示公里信息
  1391. {
  1392. polyLine.TitleOptions.Pattern = wcKm;
  1393. }
  1394. index++;
  1395. if (index == count)//添加最后一个线段
  1396. {
  1397. polylines.Add(polyLine);
  1398. }
  1399. }
  1400. if (!polyLine.Points.Any()) return;
  1401. innerData.mMapStorage.Items.AddRange(polylines);
  1402. }
  1403. /// <summary>
  1404. /// 绘制半径圆
  1405. /// </summary>
  1406. /// <param name="ctrl"></param>
  1407. /// <param name="lat"></param>
  1408. /// <param name="lon"></param>
  1409. /// <param name="radius"></param>
  1410. public static void DrawRadiusRound(this MapControl ctrl, double lat, double lon, int radius)
  1411. {
  1412. var innerData = ctrl.Tag as InnerData;
  1413. try
  1414. {
  1415. if (radius <= 0)
  1416. return;
  1417. CoordPointCollection latLngs = new CoordPointCollection();
  1418. MyLatLng centerLatLng = new MyLatLng(lon, lat);
  1419. // 0 - 360度 寻找半径为radius,圆心为centerP的圆上点的经纬度
  1420. for (int i = 0; i < 360; i++)
  1421. {
  1422. //获取目标经纬度
  1423. MyLatLng tempLatLng = getMyLatLng(centerLatLng, radius, i);
  1424. //将自定义的经纬度类 转换成 标准经纬度类
  1425. CoordPoint p = new GeoPoint(tempLatLng.m_Latitude, tempLatLng.m_Longitude);
  1426. latLngs.Add(p);
  1427. }
  1428. //安全性检查
  1429. if (latLngs.Count < 20)
  1430. {
  1431. return;
  1432. }
  1433. //通过绘制多边形的方式绘制圆
  1434. MapPolygon gpol = new MapPolygon();
  1435. gpol.Points = latLngs;
  1436. gpol.Stroke = Color.Red;
  1437. gpol.Fill = Color.FromArgb(50, Color.Red);
  1438. gpol.IsHitTestVisible = true;
  1439. innerData.mMapStorageFixed.Items.Add(gpol);
  1440. }
  1441. catch (Exception ex)
  1442. {
  1443. //Dialog.Error(ex);
  1444. }
  1445. }
  1446. /// <summary>
  1447. /// 度 转换成 弧度
  1448. /// </summary>
  1449. /// <param name="degrees"></param>
  1450. /// <returns></returns>
  1451. public static double DegreesToRadians(double degrees)
  1452. {
  1453. const double degToRadFactor = Math.PI / 180;
  1454. return degrees * degToRadFactor;
  1455. }
  1456. /// <summary>
  1457. /// 计算两个点之间的距离
  1458. /// </summary>
  1459. /// <param name="startlon">开始经度</param>
  1460. /// <param name="startlat">开始纬度</param>
  1461. /// <param name="endlon">结束经度</param>
  1462. /// <param name="endlat">结束纬度</param>
  1463. /// <returns></returns>
  1464. public static double CalcLineKm(double startlon, double startlat, double endlon, double endlat)
  1465. {
  1466. GeoPoint startPoint = new GeoPoint() { Longitude = startlon, Latitude = startlat };
  1467. GeoPoint endPoint = new GeoPoint() { Longitude = endlon, Latitude = endlat };
  1468. double result = 0;
  1469. MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
  1470. result = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
  1471. return result;
  1472. }
  1473. /// <summary>
  1474. /// 计算方向线坐标
  1475. /// </summary>
  1476. /// <param name="lon">经度</param>
  1477. /// <param name="lat">纬度</param>
  1478. /// <param name="deg"> 艏向角 角度制</param>
  1479. /// <param name="dis">长度 m</param>
  1480. /// <returns></returns>
  1481. public static (double, double) CalcSituation(double lon, double lat, double deg, double dis)
  1482. {
  1483. double arc = 6371.393 * 1000; //地球平均半径
  1484. double rad = deg * (Math.PI / 180); //角度转弧度
  1485. double c_lng = lon + dis * Math.Sin(rad) / (arc * Math.Cos(lat) * 2 * Math.PI / 360);
  1486. double c_lat = lat + dis * Math.Cos(rad) / (arc * 2 * Math.PI / 360);
  1487. return (c_lng, c_lat); //方向上的另一点坐标
  1488. }
  1489. /**
  1490. * 求B点经纬度
  1491. * @param A 已知点的经纬度,
  1492. * @param distance AB两地的距离 单位km
  1493. * @param angle AB连线与正北方向的夹角(0~360)
  1494. * @return B点的经纬度
  1495. */
  1496. private static MyLatLng getMyLatLng(MyLatLng A, double distance, double angle)
  1497. {
  1498. double dx = distance * 1000 * Math.Sin(DegreesToRadians(angle));
  1499. double dy = distance * 1000 * Math.Cos(DegreesToRadians(angle));
  1500. double bjd = (dx / A.Ed + A.m_RadLo) * 180 / Math.PI;
  1501. double bwd = (dy / A.Ec + A.m_RadLa) * 180 / Math.PI;
  1502. return new MyLatLng(bjd, bwd);
  1503. }
  1504. public static void ClearRect(this MapControl ctrl)
  1505. {
  1506. var innerDate = ctrl.Tag as InnerData;
  1507. if (innerDate.rangeItem != null)
  1508. innerDate.mMapStorage.Items.Remove(innerDate.rangeItem);
  1509. if (innerDate.dotItem != null)
  1510. innerDate.mMapStorage.Items.Remove(innerDate.dotItem);
  1511. }
  1512. /// <summary>
  1513. /// 获取地图框选的范围信息(可能为null)
  1514. /// </summary>
  1515. /// <param name="ctrl"></param>
  1516. /// <returns></returns>
  1517. public static (double starLon, double startLat, double centerLon, double centerLat,
  1518. double endLon, double endLat, double lonRange, double latRange) GetCurrentRect(this MapControl ctrl)
  1519. {
  1520. var innerData = ctrl.Tag as InnerData;
  1521. return innerData.CurrentRect;
  1522. }
  1523. /// <summary>
  1524. /// 获取地图瓦片图层
  1525. /// </summary>
  1526. /// <param name="ctrl"></param>
  1527. /// <returns></returns>
  1528. public static ImageLayer GetImageLayer(this MapControl ctrl)
  1529. {
  1530. if (ctrl.Layers == null) return null;
  1531. return (ImageLayer)ctrl.Layers["ImageTileLayer"];
  1532. }
  1533. /// <summary>
  1534. /// 获取地图绘制图层
  1535. /// </summary>
  1536. /// <param name="ctrl"></param>
  1537. /// <returns></returns>
  1538. public static VectorItemsLayer GetDrawLayer(this MapControl ctrl)
  1539. {
  1540. return (VectorItemsLayer)ctrl.Layers["DrawLayer"];
  1541. }
  1542. /// <summary>
  1543. /// 获取地图绘制图层
  1544. /// </summary>
  1545. /// <param name="ctrl"></param>
  1546. /// <returns></returns>
  1547. public static VectorItemsLayer GetPosLayer(this MapControl ctrl)
  1548. {
  1549. return (VectorItemsLayer)ctrl.Layers["PosLayer"];
  1550. }
  1551. /// <summary>
  1552. /// 获取地图绘制图层的数据仓库
  1553. /// </summary>
  1554. /// <param name="ctrl"></param>
  1555. /// <returns></returns>
  1556. public static MapItemStorage GetDrawStorage(this MapControl ctrl)
  1557. {
  1558. var innerData = ctrl.Tag as InnerData;
  1559. return innerData.mMapStorage;
  1560. }
  1561. /// <summary>
  1562. /// 设置地图类型.默认为Normal
  1563. /// 该方法为所有MapControl实例设置地图类型
  1564. /// </summary>
  1565. /// <param name="ctrl"></param>
  1566. /// <param name="mapType"></param>
  1567. public static void SetMapType(GoogleMapType mapType)
  1568. {
  1569. mMapType = mapType;
  1570. listMapCtrl.ForEach(t =>
  1571. {
  1572. if (t.GetImageLayer() == null) return;
  1573. var provider = t.GetImageLayer().DataProvider as MapTileDataProviderBase;
  1574. provider?.ClearCache();
  1575. t.Refresh();
  1576. });
  1577. }
  1578. #region private
  1579. private static void DrawRect_MouseMove(object sender, MouseEventArgs e)
  1580. {
  1581. var innerData = (sender as MapControl).Tag as InnerData;
  1582. if (!innerData.drawingRect) return;
  1583. innerData.dotItem.Location = innerData.rangeItem.GetCenter();
  1584. var startLon = Math.Round(innerData.rangeItem.Location.GetX(), 3);
  1585. var startLat = Math.Round(innerData.rangeItem.Location.GetY(), 3);
  1586. if (startLon >= 180)
  1587. {
  1588. startLon -= 360;
  1589. }
  1590. if (startLon <= -180)
  1591. {
  1592. startLon += 360;
  1593. }
  1594. var center = innerData.rangeItem.GetCenter();
  1595. var centerLon = Math.Round(center.GetX(), 3);
  1596. if (centerLon >= 180)
  1597. {
  1598. centerLon -= 360;
  1599. }
  1600. if (centerLon <= -180)
  1601. {
  1602. centerLon += 360;
  1603. }
  1604. var centerLat = Math.Round(center.GetY(), 3);
  1605. double endLon;
  1606. if (centerLon < 0 && startLon > 0)
  1607. endLon = startLon + 2 * (centerLon + 360 - startLon);
  1608. else
  1609. endLon = startLon + 2 * (centerLon - startLon);
  1610. var endLat = startLat + 2 * (centerLat - startLat);
  1611. var StartLon = Math.Min(startLon, endLon);
  1612. var StartLat = Math.Min(startLat, endLat);
  1613. var CenterLon = centerLon;
  1614. var CenterLat = centerLat;
  1615. var EndLon = Math.Max(startLon, endLon);
  1616. var EndLat = Math.Max(startLat, endLat);
  1617. double centerLonNew = CenterLon % 360;
  1618. CenterLon = centerLonNew;
  1619. //double LonRange = Math.Round((EndLon - StartLon) / 2, 3);
  1620. //double LatRange = Math.Round((EndLat - StartLat) / 2, 3);
  1621. double LonRange = Math.Round((EndLon - StartLon), 3);
  1622. double LatRange = Math.Round((EndLat - StartLat), 3);
  1623. if (LonRange >= 360)
  1624. {
  1625. }
  1626. innerData.CurrentRect = (StartLon, StartLat, CenterLon, CenterLat, EndLon, EndLat, LonRange, LatRange);
  1627. innerData.mOnRectChanged?.Invoke(innerData.CurrentRect);
  1628. }
  1629. private static void ExportImg_ItemClick(object sender, ItemClickEventArgs e)
  1630. {
  1631. var ctrl = e.Item.Tag as MapControl;
  1632. using (var dialog = new SaveFileDialog())
  1633. {
  1634. dialog.Filter = "PNG图片|*.png";
  1635. dialog.AddExtension = true;
  1636. dialog.FileName = $"Map{DateTime.Now:yyyyMMddHHmmss}.png";
  1637. if (dialog.ShowDialog() == DialogResult.OK)
  1638. {
  1639. ctrl.ExportToImage(dialog.FileName, ImageFormat.Png);
  1640. }
  1641. }
  1642. }
  1643. private static void ExportCsv_ItemClick(object sender, ItemClickEventArgs e)
  1644. {
  1645. var ctrl = e.Item.Tag as MapControl;
  1646. using (var dialog = new SaveFileDialog())
  1647. {
  1648. dialog.Filter = "CSV文件|*.csv";
  1649. dialog.AddExtension = true;
  1650. dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
  1651. if (dialog.ShowDialog() == DialogResult.OK)
  1652. {
  1653. ctrl.ExportToXlsx(dialog.FileName);
  1654. }
  1655. }
  1656. }
  1657. private static void ClearDrawObj(this MapControl ctrl)
  1658. {
  1659. ctrl.Invoke(new Action(() =>
  1660. {
  1661. try
  1662. {
  1663. var innerData = ctrl.Tag as InnerData;
  1664. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1665. innerData.drawingRect = false;
  1666. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1667. innerData.rangeItem = null;
  1668. if (innerData.mMapStorage != null && innerData.mMapStorage.Items.Any())
  1669. {
  1670. innerData.mMapStorage.Items.Clear();
  1671. }
  1672. }
  1673. catch (Exception ex)
  1674. {
  1675. }
  1676. }));
  1677. }
  1678. private static void DistanceLine_ItemClick(object sender, ItemClickEventArgs e)
  1679. {
  1680. var ctrl = e.Item.Tag as MapControl;
  1681. var innerData = ctrl.Tag as InnerData;
  1682. ctrl.MapEditor.SetEditMode();
  1683. var items = innerData.mMapStorage.Items.ToArray();
  1684. foreach (var item in items)
  1685. {
  1686. if (item.Tag != null && item.Tag.ToString() == "DrawDistanceLine")
  1687. innerData.mMapStorage.Items.Remove(item);
  1688. }
  1689. if (innerData.distinctPath != null)
  1690. {
  1691. innerData.distinctPath.Points.Clear();
  1692. }
  1693. innerData.distinctPath = new MapPolyline()
  1694. {
  1695. Stroke = Color.FromArgb(127, 255, 0, 199),
  1696. StrokeWidth = 2,
  1697. IsGeodesic = true,
  1698. CanResize = false,
  1699. CanEdit = false,
  1700. CanRotate = false,
  1701. IsHitTestVisible = false,
  1702. CanMove = true,
  1703. Tag = "DrawDistanceLine"
  1704. };
  1705. innerData.mMapStorage.Items.Add(innerData.distinctPath);
  1706. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1707. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1708. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1709. innerData.hoverTip = CreateHoverTip();
  1710. ctrl.MouseClick += AddDistinctPoint;
  1711. ctrl.MouseMove += MovingDistinct;
  1712. ctrl.MouseLeave += MapControl_MouseLeave;
  1713. ctrl.MouseEnter += MapControl_MouseEnter;
  1714. ctrl.DoubleClick += EndDistinct;
  1715. }
  1716. private static void MarkDot_ItemClick(object sender, ItemClickEventArgs e)
  1717. {
  1718. var ctrl = e.Item.Tag as MapControl;
  1719. ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
  1720. var innerData = ctrl.Tag as InnerData;
  1721. innerData.drawingRect = false;
  1722. using (var frm = new MapEditPointView())
  1723. {
  1724. if (frm.ShowDialog() != DialogResult.OK) return;
  1725. var locPoint = new GeoPoint(frm.Lat, frm.Lon);
  1726. MapCustomElement cusItem = new MapCustomElement()
  1727. {
  1728. Location = locPoint,
  1729. UseAnimation = true,
  1730. CanMove = false,
  1731. EnableHighlighting = DefaultBoolean.True,
  1732. EnableSelection = DefaultBoolean.False,
  1733. Text = "",
  1734. ToolTipPattern = $"{frm.Caption}",
  1735. SvgImage = SvgHelper.CreatePentagram(),
  1736. SvgImageSize = new Size(32, 32),
  1737. TextAlignment = DevExpress.XtraMap.TextAlignment.BottomCenter,
  1738. Tag = "DrawMarkDot"
  1739. };
  1740. innerData.mMapStorage.Items.Add(cusItem);
  1741. }
  1742. }
  1743. private static ToolTipControllerShowEventArgs CreateHoverTip()
  1744. {
  1745. ToolTipTitleItem titleItem1 = new ToolTipTitleItem() { Text = $"0千米" };
  1746. titleItem1.Appearance.ForeColor = SystemColors.GrayText;
  1747. titleItem1.Appearance.Font = new Font(AppearanceObject.DefaultFont.FontFamily, 12, FontStyle.Bold);
  1748. SuperToolTip superToolTip = new SuperToolTip();
  1749. superToolTip.Items.Add(titleItem1);
  1750. ToolTipSeparatorItem sepItem = new ToolTipSeparatorItem();
  1751. superToolTip.Items.Add(sepItem);
  1752. ToolTipItem textItem = new ToolTipItem() { Text = "单击添加测距点,双击结束测距" };
  1753. superToolTip.Items.Add(textItem);
  1754. ToolTipControllerShowEventArgs arg = new ToolTipControllerShowEventArgs();
  1755. arg.ShowBeak = true;
  1756. arg.SuperTip = superToolTip;
  1757. return arg;
  1758. }
  1759. private static void MapControl_MouseEnter(object sender, EventArgs e)
  1760. {
  1761. var innerData = (sender as MapControl).Tag as InnerData;
  1762. innerData.hoverPoint.Visible = true;
  1763. }
  1764. private static void MapControl_MouseLeave(object sender, EventArgs e)
  1765. {
  1766. var innerData = (sender as MapControl).Tag as InnerData;
  1767. innerData.hoverPoint.Visible = false;
  1768. }
  1769. private static void AddDistinctPoint(object sender, MouseEventArgs e)
  1770. {
  1771. var innerData = (sender as MapControl).Tag as InnerData;
  1772. var ctrl = sender as MapControl;
  1773. MapCallout disItem = new MapCallout { IsHitTestVisible = false, CanMove = false };
  1774. disItem.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1775. disItem.Text = $"{CalcLineKm(innerData):F2}千米";
  1776. disItem.Tag = "DrawDistanceLine";
  1777. innerData.mMapStorage.Items.Add(disItem);
  1778. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1779. innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
  1780. innerData.hoverPoint.Location = ctrl.ScreenPointToCoordPoint(e.Location);
  1781. innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
  1782. innerData.mMapStorage.Items.Add(innerData.hoverPoint);
  1783. innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
  1784. }
  1785. private static void MovingDistinct(object sender, MouseEventArgs e)
  1786. {
  1787. var innerData = (sender as MapControl).Tag as InnerData;
  1788. var ctrl = sender as MapControl;
  1789. var itemPoint = ctrl.ScreenPointToCoordPoint(e.Location);
  1790. innerData.hoverPoint.Location = itemPoint;
  1791. if (innerData.distinctPath.Points.Count > 0)
  1792. {
  1793. ctrl.MapEditor.SetEditMode();
  1794. innerData.distinctPath.Points[innerData.distinctPath.Points.Count - 1] = itemPoint;
  1795. (innerData.hoverTip.SuperTip.Items[0] as ToolTipTitleItem).Text = $"{CalcLineKm(innerData):F2}千米";
  1796. innerData.mapToolTip.ShowHint(innerData.hoverTip, ctrl.PointToScreen(e.Location));
  1797. }
  1798. }
  1799. private static double CalcLineKm(InnerData data)
  1800. {
  1801. double result = 0;
  1802. if (data.distinctPath.Points.Count < 2) return result;
  1803. for (int i = 0; i < data.distinctPath.Points.Count - 1; i++)
  1804. {
  1805. var startPoint = data.distinctPath.Points[i] as GeoPoint;
  1806. var endPoint = data.distinctPath.Points[i + 1] as GeoPoint;
  1807. MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
  1808. double partlength = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
  1809. result += partlength;
  1810. }
  1811. return result;
  1812. }
  1813. public static void ClearMap(this MapControl ctrl)
  1814. {
  1815. var innerData = ctrl.Tag as InnerData;
  1816. innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
  1817. innerData.mMapStorage?.Items.Clear();
  1818. }
  1819. private static void EndDistinct(object sender, EventArgs e)
  1820. {
  1821. var ctrl = sender as MapControl;
  1822. var innerData = ctrl.Tag as InnerData;
  1823. innerData.mapToolTip.HideHint();
  1824. ctrl.MouseClick -= AddDistinctPoint;
  1825. ctrl.MouseMove -= MovingDistinct;
  1826. ctrl.DoubleClick -= EndDistinct;
  1827. ctrl.MouseLeave -= MapControl_MouseLeave;
  1828. ctrl.MouseEnter -= MapControl_MouseEnter;
  1829. }
  1830. class MapEditPointView : DevExpress.XtraEditors.XtraForm
  1831. {
  1832. private System.ComponentModel.IContainer components = null;
  1833. private DevExpress.XtraLayout.LayoutControl layoutControl1;
  1834. private DevExpress.XtraLayout.LayoutControlGroup Root;
  1835. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
  1836. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
  1837. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
  1838. private DevExpress.XtraEditors.ButtonEdit txtLon;
  1839. private DevExpress.XtraEditors.ButtonEdit txtLat;
  1840. private DevExpress.XtraEditors.TextEdit txtCaption;
  1841. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
  1842. private DevExpress.XtraEditors.SimpleButton btnCancel;
  1843. private DevExpress.XtraEditors.SimpleButton btnOk;
  1844. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
  1845. private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
  1846. private DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider dxErrorProvider1;
  1847. private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
  1848. private void InitializeComponent()
  1849. {
  1850. this.components = new System.ComponentModel.Container();
  1851. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions1 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1852. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject1 = new DevExpress.Utils.SerializableAppearanceObject();
  1853. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject2 = new DevExpress.Utils.SerializableAppearanceObject();
  1854. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject3 = new DevExpress.Utils.SerializableAppearanceObject();
  1855. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject4 = new DevExpress.Utils.SerializableAppearanceObject();
  1856. DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions2 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
  1857. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject5 = new DevExpress.Utils.SerializableAppearanceObject();
  1858. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject6 = new DevExpress.Utils.SerializableAppearanceObject();
  1859. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject7 = new DevExpress.Utils.SerializableAppearanceObject();
  1860. DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject8 = new DevExpress.Utils.SerializableAppearanceObject();
  1861. this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
  1862. this.txtCaption = new DevExpress.XtraEditors.TextEdit();
  1863. this.txtLon = new DevExpress.XtraEditors.ButtonEdit();
  1864. this.txtLat = new DevExpress.XtraEditors.ButtonEdit();
  1865. this.Root = new DevExpress.XtraLayout.LayoutControlGroup();
  1866. this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
  1867. this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
  1868. this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
  1869. this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
  1870. this.btnOk = new DevExpress.XtraEditors.SimpleButton();
  1871. this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
  1872. this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
  1873. this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
  1874. this.dxErrorProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(this.components);
  1875. this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem();
  1876. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
  1877. this.layoutControl1.SuspendLayout();
  1878. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).BeginInit();
  1879. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).BeginInit();
  1880. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).BeginInit();
  1881. ((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit();
  1882. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
  1883. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
  1884. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
  1885. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
  1886. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
  1887. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
  1888. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).BeginInit();
  1889. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit();
  1890. this.SuspendLayout();
  1891. //
  1892. // layoutControl1
  1893. //
  1894. this.layoutControl1.Controls.Add(this.btnCancel);
  1895. this.layoutControl1.Controls.Add(this.btnOk);
  1896. this.layoutControl1.Controls.Add(this.txtCaption);
  1897. this.layoutControl1.Controls.Add(this.txtLon);
  1898. this.layoutControl1.Controls.Add(this.txtLat);
  1899. this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
  1900. this.layoutControl1.Location = new System.Drawing.Point(0, 0);
  1901. this.layoutControl1.Name = "layoutControl1";
  1902. this.layoutControl1.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(689, 0, 650, 400);
  1903. this.layoutControl1.Root = this.Root;
  1904. this.layoutControl1.Size = new System.Drawing.Size(272, 208);
  1905. this.layoutControl1.TabIndex = 0;
  1906. this.layoutControl1.Text = "layoutControl1";
  1907. //
  1908. // txtCaption
  1909. //
  1910. this.txtCaption.Location = new System.Drawing.Point(12, 29);
  1911. this.txtCaption.Name = "txtCaption";
  1912. this.txtCaption.Properties.Appearance.Options.UseTextOptions = true;
  1913. this.txtCaption.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1914. this.txtCaption.Properties.AutoHeight = false;
  1915. this.txtCaption.Properties.MaxLength = 30;
  1916. this.txtCaption.Size = new System.Drawing.Size(248, 22);
  1917. this.txtCaption.StyleController = this.layoutControl1;
  1918. this.txtCaption.TabIndex = 9;
  1919. //
  1920. // txtLon
  1921. //
  1922. this.txtLon.Location = new System.Drawing.Point(12, 80);
  1923. this.txtLon.Name = "txtLon";
  1924. this.txtLon.Properties.Appearance.Options.UseTextOptions = true;
  1925. this.txtLon.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1926. this.txtLon.Properties.AutoHeight = false;
  1927. this.txtLon.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1928. 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)});
  1929. this.txtLon.Size = new System.Drawing.Size(248, 22);
  1930. this.txtLon.StyleController = this.layoutControl1;
  1931. this.txtLon.TabIndex = 4;
  1932. //
  1933. // txtLat
  1934. //
  1935. this.txtLat.Location = new System.Drawing.Point(12, 131);
  1936. this.txtLat.Name = "txtLat";
  1937. this.txtLat.Properties.Appearance.Options.UseTextOptions = true;
  1938. this.txtLat.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
  1939. this.txtLat.Properties.AutoHeight = false;
  1940. this.txtLat.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
  1941. 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)});
  1942. this.txtLat.Size = new System.Drawing.Size(248, 22);
  1943. this.txtLat.StyleController = this.layoutControl1;
  1944. this.txtLat.TabIndex = 5;
  1945. //
  1946. // Root
  1947. //
  1948. this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
  1949. this.Root.GroupBordersVisible = false;
  1950. this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
  1951. this.layoutControlItem1,
  1952. this.emptySpaceItem1,
  1953. this.layoutControlItem5,
  1954. this.layoutControlItem2,
  1955. this.layoutControlItem3,
  1956. this.layoutControlItem6,
  1957. this.emptySpaceItem2});
  1958. this.Root.Name = "Root";
  1959. this.Root.Size = new System.Drawing.Size(272, 208);
  1960. this.Root.TextVisible = false;
  1961. //
  1962. // layoutControlItem1
  1963. //
  1964. this.layoutControlItem1.Control = this.txtLon;
  1965. this.layoutControlItem1.Location = new System.Drawing.Point(0, 43);
  1966. this.layoutControlItem1.MaxSize = new System.Drawing.Size(0, 51);
  1967. this.layoutControlItem1.MinSize = new System.Drawing.Size(54, 51);
  1968. this.layoutControlItem1.Name = "layoutControlItem1";
  1969. this.layoutControlItem1.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  1970. this.layoutControlItem1.Size = new System.Drawing.Size(252, 51);
  1971. this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1972. this.layoutControlItem1.Text = "经度";
  1973. this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Top;
  1974. this.layoutControlItem1.TextSize = new System.Drawing.Size(24, 14);
  1975. //
  1976. // emptySpaceItem1
  1977. //
  1978. this.emptySpaceItem1.AllowHotTrack = false;
  1979. this.emptySpaceItem1.Location = new System.Drawing.Point(0, 162);
  1980. this.emptySpaceItem1.MaxSize = new System.Drawing.Size(0, 26);
  1981. this.emptySpaceItem1.MinSize = new System.Drawing.Size(104, 26);
  1982. this.emptySpaceItem1.Name = "emptySpaceItem1";
  1983. this.emptySpaceItem1.Size = new System.Drawing.Size(113, 26);
  1984. this.emptySpaceItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1985. this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
  1986. //
  1987. // layoutControlItem2
  1988. //
  1989. this.layoutControlItem2.Control = this.txtLat;
  1990. this.layoutControlItem2.Location = new System.Drawing.Point(0, 94);
  1991. this.layoutControlItem2.MaxSize = new System.Drawing.Size(0, 51);
  1992. this.layoutControlItem2.MinSize = new System.Drawing.Size(54, 51);
  1993. this.layoutControlItem2.Name = "layoutControlItem2";
  1994. this.layoutControlItem2.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
  1995. this.layoutControlItem2.Size = new System.Drawing.Size(252, 51);
  1996. this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  1997. this.layoutControlItem2.Text = "纬度";
  1998. this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Top;
  1999. this.layoutControlItem2.TextSize = new System.Drawing.Size(24, 14);
  2000. //
  2001. // layoutControlItem5
  2002. //
  2003. this.layoutControlItem5.Control = this.txtCaption;
  2004. this.layoutControlItem5.Location = new System.Drawing.Point(0, 0);
  2005. this.layoutControlItem5.MaxSize = new System.Drawing.Size(0, 43);
  2006. this.layoutControlItem5.MinSize = new System.Drawing.Size(54, 43);
  2007. this.layoutControlItem5.Name = "layoutControlItem5";
  2008. this.layoutControlItem5.Size = new System.Drawing.Size(252, 43);
  2009. this.layoutControlItem5.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2010. this.layoutControlItem5.Text = "标题";
  2011. this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Top;
  2012. this.layoutControlItem5.TextSize = new System.Drawing.Size(24, 14);
  2013. //
  2014. // btnOk
  2015. //
  2016. this.btnOk.Location = new System.Drawing.Point(125, 174);
  2017. this.btnOk.Name = "btnOk";
  2018. this.btnOk.Size = new System.Drawing.Size(65, 22);
  2019. this.btnOk.StyleController = this.layoutControl1;
  2020. this.btnOk.TabIndex = 10;
  2021. this.btnOk.Text = "确定";
  2022. this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
  2023. //
  2024. // layoutControlItem3
  2025. //
  2026. this.layoutControlItem3.Control = this.btnOk;
  2027. this.layoutControlItem3.Location = new System.Drawing.Point(113, 162);
  2028. this.layoutControlItem3.MaxSize = new System.Drawing.Size(69, 26);
  2029. this.layoutControlItem3.MinSize = new System.Drawing.Size(69, 26);
  2030. this.layoutControlItem3.Name = "layoutControlItem3";
  2031. this.layoutControlItem3.Size = new System.Drawing.Size(69, 26);
  2032. this.layoutControlItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2033. this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
  2034. this.layoutControlItem3.TextVisible = false;
  2035. //
  2036. // btnCancel
  2037. //
  2038. this.btnCancel.Location = new System.Drawing.Point(194, 174);
  2039. this.btnCancel.Name = "btnCancel";
  2040. this.btnCancel.Size = new System.Drawing.Size(66, 22);
  2041. this.btnCancel.StyleController = this.layoutControl1;
  2042. this.btnCancel.TabIndex = 11;
  2043. this.btnCancel.Text = "取消";
  2044. this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
  2045. //
  2046. // layoutControlItem6
  2047. //
  2048. this.layoutControlItem6.Control = this.btnCancel;
  2049. this.layoutControlItem6.Location = new System.Drawing.Point(182, 162);
  2050. this.layoutControlItem6.MaxSize = new System.Drawing.Size(70, 26);
  2051. this.layoutControlItem6.MinSize = new System.Drawing.Size(70, 26);
  2052. this.layoutControlItem6.Name = "layoutControlItem6";
  2053. this.layoutControlItem6.Size = new System.Drawing.Size(70, 26);
  2054. this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2055. this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
  2056. this.layoutControlItem6.TextVisible = false;
  2057. //
  2058. // dxErrorProvider1
  2059. //
  2060. this.dxErrorProvider1.ContainerControl = this;
  2061. //
  2062. // emptySpaceItem2
  2063. //
  2064. this.emptySpaceItem2.AllowHotTrack = false;
  2065. this.emptySpaceItem2.Location = new System.Drawing.Point(0, 145);
  2066. this.emptySpaceItem2.MinSize = new System.Drawing.Size(104, 1);
  2067. this.emptySpaceItem2.Name = "emptySpaceItem2";
  2068. this.emptySpaceItem2.Size = new System.Drawing.Size(252, 17);
  2069. this.emptySpaceItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
  2070. this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
  2071. //
  2072. // MapEditPointView
  2073. //
  2074. this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
  2075. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  2076. this.ClientSize = new System.Drawing.Size(272, 208);
  2077. this.Controls.Add(this.layoutControl1);
  2078. this.IconOptions.ShowIcon = false;
  2079. this.MaximizeBox = false;
  2080. this.MinimizeBox = false;
  2081. this.Name = "MapEditPointView";
  2082. this.ShowInTaskbar = false;
  2083. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
  2084. this.Text = "标点";
  2085. ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
  2086. this.layoutControl1.ResumeLayout(false);
  2087. ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).EndInit();
  2088. ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).EndInit();
  2089. ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).EndInit();
  2090. ((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit();
  2091. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
  2092. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
  2093. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
  2094. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
  2095. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
  2096. ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
  2097. ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).EndInit();
  2098. ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit();
  2099. this.ResumeLayout(false);
  2100. }
  2101. protected override void Dispose(bool disposing)
  2102. {
  2103. if (disposing && (components != null))
  2104. {
  2105. components.Dispose();
  2106. }
  2107. base.Dispose(disposing);
  2108. }
  2109. public MapEditPointView()
  2110. {
  2111. InitializeComponent();
  2112. }
  2113. public string Caption
  2114. {
  2115. get
  2116. {
  2117. return txtCaption.Text.Trim();
  2118. }
  2119. set
  2120. {
  2121. txtCaption.Text = value;
  2122. }
  2123. }
  2124. public double Lon
  2125. {
  2126. get
  2127. {
  2128. return double.Parse(txtLon.Text.Trim());
  2129. }
  2130. set
  2131. {
  2132. txtLon.Text = value.ToString();
  2133. }
  2134. }
  2135. public double Lat
  2136. {
  2137. get
  2138. {
  2139. return double.Parse(txtLat.Text.Trim());
  2140. }
  2141. set
  2142. {
  2143. txtLat.Text = value.ToString();
  2144. }
  2145. }
  2146. private void btnOk_Click(object sender, EventArgs e)
  2147. {
  2148. dxErrorProvider1.ClearErrors();
  2149. double lon, lat;
  2150. if (!double.TryParse(txtLon.Text, out lon))
  2151. {
  2152. dxErrorProvider1.SetError(txtLon, "请设置正确的经度");
  2153. return;
  2154. }
  2155. if (!double.TryParse(txtLat.Text, out lat))
  2156. {
  2157. dxErrorProvider1.SetError(txtLat, "请设置正确的纬度");
  2158. return;
  2159. }
  2160. if (lon < -180 || lon > 180)
  2161. {
  2162. dxErrorProvider1.SetError(txtLon, "经度范围[-180,180]");
  2163. return;
  2164. }
  2165. if (lat < -90 || lat > 90)
  2166. {
  2167. dxErrorProvider1.SetError(txtLat, "纬度范围[-90,90]");
  2168. return;
  2169. }
  2170. this.DialogResult = DialogResult.OK;
  2171. }
  2172. private void btnCancel_Click(object sender, EventArgs e)
  2173. {
  2174. this.DialogResult = DialogResult.Cancel;
  2175. }
  2176. }
  2177. #endregion
  2178. #region 半径圆
  2179. public class MyLatLng
  2180. {
  2181. public double Rc = 6378137; //赤道半径
  2182. public double Rj = 6356725; //极半径
  2183. public double m_LoDeg, m_LoMin, m_LoSec;
  2184. public double m_LaDeg, m_LaMin, m_LaSec;
  2185. public double m_Longitude, m_Latitude;
  2186. public double m_RadLo, m_RadLa;
  2187. public double Ec;
  2188. public double Ed;
  2189. public MyLatLng(double longitude, double latitude)
  2190. {
  2191. m_LoDeg = (int)longitude;
  2192. m_LoMin = (int)((longitude - m_LoDeg) * 60);
  2193. m_LoSec = (longitude - m_LoDeg - m_LoMin / 60) * 3600;
  2194. m_LaDeg = (int)latitude;
  2195. m_LaMin = (int)((latitude - m_LaDeg) * 60);
  2196. m_LaSec = (latitude - m_LaDeg - m_LaMin / 60) * 3600;
  2197. m_Longitude = longitude;
  2198. m_Latitude = latitude;
  2199. m_RadLo = longitude * Math.PI / 180;
  2200. m_RadLa = latitude * Math.PI / 180;
  2201. Ec = Rj + (Rc - Rj) * (90 - m_Latitude) / 90;
  2202. Ed = Ec * Math.Cos(m_RadLa);
  2203. }
  2204. }
  2205. #endregion
  2206. #region ImageLayer数据源接口实现(本地和Http接口)
  2207. class ImageTileSource : IImageTileSource
  2208. {
  2209. SQLiteConnection con;
  2210. public ImageTileSource()
  2211. {
  2212. var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
  2213. if (files.Length > 0)
  2214. {
  2215. try
  2216. {
  2217. conStr = string.Format(conStr, files[0]);
  2218. con = new SQLiteConnection(conStr);
  2219. con.Open();
  2220. }
  2221. catch
  2222. {
  2223. conStr = null;
  2224. Console.WriteLine("Data.gmdb文件读取出错!");
  2225. }
  2226. }
  2227. else
  2228. {
  2229. conStr = null;
  2230. }
  2231. }
  2232. public string Name => "GMap地图瓦片";
  2233. public bool CanDisposeSourceImage => true;
  2234. public Image GetImage(int x, int y, int level, Size size)
  2235. {
  2236. var data = QueryTile(x, y, level, 0);
  2237. if (data == null) return null;
  2238. return Image.FromStream(new MemoryStream(data));
  2239. }
  2240. 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})";
  2241. string conStr = "Data Source=\"{0}\";Page Size=32768";
  2242. byte[] QueryTile(int x, int y, int zoom, int type)
  2243. {
  2244. if (conStr == null) return null;
  2245. type = (int)mMapType;
  2246. if (type == 0) type = 1818940751;
  2247. using (DbCommand com = con.CreateCommand())
  2248. {
  2249. com.CommandText = string.Format(QuerySql, x, y, zoom, type);
  2250. using (DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
  2251. {
  2252. if (rd.Read())
  2253. {
  2254. long length = rd.GetBytes(0, 0, null, 0, 0);
  2255. byte[] tile = new byte[length];
  2256. rd.GetBytes(0, 0, tile, 0, tile.Length);
  2257. return tile;
  2258. }
  2259. }
  2260. }
  2261. return null;
  2262. }
  2263. }
  2264. class HttpMapDataProvider : MapDataProviderBase
  2265. {
  2266. public HttpMapDataProvider()
  2267. {
  2268. TileSource = new HttpTileSource(this);
  2269. }
  2270. public override MapSize GetMapSizeInPixels(double zoomLevel)
  2271. {
  2272. double imageSize;
  2273. imageSize = HttpTileSource.CalculateTotalImageSize(zoomLevel);
  2274. return new MapSize(imageSize, imageSize);
  2275. }
  2276. protected override Size BaseSizeInPixels
  2277. {
  2278. get { return new Size(Convert.ToInt32(HttpTileSource.tileSize * 2), Convert.ToInt32(HttpTileSource.tileSize * 2)); }
  2279. }
  2280. }
  2281. class HttpTileSource : MapTileSourceBase
  2282. {
  2283. public const int tileSize = 256;
  2284. public const int maxZoomLevel = 14;
  2285. public string HttpServerAddr { get; set; }
  2286. public GoogleMapType MapType { get; set; } = GoogleMapType.Normal;
  2287. internal static double CalculateTotalImageSize(double zoomLevel)
  2288. {
  2289. if (zoomLevel < 1.0)
  2290. return zoomLevel * tileSize * 2;
  2291. return Math.Pow(2.0, zoomLevel) * tileSize;
  2292. }
  2293. public HttpTileSource(ICacheOptionsProvider cacheOptionsProvider) :
  2294. base((int)CalculateTotalImageSize(maxZoomLevel), (int)CalculateTotalImageSize(maxZoomLevel), tileSize, tileSize, cacheOptionsProvider)
  2295. {
  2296. }
  2297. public override Uri GetTileByZoomLevel(int zoomLevel, int tilePositionX, int tilePositionY)
  2298. {
  2299. if (string.IsNullOrWhiteSpace(HttpServerAddr)) return null;
  2300. try
  2301. {
  2302. if (zoomLevel <= maxZoomLevel)
  2303. {
  2304. string imgUrl = $"{HttpServerAddr}/{(int)MapType}/{zoomLevel}/{tilePositionX}/{tilePositionY}";
  2305. //string imgUrl = string.Format("http://192.168.0.214:58089/{0}/{1}/{2}/{3}", (int)GoogleMapType.Normal, zoomLevel, tilePositionX, tilePositionY);
  2306. Uri u = new Uri(imgUrl);
  2307. return u;
  2308. }
  2309. return null;
  2310. }
  2311. catch
  2312. {
  2313. Console.WriteLine($"加载地图数据出错,无法连接到{HttpServerAddr}");
  2314. return null;
  2315. }
  2316. }
  2317. }
  2318. #endregion
  2319. //定位点聚合器
  2320. class PosClusterer : IClusterer
  2321. {
  2322. private MapControl ctrl;
  2323. private IMapDataAdapter owner;
  2324. private MapViewport preViewPoint;
  2325. private DebounceDispatcher dispatcher = new DebounceDispatcher();
  2326. public bool IsBusy { get; private set; }
  2327. public MapItemCollection Items { get; private set; }
  2328. public PosClusterer(MapControl ctrl)
  2329. {
  2330. this.ctrl = ctrl;
  2331. }
  2332. public void SetOwner(IMapDataAdapter owner)
  2333. {
  2334. this.owner = owner;
  2335. Items = new MapItemCollection(owner);
  2336. }
  2337. public void Clusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2338. {
  2339. IsBusy = true;
  2340. if (sourceChanged)
  2341. DoClusterize(sourceItems, viewport, sourceChanged);
  2342. else
  2343. dispatcher.Debounce(100, () => DoClusterize(sourceItems, viewport, sourceChanged));
  2344. }
  2345. private void DoClusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
  2346. {
  2347. if (preViewPoint == null)
  2348. {
  2349. preViewPoint = viewport;
  2350. return;
  2351. }
  2352. if (!sourceChanged && preViewPoint.ZoomLevel == viewport.ZoomLevel)//地图移动或者MapControl大小发生了改变时直接操作Items避免闪烁
  2353. {
  2354. preViewPoint = viewport;
  2355. }
  2356. else//地图进行了缩放
  2357. {
  2358. Items.Clear();
  2359. var cache = new Dictionary<int, List<MapItem>>();
  2360. foreach (MapDot item in sourceItems)
  2361. {
  2362. var point = ctrl.CoordPointToScreenPoint(item.Location);
  2363. int pointX = (int)point.X;
  2364. int pointY = (int)point.Y;
  2365. bool visible = true;
  2366. if (pointX <= _dotSize || pointX > ctrl.Width - _dotSize)
  2367. visible = false;
  2368. else if (pointY <= _dotSize || pointY > ctrl.Height - _dotSize)
  2369. visible = false;
  2370. pointX /= (_dotSize * 2);
  2371. pointY /= (_dotSize * 2);
  2372. var key = pointX << 16 | pointY;
  2373. if (!visible)
  2374. key = -key;
  2375. if (!cache.ContainsKey(key))
  2376. cache.Add(key, new List<MapItem>());
  2377. cache[key].Add(item);
  2378. }
  2379. var innerData = ctrl.Tag as InnerData;
  2380. innerData._clusterCache.Clear();
  2381. LinkedList<MapItem> temp = new LinkedList<MapItem>();
  2382. foreach (var kv in cache)
  2383. {
  2384. var firstDot = kv.Value[0] as MapDot;
  2385. var firstObj = firstDot.Tag as PosData;
  2386. firstDot.Size = kv.Value.Count > 1 ? _dotSize + 2 : _dotSize;
  2387. firstObj.ClusterCount = kv.Value.Count;
  2388. firstObj.ClusterKey = kv.Key;
  2389. innerData._clusterCache.Add(kv.Key, firstDot);
  2390. temp.AddLast(firstDot);
  2391. }
  2392. Items.AddRange(temp);
  2393. cache.Clear();
  2394. preViewPoint = viewport;
  2395. owner.OnClustered();
  2396. }
  2397. this.IsBusy = false;
  2398. }
  2399. //计算多个坐标的中心位置
  2400. public GeoPoint GetCenterPointFromListOfCoordinates(List<MapItem> geoCoordinateList)
  2401. {
  2402. int total = geoCoordinateList.Count;
  2403. double lat = 0, lon = 0;
  2404. foreach (MapDot g in geoCoordinateList)
  2405. {
  2406. lat += (g.Location as GeoPoint).Latitude * Math.PI / 180;
  2407. lon += (g.Location as GeoPoint).Longitude * Math.PI / 180;
  2408. }
  2409. lat /= total;
  2410. lon /= total;
  2411. return new GeoPoint(lat * 180 / Math.PI, lon * 180 / Math.PI);
  2412. }
  2413. }
  2414. }