MapControlEx.cs 110 KB

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