MapControlEx.cs 97 KB

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