MapControlEx.cs 117 KB

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