MapControlEx.cs 107 KB

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