MapControlEx.cs 113 KB

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