MapControlEx.cs 99 KB

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