12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582 |
- using DevExpress.Map.Native;
- using DevExpress.Utils;
- using DevExpress.Utils.Design;
- using DevExpress.Utils.Svg;
- using DevExpress.XtraBars;
- using DevExpress.XtraMap;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Data.Common;
- using System.Data.SQLite;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using DevExpress.XtraMap.ItemEditor;
- using DxHelper;
- using System.Runtime.CompilerServices;
- using DevExpress.XtraPrinting;
- using DevExpress.Export.Xl;
- using DevExpress.XtraEditors;
- using DevExpress.Map.Dashboard;
- using DevExpress.XtraGrid;
- using DevExpress.XtraGrid.Views.Grid;
- using DevExpress.XtraGrid.Columns;
- using DevExpress.Map;
- using System.Threading;
- using System.ComponentModel.DataAnnotations.Schema;
- using XzXdDw.App.Model;
- using DevExpress.XtraCharts.Native;
- using DevExpress.Utils.Extensions;
- using System.Windows.Ink;
- //using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
- //using Serilog;
- //using DevExpress.XtraPrinting.Native;
- //using RHDW.Model;
- /// <summary>
- /// 指示某个属性需要导出
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class ExportCellAttribute : Attribute
- {
- /// <summary>
- /// 指示某个属性需要导出
- /// </summary>
- public ExportCellAttribute()
- {
- }
- /// <summary>
- /// 指示某个属性需要导出
- /// </summary>
- /// <param name="format">浮点数(默认f4)、时间(默认yyyy-MM-dd HH:mm:ss)等导出时的格式化字符串</param>
- public ExportCellAttribute(string format)
- {
- this.Format = format;
- }
- /// <summary>
- /// 浮点数(默认f4)、时间(默认yyyy-MM-dd HH:mm:ss)等导出时的格式化字符串
- /// </summary>
- public string Format { get; set; }
- /// <summary>
- /// 列的排列顺序,未指定的ColumnIndex的按照属性顺序排在之后
- /// </summary>
- public int ColumnIndex { get; set; } = -1;
- }
- /// <summary>
- /// 指示某个属性在ToolTip中显示
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class ToolTipAttribute : Attribute
- {
- /// <summary>
- /// 指示某个属性在ToolTip中显示
- /// </summary>
- public ToolTipAttribute()
- {
- }
- /// <summary>
- /// 指示某个属性在ToolTip中显示
- /// </summary>
- /// <param name="format">浮点数(默认f4)、时间(默认yyyy-MM-dd HH:mm:ss)等导出时的格式化字符串</param>
- public ToolTipAttribute(string format)
- {
- this.Format = format;
- }
- /// <summary>
- /// 浮点数(默认f4)、时间(默认yyyy-MM-dd HH:mm:ss)等导出时的格式化字符串
- /// </summary>
- public string Format { get; set; }
- /// <summary>
- /// ToolTip从上到下的排列顺序,未指定的Index将按照属性顺序排在之后
- /// </summary>
- public int Index { get; set; } = 10000;
- }
- /// <summary>
- /// 定位点绑定到地图的对象
- /// </summary>
- public class PosData : BaseModel<long>
- {
- /// <summary>
- /// 信号时刻
- /// </summary>
- [Display(Name = "信号时刻")]
- [DisplayFormat(DataFormatString = "yyyy-MM-dd HH:mm:ss.fff")]
- [ExportCell(ColumnIndex = 0)]//如果导出了SigTime,则内部会自动按照SigTime降序排列后再导出
- [ToolTip(Index = 0)]
- public DateTime SigTime { get; set; }
- /// <summary>
- /// 定位经度
- /// </summary>
- [Display(Name = "定位经度", AutoGenerateField = false)]
- [ExportCell("f4")]
- [ToolTip("f4")]
- public double PosLon { get; set; }
- /// <summary>
- /// 定位纬度
- /// </summary>
- [Display(Name = "定位纬度", AutoGenerateField = false)]
- [ExportCell("f4")]
- [ToolTip("f4")]
- public double PosLat { get; set; }
- /// <summary>
- /// 定位经度
- /// </summary>
- [Display(Name = "镜像经度", AutoGenerateField = false)]
- [ExportCell("f4")]
- [ToolTip("f4")]
- public double MirrLon { get; set; }
- /// <summary>
- /// 定位纬度
- /// </summary>
- [Display(Name = "镜像纬度", AutoGenerateField = false)]
- [ExportCell("f4")]
- [ToolTip("f4")]
- public double MirrLat { get; set; }
- /// <summary>
- /// 当前点是否被选中(默认false)
- /// </summary>
- [Display(Name = "是否选中", AutoGenerateField = false)]
- [NotMapped]
- public bool Selected { get; set; }
- /// <summary>
- /// 当前点是否可见(默认true)
- /// </summary>
- [Display(Name = "是否可见", AutoGenerateField = false)]
- [NotMapped]
- public bool Visible { get; set; } = true;
- /// <summary>
- /// 用于生成颜色的一个key,相同的key具有相同的颜色,当ColorKey为html颜色时则使用此颜色(如#A1B2FF),默认红色#CC3333
- /// </summary>、
- [Display(Name = "颜色标记", AutoGenerateField = false)]
- [NotMapped]
- public string ColorKey { get; set; } = "#CC3333";
- /// <summary>
- /// 判断定位点是否在一个框选的矩形区域内
- /// </summary>
- /// <param name="startLon"></param>
- /// <param name="startLat"></param>
- /// <param name="endLon"></param>
- /// <param name="endLat"></param>
- /// <returns></returns>
- public bool InRectangle(double startLon, double startLat, double endLon, double endLat)
- {
- return PosLon >= startLon && PosLon <= endLon && PosLat >= startLat && PosLat <= endLat;
- }
- /// <summary>
- /// 内部调用的属性
- /// </summary>
- [Display(AutoGenerateField = false)]
- [NotMapped]
- internal int ClusterCount { get; set; } = 1;
- /// <summary>
- /// 内部调用的属性
- /// </summary>
- [Display(AutoGenerateField = false)]
- [NotMapped]
- internal int ClusterKey { get; set; } = int.MinValue;
- }
- public enum GoogleMapType
- {
- /// <summary>
- /// 卫星地图
- /// </summary>
- Sat = 47626774,
- /// <summary>
- /// 地形图
- /// </summary>
- Landform = 370833361,
- /// <summary>
- /// 混合地图
- /// </summary>
- Mix = 1024577166,
- /// <summary>
- /// 普通地图
- /// </summary>
- Normal = 1818940751
- }
- /// <summary>
- /// MapControl扩展类,封装了常用的非业务基础功能.
- /// 内置了4个图层,ImageTileLayer、DrawLayer、FixedDrawLayer、PosLayer.
- /// 必须首先调用UseDefalutOptions函数
- /// </summary>
- public static class MapControlEx
- {
- class InnerData
- {
- internal GeoPoint _mapMenuGeoPoint;
- internal Dictionary<int, MapItem> _clusterCache = new Dictionary<int, MapItem>();
- internal Dictionary<PosData, MapItem> _dataCache = new Dictionary<PosData, MapItem>();
- internal BarManager barM;
- internal PopupMenu mapMenu;
- internal PopupMenu posMenu;
- internal PopupMenu rectMenu;
- internal Action<(double starLon, double startLat, double centerLon, double centerLat,
- double endLon, double endLat, double lonRange, double latRange)> mOnRectChanged;
- internal MapItemStorage mMapStorage;
- internal MapItemStorage mMapStorageFixed;
- internal MapPolyline distinctPath;
- internal MapDot hoverPoint;
- internal ToolTipControllerShowEventArgs hoverTip;
- internal ToolTipController mapToolTip;
- internal MapItemStorage posStorge;
- internal MapRectangle rangeItem;
- internal MapDot dotItem = new MapDot() { Tag = "DrawRect" };
- internal bool drawingRect = false;
- internal bool mouseLeftDown = false;
- internal (double starLon, double startLat, double centerLon, double centerLat,
- double endLon, double endLat, double lonRange, double latRange)
- CurrentRect;
- internal MapDot preSelectedItem;
- internal Type posDataType;
- }
- private static GoogleMapType mMapType = GoogleMapType.Normal;
- private static List<MapControl> listMapCtrl = new List<MapControl>();
- private const int _dotSize = 8;
- private const int _selectedDotSize = 16;
- /// <summary>
- /// <para>设置地图通用属性并创建4个Layer.</para>
- /// <para>ImageLayer:绘制地图瓦片</para>
- /// <para>DrawLayer:地图绘制图层,右键可以擦除</para>
- /// <para>FixedDrawLayer:地图绘制层,右键无法擦除</para>
- /// <para>PosLayer:定位点绘制专用图层</para>
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static MapControl UseDefalutOptions(this MapControl ctrl)
- {
- var barM = new BarManager();
- barM.BeginInit();
- barM.Form = ctrl;
- var mapMeun = new PopupMenu() { Manager = barM };
- var posMenu = new PopupMenu() { Manager = barM };
- var rectMenu = new PopupMenu() { Manager = barM };
- barM.EndInit();
- listMapCtrl.Add(ctrl);
- var innerData = new InnerData();
- innerData.barM = barM;
- innerData.mapMenu = mapMeun;
- innerData.posMenu = posMenu;
- innerData.rectMenu = rectMenu;
- innerData.mapToolTip = new ToolTipController();
- innerData.mapToolTip.InitialDelay = 10;
- innerData.mapToolTip.KeepWhileHovered = true;
- innerData.mapToolTip.ReshowDelay = 10;
- innerData.mapToolTip.ShowBeak = true;
- innerData.mapToolTip.ToolTipAnchor = DevExpress.Utils.ToolTipAnchor.Cursor;
- innerData.mapToolTip.ToolTipType = ToolTipType.SuperTip;
- ctrl.Tag = innerData;
- ctrl.ToolTipController = innerData.mapToolTip;
- ctrl.ToolTipController.BeforeShow += (sender, e) =>
- {
- if (e.SelectedObject == null) return;
- if (e.SelectedObject.ToString() == ItemsEditorPanelAction.AddRectangle.ToString())
- {
- e.ToolTip = "绘制矩形";
- return;
- }
- var mapDot = e.SelectedObject as MapDot;
- if (mapDot == null) return;
- var posItem = mapDot.Tag as PosData;
- if (mapDot == null || posItem == null) return;
- SuperToolTip superToolTip = new SuperToolTip();
- if (posItem.ClusterCount == 1)
- {
- var props = posItem.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
- var list = new List<(int Index, string Name, string Format, object Value)>();
- foreach (var prop in props)
- {
- var attrToolTip = prop.GetCustomAttribute<ToolTipAttribute>();
- if (attrToolTip == null) continue;
- string toolTipFormat = attrToolTip.Format;
- var val = prop.GetValue(posItem);
- string displayName = prop.Name;
- var attrDisplay = prop.GetCustomAttribute<DisplayAttribute>();
- if (attrDisplay != null && !string.IsNullOrWhiteSpace(attrDisplay.Name))
- displayName = attrDisplay.Name;
- int index = attrToolTip.Index;
- list.Add((index, displayName, toolTipFormat, val));
- }
- list = list.OrderBy(p => p.Index).ToList();
- foreach ((int Index, string Name, string Format, object val) in list)
- {
- string f = null;
- if (val is DateTime)
- {
- f = "yyyy-MM-dd HH:mm:ss";
- }
- else if (val is float || val is double || val is decimal)
- {
- f = "f4";
- }
- if (!string.IsNullOrWhiteSpace(Format))
- f = Format;
- string valStr;
- if (!string.IsNullOrWhiteSpace(f))
- valStr = ((dynamic)val).ToString(f);
- else
- valStr = val.ToString();
- ToolTipItem tipItem = new ToolTipItem();
- tipItem.Text = $"{Name}:{valStr}";
- superToolTip.Items.Add(tipItem);
- }
- }
- else
- {
- ToolTipItem tipItem = new ToolTipItem();
- tipItem.Text = $"当前位置附近有{posItem.ClusterCount}个定位点,放大可查看";
- superToolTip.Items.Add(tipItem);
- }
- e.SuperTip = superToolTip;
- };
- ctrl.MouseDown += (sender, e) =>
- {
- if (e.Button == MouseButtons.Right)
- {
- var hitInfo = ctrl.CalcHitInfo(e.Location);
- if (hitInfo.InMapRectangle && innerData.rangeItem != null)
- {
- rectMenu?.ShowPopup(Cursor.Position);
- }
- else if (hitInfo.InMapDot && hitInfo.MapDot.Tag is PosData)
- {
- var selectPos = (PosData)hitInfo.MapDot.Tag;
- if (!selectPos.Selected)
- {
- selectPos.Selected = true;
- ctrl.UpdatePosItem(selectPos);
- }
- if (selectPos.ClusterCount == 1)
- {
- posMenu?.ShowPopup(Cursor.Position);//选中了原始MapItem
- }
- else
- {
- //选中了聚合后的MapItem
- }
- }
- else
- {
- var geoPoint = ctrl.ScreenPointToCoordPoint(e.Location) as GeoPoint;
- innerData._mapMenuGeoPoint = geoPoint;
- innerData.mapMenu?.ShowPopup(Cursor.Position);
- }
- }
- else
- {
- innerData.mouseLeftDown = true;
- innerData.barM.CloseMenus();
- var hitInfo = ctrl.CalcHitInfo(e.Location);
- if (hitInfo.InMapDot && hitInfo.MapDot.Tag is PosData)
- {
- var selectPos = hitInfo.MapDot.Tag as PosData;
- if (!selectPos.Selected)
- {
- selectPos.Selected = true;
- ctrl.UpdatePosItem(selectPos);
- }
- }
- }
- };
- ctrl.MouseUp += (sender, e) =>
- {
- innerData.mouseLeftDown = false;
- };
- //中心点、缩放级别
- ctrl.MinZoomLevel = 3;
- ctrl.ZoomLevel = 5;
- ctrl.MaxZoomLevel = 14;
- ctrl.CenterPoint = new GeoPoint(18, 110);
- //禁用多余特效
- ctrl.EnableDelayedScrolling = true;
- ctrl.RenderMode = RenderMode.DirectX;
- ctrl.EnableAnimation = false;
- ctrl.EnableRotation = false;
- //ctrl.ShowSearchPanel = false;
- ctrl.SearchPanelOptions.Visible = false;
- ctrl.SelectionMode = ElementSelectionMode.Single;//只能单选图层上的元素
- ((GeoMapCoordinateSystem)ctrl.CoordinateSystem).CircularScrollingMode = CircularScrollingMode.TilesAndVectorItems;
- //地图下方导航栏
- ctrl.NavigationPanelOptions.Height = 35;
- ctrl.NavigationPanelOptions.BackgroundStyle.Fill = Color.Transparent;
- ctrl.NavigationPanelOptions.ShowScrollButtons = false;
- ctrl.NavigationPanelOptions.ShowZoomTrackbar = false;
- // ctrl.NavigationPanelOptions.ShowCoordinates = true;
- //ctrl.NavigationPanelOptions.ShowKilometersScale = false;
- //ctrl.NavigationPanelOptions.ShowMilesScale = false;
- ctrl.NavigationPanelOptions.CoordinatesStyle.Font = new Font("微软雅黑", 10F);
- ctrl.NavigationPanelOptions.ScaleStyle.Font = new Font("微软雅黑", 10F);
- // Create ImageTileLayer
- ImageLayer layer = new ImageLayer() { Name = "ImageTileLayer" };
- bool localGmdbDataEnable = false;//本地Data.Gmdb是否可用,可用时读取本地瓦片,否则执行Http请求资源
- var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
- if (files.Length > 0)
- {
- try
- {
- string conStr = string.Format("Data Source=\"{0}\";Page Size=32768", files[0]);
- var con = new SQLiteConnection(conStr);
- con.Open();
- con.Close();
- localGmdbDataEnable = true;
- }
- catch (Exception ex)
- {
- Console.Error.WriteLine(ex.Message);
- }
- }
- if (localGmdbDataEnable)
- {
- var provider = new ImageTileDataProvider();//地图瓦片提供者
- provider.TileSource = new ImageTileSource();//地图瓦片数据源接口实现
- layer.DataProvider = provider;
- }
- else
- {
- var provider = new HttpMapDataProvider();
- layer.DataProvider = provider;
- }
- ctrl.Layers.Add(layer);
- //地图绘制加载(标点、测距、框选等元素载体图层).用来绘制可擦除的元素
- var layerDraw = new VectorItemsLayer() { Name = "DrawLayer" };
- var drawDataStorage = new MapItemStorage();
- layerDraw.Data = drawDataStorage;
- ctrl.Layers.Add(layerDraw);
- innerData.mMapStorage = drawDataStorage;
- //绘制图层,不可手动擦除,一般用来绘制卫星、参考站等固定元素
- var layerDrawFixed = new VectorItemsLayer() { Name = "FixedDrawLayer" };
- var drawDataStorageFixed = new MapItemStorage();
- layerDrawFixed.Data = drawDataStorageFixed;
- ctrl.Layers.Add(layerDrawFixed);
- innerData.mMapStorageFixed = drawDataStorageFixed;
- //定位点专用PosLayer
- var layerPos = new VectorItemsLayer() { Name = "PosLayer" };
- layerPos.ToolTipPattern = "Test";//随便给一个,不然不会显示定位点的tooltip
- layerPos.AllowEditItems = true;
- layerPos.EnableHighlighting = false;
- layerPos.EnableSelection = false;
- ctrl.Layers.Add(layerPos);
- var posStorge = new MapItemStorage();
- layerPos.Data = posStorge;
- innerData.posStorge = posStorge;
- return ctrl;
- }
- /// <summary>
- /// 在框选矩形上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为选中的定位点</param>
- /// <returns></returns>
- public static MapControl AddPosMenu<T>(this MapControl ctrl, string caption, SvgImage img, Action<T> action) where T : PosData, new()
- {
- var btnCustom = new BarButtonItem() { Caption = caption };
- btnCustom.ImageOptions.SvgImage = img;
- btnCustom.Tag = ctrl;
- var innerData = ctrl.Tag as InnerData;
- btnCustom.ItemClick += (sender, e) =>
- {
- action((T)innerData.preSelectedItem.Tag);
- };
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.posMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 在框选矩形上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为选中的定位点</param>
- /// <returns></returns>
- public static MapControl AddPosMenuEx<T>(this MapControl ctrl, string caption, Image img, Action<T> action) where T : PosData, new()
- {
- var btnCustom = new BarButtonItem() { Caption = caption };
- btnCustom.ImageOptions.Image = img;
- btnCustom.Tag = ctrl;
- var innerData = ctrl.Tag as InnerData;
- btnCustom.ItemClick += (sender, e) =>
- {
- action((T)innerData.preSelectedItem.Tag);
- };
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.posMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 在地图上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为点击位置的经纬度</param>
- /// <returns></returns>
- public static MapControl AddMapMenu(this MapControl ctrl, string caption, SvgImage img, Action<double, double> action)
- {
- var btnCustom = new BarButtonItem() { Caption = caption, Name = caption };
- btnCustom.ImageOptions.SvgImage = img;
- btnCustom.Tag = ctrl;
- var innerData = ctrl.Tag as InnerData;
- btnCustom.ItemClick += (sender, e) =>
- {
- btnCustom.Enabled = false;
- action(innerData._mapMenuGeoPoint.Longitude, innerData._mapMenuGeoPoint.Latitude);
- btnCustom.Enabled = true;
- };
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 在地图上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为点击位置的经纬度</param>
- /// <returns></returns>
- public static MapControl AddMapMenuEx(this MapControl ctrl, string caption, Image img, Action<double, double> action)
- {
- var btnCustom = new BarButtonItem() { Caption = caption, Name = caption };
- btnCustom.ImageOptions.Image = img;
- btnCustom.Tag = ctrl;
- var innerData = ctrl.Tag as InnerData;
- btnCustom.ItemClick += (sender, e) =>
- {
- action(innerData._mapMenuGeoPoint.Longitude, innerData._mapMenuGeoPoint.Latitude);
- };
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 在框选矩形上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为框选的定位点</param>
- /// <returns></returns>
- public static MapControl AddRectMenu<T>(this MapControl ctrl, string caption, SvgImage img, Action<IEnumerable<T>> action) where T : PosData, new()
- {
- var btnCustom = new BarButtonItem() { Caption = caption };
- btnCustom.ImageOptions.SvgImage = img;
- btnCustom.Tag = ctrl;
- btnCustom.ItemClick += (sender, e) =>
- {
- var data = ctrl.GetRectPosItem<T>();
- action(data);
- };
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.rectMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 在框选矩形上增加右键菜单
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="caption"></param>
- /// <param name="img"></param>
- /// <param name="action">一个回调,参数为框选的定位点</param>
- /// <returns></returns>
- public static MapControl AddMapMenuEx<T>(this MapControl ctrl, string caption, Image img, Action<IEnumerable<T>> action) where T : PosData, new()
- {
- var btnCustom = new BarButtonItem() { Caption = caption };
- btnCustom.ImageOptions.Image = img;
- btnCustom.Tag = ctrl;
- btnCustom.ItemClick += (sender, e) =>
- {
- var data = ctrl.GetRectPosItem<T>();
- action(data);
- };
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnCustom);
- innerData.rectMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnCustom));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 重新设置定位数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="items">数据源(指定null或空集合可以清空已有数据)</param>
- /// <param name="clearDrawLayer">是否清除DrawLayer上临时绘制的内容</param>
- public static void SetPosDataSource<T>(this MapControl ctrl, IEnumerable<T> items, bool clearDrawLayer = true) where T : PosData, new()
- {
- var innerData = ctrl.Tag as InnerData;
- innerData._dataCache.Clear();
- if (clearDrawLayer)
- ctrl.ClearDrawObj();
- innerData.posStorge.Items.Clear();
- if (items == null || !items.Any()) return;
- List<MapDot> list = new List<MapDot>();
- for (int i = 0; i < items.Count(); i++)
- {
- var p = items.ElementAt(i);
- if (p.PosLon < -180 || p.PosLon > 180) continue;
- if (p.PosLon == 0 && p.PosLat == 0) continue;
- var mapItem = new MapDot()
- {
- EnableHighlighting = DefaultBoolean.True,
- EnableSelection = DefaultBoolean.False,
- CanMove = false,
- Visible = p.Visible,
- IsHitTestVisible = true,
- Fill = ColorHelper.IsHtmlColor(p.ColorKey) ? ColorTranslator.FromHtml(p.ColorKey) : ColorHelper.GetColor(p.ColorKey),
- Size = _dotSize,
- Tag = items.ElementAt(i),
- Location = new GeoPoint(p.PosLat, p.PosLon)
- };
- list.Add(mapItem);
- innerData._dataCache.Add(p, mapItem);
- }
- innerData.posStorge.Items.AddRange(list);
- }
- /// <summary>
- /// 定位图层数据源添加一个定位点
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="item"></param>
- public static void AddPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
- {
- if (item.PosLon > 180) return;
- var innerData = ctrl.Tag as InnerData;
- var mapItem = new MapDot()
- {
- EnableHighlighting = DefaultBoolean.True,
- EnableSelection = DefaultBoolean.False,
- CanMove = false,
- Visible = item.Visible,
- IsHitTestVisible = true,
- Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey),
- Size = _dotSize,
- Tag = item,
- Location = new GeoPoint(item.PosLat, item.PosLon)
- };
- innerData._dataCache.Add(item, mapItem);
- innerData.posStorge.Items.Add(mapItem);
- }
- /// <summary>
- /// 定位图层数据源删除定位点
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="data"></param>
- public static void DelPosItem<T>(this MapControl ctrl, IEnumerable<T> data) where T : PosData, new()
- {
- if (data == null || !data.Any()) return;
- foreach (var item in data)
- {
- ctrl.DelPosItem(item);
- }
- ctrl.Refresh();
- }
- /// <summary>
- /// 定位图层数据源删除定位点
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="data"></param>
- public static void DelPosItem<T>(this MapControl ctrl, T item) where T : PosData, new()
- {
- if (item == null) return;
- var innerData = ctrl.Tag as InnerData;
- if (innerData._dataCache.ContainsKey(item))
- {
- innerData.posStorge.Items.Remove(innerData._dataCache[item]);
- innerData._dataCache.Remove(item);
- }
- ctrl.Refresh();
- }
- /// <summary>
- /// 定位图层数据源删除定位点
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="data"></param>
- public static void DelPosItem<T>(this MapControl ctrl, Func<T, bool> predicate) where T : PosData, new()
- {
- var innerData = ctrl.Tag as InnerData;
- List<PosData> keys = new List<PosData>();
- foreach (var item in innerData._dataCache.Keys)
- {
- if (predicate((T)item))
- keys.Add(item);
- }
- foreach (var item in keys)
- {
- ctrl.DelPosItem(item);
- }
- ctrl.Refresh();
- }
- /// <summary>
- /// 更新定位数据(可以更新可见性、颜色、经纬度、选中状态)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="item"></param>
- /// <param name="setCenter">是否将这个点设置到地图中心显示</param>
- public static void UpdatePosItem<T>(this MapControl ctrl, T item, bool setCenter = false) where T : PosData, new()
- {
- if (item == null) return;
- var innerData = ctrl.Tag as InnerData;
- if (innerData._dataCache.ContainsKey(item))
- {
- var mapDot = innerData._dataCache[item] as MapDot;
- mapDot.Visible = item.Visible;//外部修改了可见性
- mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
- mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
- if (mapDot.Size != (item.Selected ? _selectedDotSize : _dotSize))//外部修改了选中状态
- {
- mapDot.Size = item.Selected ? _selectedDotSize : _dotSize;
- mapDot.StrokeWidth = item.Selected ? 0 : 1;
- if (item.ClusterCount > 1)
- {
- if (innerData._clusterCache.TryGetValue(item.ClusterKey, out MapItem clusterItem))
- {
- (clusterItem as MapDot).Size = item.Selected ? _selectedDotSize : _dotSize;
- }
- }
- if (mapDot.ClusteredItems.Any())
- (mapDot.ClusteredItems[0] as MapDot).Size = _selectedDotSize;
- if (item.Selected)
- {
- //让选中的Item在上层
- var idx = innerData.posStorge.Items.IndexOf(mapDot);
- innerData.posStorge.Items.Swap(idx, innerData.posStorge.Items.Count - 1);
- //innerData.posStorge.Items.Add(mapDot);
- //需要将上次选中的点设置为未选中
- if (innerData.preSelectedItem != null)
- {
- innerData.preSelectedItem.Size = _dotSize;
- (innerData.preSelectedItem.Tag as PosData).Selected = false;
- if ((innerData.preSelectedItem.Tag as PosData).ClusterCount > 1)
- {
- if (innerData._clusterCache.TryGetValue((innerData.preSelectedItem.Tag as PosData).ClusterKey, out MapItem clusterItem))
- {
- (clusterItem as MapDot).Size = _dotSize + 2;
- }
- }
- }
- innerData.preSelectedItem = mapDot;
- }
- }
- if (setCenter && item.Visible)
- ctrl.SetCenterPoint(item.PosLon, item.PosLat, false);
- }
- }
- /// <summary>
- /// 更新定位数据(可以更新可见性、颜色、经纬度)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="item"></param>
- public static void UpdatePosItem<T>(this MapControl ctrl, IEnumerable<T> items) where T : PosData, new()
- {
- if (items == null || !items.Any()) return;
- var innerData = ctrl.Tag as InnerData;
- foreach (var item in items)
- {
- if (innerData._dataCache.ContainsKey(item))
- {
- var mapDot = innerData._dataCache[item] as MapDot;
- mapDot.Visible = item.Visible;//外部修改了可见性
- mapDot.Fill = ColorHelper.IsHtmlColor(item.ColorKey) ? ColorTranslator.FromHtml(item.ColorKey) : ColorHelper.GetColor(item.ColorKey);//外部修改了颜色
- mapDot.Location = new GeoPoint(item.PosLat, item.PosLon);//外部修改了位置
- }
- }
- }
- /// <summary>
- /// 设置地图中心点
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="lon"></param>
- /// <param name="lat"></param>
- /// <param name="animated">是否显示动画</param>
- /// <returns></returns>
- public static MapControl SetCenterPoint(this MapControl ctrl, double lon, double lat, bool animated = false)
- {
- ctrl.SetCenterPoint(new GeoPoint(lat, lon), animated);
- return ctrl;
- }
- public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, Image img, string toolTip = "")
- {
- var innerData = ctrl.Tag as InnerData;
- var item = new MapCustomElement() { Tag = tag };
- item.UseAnimation = false;
- item.BackgroundDrawingMode = ElementState.None;
- item.Location = new GeoPoint(imgLat, imgLon);
- item.Image = img;
- item.ToolTipPattern = toolTip;
- innerData.mMapStorage.Items.Add(item);
- }
- public static void DrawFixedImg(this MapControl ctrl, string tag, double imgLat, double imgLon, SvgImage img, Size size, string toolTip = "")
- {
- var innerData = ctrl.Tag as InnerData;
- var item = new MapCustomElement() { Tag = tag };
- item.UseAnimation = false;
- item.BackgroundDrawingMode = ElementState.None;
- item.Location = new GeoPoint(imgLat, imgLon);
- item.SvgImage = img;
- item.SvgImageSize = size;
- item.ToolTipPattern = toolTip;
- innerData.mMapStorage.Items.Add(item);
- }
- public static void DelFixedImg(this MapControl ctrl, string tag)
- {
- var innerData = ctrl.Tag as InnerData;
- var delItems = innerData.mMapStorageFixed.Items.ToList().FindAll(p => p.Tag.ToString() == tag);
- foreach (var item in delItems)
- {
- innerData.mMapStorageFixed.Items.Remove(item);
- }
- }
- /// <summary>
- /// 获取当前矩形框选的定位点
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static IEnumerable<T> GetRectPosItem<T>(this MapControl ctrl) where T : PosData, new()
- {
- var innerData = ctrl.Tag as InnerData;
- if (innerData.CurrentRect == default) return new List<T>();
- var rect = ctrl.GetCurrentRect();
- double startLon = rect.starLon;
- double startLat = rect.startLat;
- double endLon = rect.endLon;
- double endLat = rect.endLat;
- var temp = innerData._dataCache.Keys.Where(p => p.InRectangle(startLon, startLat, endLon, endLat));
- var res = temp.Select(p => (T)p);
- return res;
- }
- /// <summary>
- /// <para>设置地图瓦片Http地址.格式如http://192.168.100.63:58089</para>
- /// <para>当客户端本地运行目录或子目录存在Data.gmdb时Http接口不会被调用</para>
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="httpAddr">such as http://192.168.100.63:58089</param>
- /// <returns></returns>
- public static MapControl SetMapDataHttpAddr(this MapControl ctrl, string httpAddr)
- {
- var provider = ctrl.GetImageLayer().DataProvider;
- if (provider is HttpMapDataProvider)
- {
- var tileSource = ((provider as HttpMapDataProvider).TileSource as HttpTileSource);
- tileSource.HttpServerAddr = httpAddr;
- }
- return ctrl;
- }
- /// <summary>
- /// 定位点使用内置聚合器
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static MapControl UseCluster(this MapControl ctrl)
- {
- var innerData = ctrl.Tag as InnerData;
- innerData.posStorge.Clusterer = new PosClusterer(ctrl);//定位点聚合器
- return ctrl;
- }
- /// <summary>
- /// 为地图添加右键测距功能
- /// </summary>
- /// <returns></returns>
- public static MapControl UseDistanceLine(this MapControl ctrl)
- {
- var btnDistance = new BarButtonItem() { Caption = "测距" };
- btnDistance.ImageOptions.SvgImage = SvgHelper.CreateDistanceLine();
- btnDistance.Tag = ctrl;
- btnDistance.ItemClick += DistanceLine_ItemClick;
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnDistance);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnDistance));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 为地图添加右键标点功能
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="menu"></param>
- /// <param name="item"></param>
- /// <returns></returns>
- public static MapControl UseMarkDot(this MapControl ctrl)
- {
- var btnMarkDot = new BarButtonItem() { Caption = "标点" };
- btnMarkDot.ImageOptions.SvgImage = SvgHelper.CreateMarkDot();
- btnMarkDot.Tag = ctrl;
- btnMarkDot.ItemClick += MarkDot_ItemClick;
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnMarkDot);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnMarkDot));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 为地图添加清除功能
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="item"></param>
- /// <returns></returns>
- public static MapControl UseClearAll(this MapControl ctrl)
- {
- var btnClearAll = new BarButtonItem() { Caption = "清除" };
- btnClearAll.ImageOptions.SvgImage = SvgHelper.CreateClear();
- btnClearAll.Tag = ctrl;
- btnClearAll.ItemClick += (sender, e) => ctrl.ClearDrawObj();
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnClearAll);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnClearAll));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 为地图添加导出图片功能
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="item"></param>
- /// <returns></returns>
- public static MapControl UseExportImg(this MapControl ctrl)
- {
- var btnExportImg = new BarButtonItem() { Caption = "导出图片" };
- btnExportImg.ImageOptions.SvgImage = SvgHelper.CreateExportImg();
- btnExportImg.Tag = ctrl;
- btnExportImg.ItemClick += ExportImg_ItemClick;
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnExportImg);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportImg));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 为地图添加导出图片功能
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="item"></param>
- /// <returns></returns>
- public static MapControl UseExportCsv(this MapControl ctrl, bool exportHeader = true)
- {
- var innerData = ctrl.Tag as InnerData;
- var btnExportCsv = new BarButtonItem() { Caption = "导出Csv" };
- btnExportCsv.ImageOptions.SvgImage = SvgHelper.CreateExportCsv();
- btnExportCsv.Tag = ctrl;
- btnExportCsv.ItemClick += (sender, e) =>
- {
- if (!innerData._dataCache.Any()) return;
- bool exportSigTime = false;
- Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
- var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
- List<(int ColumnIndex, PropertyInfo Prop, string Header)> listPorps = new List<(int, PropertyInfo, string)>();
- foreach (var prop in props)
- {
- ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
- if (attrExport == null) continue;
- if (prop.Name == nameof(PosData.SigTime))
- exportSigTime = true;
- if (!string.IsNullOrWhiteSpace(attrExport.Format))
- {
- cellFormats.Add(prop.Name, attrExport.Format);
- }
- if (attrExport.ColumnIndex == -1)
- attrExport.ColumnIndex = 10000;
- var attrDisplay = prop.GetCustomAttribute<DisplayAttribute>();
- if (attrDisplay != null && !string.IsNullOrWhiteSpace(attrDisplay.Name))
- listPorps.Add((attrExport.ColumnIndex, prop, attrDisplay.Name));
- else
- listPorps.Add((attrExport.ColumnIndex, prop, prop.Name));
- }
- listPorps = listPorps.OrderBy(p => p.ColumnIndex).ToList();
- using (var dialog = new SaveFileDialog())
- {
- dialog.Filter = "CSV文件|*.csv";
- dialog.AddExtension = true;
- dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.csv";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- var list = innerData._dataCache.Keys as IEnumerable<PosData>;
- if (exportSigTime)
- list = list.OrderByDescending(p => p.SigTime);//如果导出了SigTime,则自动按照SigTime降序排列后导出
- StreamWriter sw = new StreamWriter(dialog.FileName, false, new UTF8Encoding(true));//utf8-bom
- if (exportHeader)
- {
- foreach (var prop in listPorps)
- {
- sw.Write($"{prop.Header},");
- }
- sw.WriteLine();
- }
- WaitHelper.ShowOverlayForm(ctrl);
- long count = list.Count() * listPorps.Count;
- int idx = 1;
- foreach (var item in list)
- {
- foreach (var prop in listPorps)
- {
- WaitHelper.UpdateOverlyText($"{idx * 100 / count}%");
- var value = prop.Prop.GetValue(item);
- string str = null;
- if (cellFormats.ContainsKey(prop.Prop.Name))
- {
- str = ((dynamic)value).ToString(cellFormats[prop.Prop.Name]);
- }
- else
- {
- if (value is DateTime)
- str = $"{(DateTime)value:yyyy-MM-dd HH:mm:ss}";
- else if (value is float || value is double || value is decimal)
- {
- dynamic valD = value;
- str = ((dynamic)value).ToString("f4");
- }
- }
- sw.Write($"{str},");
- idx++;
- }
- sw.WriteLine();
- }
- sw.Close();
- WaitHelper.CloseOverlayForm();
- }
- }
- GC.Collect();
- };
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnExportCsv);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportCsv));
- innerData.barM.EndInit();
- return ctrl;
- }
- /// <summary>
- /// 为地图添加导出Excel数据功能
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="ctrl"></param>
- /// <param name="exportHeader">是否导出列头</param>
- /// <returns></returns>
- public static MapControl UseExportXlsx(this MapControl ctrl, bool exportHeader = true)
- {
- Action action = () =>
- {
- var btnExportXlsx = new BarButtonItem() { Caption = "导出Excel" };
- btnExportXlsx.ImageOptions.SvgImage = SvgHelper.CreateExportXlsx();
- var innerData = ctrl.Tag as InnerData;
- innerData.barM.BeginInit();
- innerData.barM.Items.Add(btnExportXlsx);
- innerData.mapMenu.LinksPersistInfo.Add(new LinkPersistInfo(btnExportXlsx));
- innerData.barM.EndInit();
- btnExportXlsx.ItemClick += (sender, e) =>
- {
- if (!innerData._dataCache.Any()) return;
- GridControl gc = new GridControl();
- GridView view = new GridView();
- view.GridControl = gc;
- gc.MainView = view;
- gc.ViewCollection.Add(view);
- view.OptionsPrint.ShowPrintExportProgress = false;
- bool exportSigTime = false;
- Dictionary<string, string> cellFormats = new Dictionary<string, string>();//单元格的format
- var props = innerData._dataCache.Keys.GetType().GetGenericArguments().First().GetProperties(BindingFlags.Public | BindingFlags.Instance);
- foreach (var prop in props)
- {
- ExportCellAttribute attrExport = prop.GetCustomAttribute<ExportCellAttribute>();
- if (attrExport == null) continue;
- if (prop.Name == nameof(PosData.SigTime))
- exportSigTime = true;
- if (!string.IsNullOrWhiteSpace(attrExport.Format))
- {
- cellFormats.Add(prop.Name, attrExport.Format);
- }
- var col = new GridColumn();
- col.FieldName = prop.Name;
- col.Visible = true;
- var attr = prop.GetCustomAttribute<DisplayAttribute>();
- if (attr != null && !string.IsNullOrWhiteSpace(attr.Name))
- col.Caption = attr.Name;
- else
- col.Caption = prop.Name;
- if (attrExport.ColumnIndex >= 0)
- col.VisibleIndex = attrExport.ColumnIndex;
- view.Columns.Add(col);
- }
- gc.Visible = false;
- gc.Parent = ctrl.Parent;
- using (var dialog = new SaveFileDialog())
- {
- dialog.Filter = "Excel文件|*.xlsx";
- dialog.AddExtension = true;
- dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- var list = innerData._dataCache.Keys.ToList();
- if (exportSigTime)
- list = list.OrderByDescending(p => p.SigTime).ToList();//如果导出了SigTime,则自动按照SigTime降序排列后导出
- gc.DataSource = list;
- gc.Visible = true;
- var exportType = DevExpress.Export.ExportSettings.DefaultExportType;
- var options = new XlsxExportOptionsEx();
- WaitHelper.ShowOverlayForm(ctrl);
- options.ExportProgress += arg =>
- {
- WaitHelper.UpdateOverlyText($"{arg.ProgressPercentage}%");
- if (arg.ProgressPercentage >= 100)
- {
- WaitHelper.CloseOverlayForm();
- }
- };
- view.OptionsPrint.PrintHeader = exportHeader;
- options.CustomizeCell += arg =>
- {
- arg.Handled = true;
- var aligmentCenter = new XlCellAlignment()
- {
- HorizontalAlignment = XlHorizontalAlignment.Center,
- VerticalAlignment = XlVerticalAlignment.Center
- };
- var aligmentLeft = new XlCellAlignment()
- {
- HorizontalAlignment = XlHorizontalAlignment.Left,
- VerticalAlignment = XlVerticalAlignment.Center
- };
- if (arg.Value is bool)
- {
- arg.Formatting.Alignment = aligmentCenter;
- arg.Value = ((bool)arg.Value) ? "☑" : "☐";
- }
- if (arg.Value is DateTime)
- {
- arg.Formatting.Alignment = aligmentLeft;
- arg.Formatting.FormatType = FormatType.DateTime;
- arg.Formatting.FormatString = "yyyy-MM-dd HH:mm:ss";
- }
- else if (arg.Value is float || arg.Value is double || arg.Value is decimal)
- {
- arg.Formatting.Alignment = aligmentLeft;
- arg.Formatting.FormatType = FormatType.Numeric;
- arg.Formatting.FormatString = "f4";
- }
- if (cellFormats.ContainsKey(arg.ColumnFieldName))
- {
- arg.Formatting.FormatString = cellFormats[arg.ColumnFieldName];
- }
- };
- view.OptionsPrint.ShowPrintExportProgress = false;
- DevExpress.Export.ExportSettings.DefaultExportType = DevExpress.Export.ExportType.DataAware;
- gc.ExportToXlsx(dialog.FileName, options);
- DevExpress.Export.ExportSettings.DefaultExportType = exportType;
- gc.Visible = false;
- }
- }
- gc.Parent = null;
- gc.Dispose();
- GC.Collect();
- };
- };
- if (ctrl.Parent == null)
- {
- ctrl.ParentChanged += (sender, e) => action();
- }
- else
- {
- action();
- }
- return ctrl;
- }
- /// <summary>
- /// 为地图添加矩形框选区域功能
- /// </summary>
- /// <returns></returns>
- public static MapControl UseDrawRect(this MapControl ctrl, Action<(double starLon, double startLat, double centerLon, double centerLat,
- double endLon, double endLat, double lonRange, double latRange)> onRectChanged = null)
- {
- var innerData = ctrl.Tag as InnerData;
- innerData.mOnRectChanged = onRectChanged;
- ctrl.MapEditor.ShowEditorPanel = true;
- ctrl.MapEditor.PanelOptions.ShowAddCalloutButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddCustomElementButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddDotButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddEllipseButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddLineButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddPathButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddPolylineButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddPushpinButton = false;
- ctrl.MapEditor.PanelOptions.ShowAddSplineButton = false;
- ctrl.MapEditor.PanelOptions.ShowEditModeButton = false;
- ctrl.MapEditor.PanelOptions.ShowTransformModeButton = false;
- ctrl.MapEditor.PanelOptions.ShowUndoRedoButtons = false;
- ctrl.MouseMove += DrawRect_MouseMove;
- ctrl.MapEditor.MapItemCreating += (sender, e) =>
- {
- if (!innerData.mouseLeftDown)
- {
- e.Cancel = true;
- return;
- }
- if (!(e.Item is MapRectangle)) return;
- var items = innerData.mMapStorage.Items.ToList().FindAll(p => p.Tag != null && p.Tag.ToString() == "DrawRect");
- ctrl.MapEditor.RemoveItems(items);
- ctrl.RemoveFlag("RectCallout");
- var item = e.Item as MapRectangle;
- item.Tag = "DrawRect";
- item.CanMove = false;
- item.CanResize = false;
- item.EnableSelection = DefaultBoolean.False;
- item.EnableHighlighting = DefaultBoolean.True;
- innerData.rangeItem = item;
- if (innerData.rangeItem.Height == 0 && innerData.rangeItem.Width == 0)
- {
- innerData.rangeItem.Height = 5;
- innerData.rangeItem.Width = 5;
- }
- item.Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209));
- item.Stroke = Color.FromArgb(23, 107, 209);
- item.StrokeWidth = 1;
- innerData.dotItem.Fill = Color.Red;
- innerData.dotItem.Size = 6;
- innerData.dotItem.Location = innerData.rangeItem.GetCenter();
- innerData.mMapStorage.Items.Add(innerData.rangeItem);
- innerData.mMapStorage.Items.Add(innerData.dotItem);
- DrawRect_MouseMove(ctrl, null);
- var layer = ctrl.Layers.Find(p => p.Name == "");
- if (layer != null) ctrl.Layers.Remove(layer);
- };
- ctrl.MapEditor.MapItemEdited += (sender, e) =>
- {
- innerData.drawingRect = e.Action == MapEditorAction.Create;
- };
- return ctrl;
- }
- public static void Drea(this MapControl ctrl, double Lat,double Lon)
- {
- var innerData = ctrl.Tag as InnerData;
- var mapItem = new MapDot()
- {
- Stroke = Color.FromArgb(128, 255, 93, 106),
- ToolTipPattern = "天线",
- EnableHighlighting = DefaultBoolean.True,
- EnableSelection = DefaultBoolean.False,
- CanMove = false,
- Visible = true,
- IsHitTestVisible = true,
- Fill = Color.FromArgb(128, 255, 93, 106),
- Size = 400,
- Tag = "天线",
- Location = new GeoPoint(Lat, Lon),
- StrokeWidth = 1,
- };
- innerData.posStorge.Items.Add(mapItem);
- }
- public static void DrawEllipse(this MapControl ctrl, double lat, double lon, int radius)
- {
- var innerData = ctrl.Tag as InnerData;
- try
- {
- if (radius <= 0)
- return;
- CoordPointCollection latLngs = new CoordPointCollection();
- MyLatLng centerLatLng = new MyLatLng(lon, lat);
- // 0 - 360度 寻找半径为radius,圆心为centerP的圆上点的经纬度
- for (int i = 0; i < 360; i++)
- {
- //获取目标经纬度
- MyLatLng tempLatLng = getMyLatLng(centerLatLng, radius, i);
- //将自定义的经纬度类 转换成 标准经纬度类
- CoordPoint p = new GeoPoint(tempLatLng.m_Latitude, tempLatLng.m_Longitude);
- latLngs.Add(p);
- }
- //安全性检查
- if (latLngs.Count < 20)
- {
- return;
- }
- //通过绘制多边形的方式绘制圆
- MapPolygon gpol = new MapPolygon();
- gpol.Points = latLngs;
- gpol.Stroke = Color.Red;
- gpol.Fill = Color.FromArgb(50, Color.Red);
- gpol.IsHitTestVisible = true;
- innerData.mMapStorage.Items.Add(gpol);
- }
- catch (Exception ex)
- {
- //Dialog.Error(ex);
- }
- }
- /// <summary>
- /// 绘制矩形
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="startLon"></param>
- /// <param name="startLat"></param>
- /// <param name="endLon"></param>
- /// <param name="endLat"></param>
- public static void DrawRect(this MapControl ctrl, double startLon, double startLat, double endLon, double endLat, bool recCallback = false)
- {
- var innerData = ctrl.Tag as InnerData;
- if (innerData.rangeItem != null)
- innerData.mMapStorage.Items.Remove(innerData.rangeItem);
- if (innerData.dotItem != null)
- innerData.mMapStorage.Items.Remove(innerData.dotItem);
- double centerLon = (startLon + endLon) / 2;
- double centerLat = (startLat + endLat) / 2;
- var size = BoundingRectItemHelper.CalculateRectangleSize(ctrl.CoordinateSystem,
- new GeoPoint(startLat, startLon),
- new GeoPoint(endLat, endLon));
- innerData.dotItem.Location = new GeoPoint(centerLat, centerLon);
- innerData.dotItem.Fill = Color.Red;
- innerData.dotItem.Size = 8;
- var rect = new MapRectangle()
- {
- CanMove = false,
- CanResize = false,
- EnableSelection = DefaultBoolean.False,
- EnableHighlighting = DefaultBoolean.True,
- Tag = "DrawRect",
- Width = size.Width,
- Height = size.Height,
- Location = new GeoPoint(startLat, startLon),
- Fill = Color.FromArgb(50, Color.FromArgb(23, 107, 209)),
- Stroke = Color.FromArgb(23, 107, 209),
- StrokeWidth = 1
- };
- innerData.rangeItem = rect;
- innerData.CurrentRect = (startLon, startLat, centerLon, centerLat, endLon, endLat, (endLon - startLon) / 2, (endLat - startLat) / 2);
- innerData.mMapStorage.Items.Add(innerData.rangeItem);
- innerData.mMapStorage.Items.Add(innerData.dotItem);
- if (recCallback)
- innerData.mOnRectChanged?.Invoke(ctrl.GetCurrentRect());
- }
- public static void DrawGdopLine(this MapControl ctrl, IEnumerable<(string wcKm, double lon, double lat)> lines)
- {
- if (lines == null || !lines.Any()) return;
- var innerData = ctrl.Tag as InnerData;
- var wcKm = lines.First().wcKm;
- var polyLine = new MapPolyline()
- {
- Stroke = ColorHelper.GetColor(wcKm),
- StrokeWidth = 2,
- IsGeodesic = true,
- CanResize = false,
- CanEdit = false,
- CanRotate = false,
- IsHitTestVisible = true,
- CanMove = false,
- Tag = $"DrawGdopLine_{wcKm}",
- };
- polyLine.TitleOptions.Pattern = wcKm;
- foreach (var item in lines)
- {
- if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
- polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
- }
- if (!polyLine.Points.Any()) return;
- innerData.mMapStorage.Items.Add(polyLine);
- }
- public static void DrawDtoLine(this MapControl ctrl, string title, IEnumerable<(double lon, double lat)> lines)
- {
- if (lines == null || !lines.Any()) return;
- var innerData = ctrl.Tag as InnerData;
- var polyLine = new MapPolyline()
- {
- Stroke = ColorHelper.GetColor(title),
- StrokeWidth = 2,
- IsGeodesic = true,
- CanResize = false,
- CanEdit = false,
- CanRotate = false,
- IsHitTestVisible = true,
- CanMove = false,
- Tag = $"DrawDtoLine_{title}",
- ToolTipPattern = $"{title}",
- };
- foreach (var item in lines)
- {
- if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
- polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
- }
- if (!polyLine.Points.Any()) return;
- innerData.mMapStorage.Items.Add(polyLine);
- }
- public static void DrawDtoPonit(this MapControl ctrl, string title, IEnumerable<(double lon, double lat)> lines)
- {
- if (lines == null || !lines.Any()) return;
- var innerData = ctrl.Tag as InnerData;
- List<MapDot> list = new List<MapDot>();
- var color = ColorHelper.GetColor(title);
- for (int i = 0; i < lines.Count(); i++)
- {
- var p = lines.ElementAt(i);
- if (p.lon < -180 || p.lon > 180) continue;
- if (p.lon == 0 && p.lon == 0) continue;
- var mapItem = new MapDot()
- {
- EnableHighlighting = DefaultBoolean.True,
- EnableSelection = DefaultBoolean.False,
- CanMove = false,
- Visible = true,
- IsHitTestVisible = true,
- Fill = color,
- Size = 4,
- Tag = $"DrawPoint_{title}{lines.ElementAt(i).lon}",
- Location = new GeoPoint(p.lat, p.lon),
- ToolTipPattern = $"{title}",
- };
- list.Add(mapItem);
- }
- if (!list.Any()) return;
- innerData.mMapStorage.Items.AddRange(list);
- }
- public static void DrawErrEllipse(this MapControl ctrl, double r1, double r2, IEnumerable<(double lon, double lat)> lines)
- {
- if (lines == null || !lines.Any()) return;
- var innerData = ctrl.Tag as InnerData;
- //innerData.mMapStorage.Items.Clear();
- var polyLine = new MapPolyline()
- {
- Stroke = Color.Red,
- StrokeWidth = 4,
- IsGeodesic = true,
- CanResize = false,
- CanEdit = false,
- CanRotate = false,
- IsHitTestVisible = true,
- CanMove = false,
- Tag = $"DrawErrEllipse",
- };
- //polyLine.ToolTipPattern = $"长轴:{r1:f1}km\r\n短轴:{r2:f1}km";
- foreach (var item in lines)
- {
- if (double.IsNaN(item.lat) || double.IsNaN(item.lon)) continue;
- polyLine.Points.Add(new GeoPoint(item.lat, item.lon));
- }
- if (!polyLine.Points.Any()) return;
- innerData.mMapStorage.Items.Add(polyLine);
- var callout = new DevExpress.XtraMap.MapCallout()
- {
- Text = $"R1={r1:f1}km\r\nR2={r2:f1}km",
- Location = polyLine.Points.First(),
- CanMove = false,
- IsHitTestVisible = false,
- };
- innerData.mMapStorage.Items.Add(callout);
- }
- public static void ClearRect(this MapControl ctrl)
- {
- var innerDate = ctrl.Tag as InnerData;
- if (innerDate.rangeItem != null)
- innerDate.mMapStorage.Items.Remove(innerDate.rangeItem);
- if (innerDate.dotItem != null)
- innerDate.mMapStorage.Items.Remove(innerDate.dotItem);
- }
- /// <summary>
- /// 获取地图框选的范围信息(可能为null)
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static (double starLon, double startLat, double centerLon, double centerLat,
- double endLon, double endLat, double lonRange, double latRange) GetCurrentRect(this MapControl ctrl)
- {
- var innerData = ctrl.Tag as InnerData;
- return innerData.CurrentRect;
- }
- /// <summary>
- /// 获取地图瓦片图层
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static ImageLayer GetImageLayer(this MapControl ctrl)
- {
- if (ctrl.Layers == null) return null;
- return (ImageLayer)ctrl.Layers["ImageTileLayer"];
- }
- /// <summary>
- /// 获取地图绘制图层
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static VectorItemsLayer GetDrawLayer(this MapControl ctrl)
- {
- return (VectorItemsLayer)ctrl.Layers["DrawLayer"];
- }
- /// <summary>
- /// 获取地图绘制图层
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static VectorItemsLayer GetPosLayer(this MapControl ctrl)
- {
- return (VectorItemsLayer)ctrl.Layers["PosLayer"];
- }
- /// <summary>
- /// 获取地图绘制图层的数据仓库
- /// </summary>
- /// <param name="ctrl"></param>
- /// <returns></returns>
- public static MapItemStorage GetDrawStorage(this MapControl ctrl)
- {
- var innerData = ctrl.Tag as InnerData;
- return innerData.mMapStorage;
- }
- public static void RemoveFlag(this MapControl ctrl, string flag)
- {
- var innerData = ctrl.Tag as InnerData;
- var items = innerData.mMapStorage.Items.ToList().FindAll(p => p.Tag != null && p.Tag.ToString() == flag);
- foreach (var item in items)
- {
- innerData.mMapStorage.Items.Remove(item);
- }
- //ctrl.MapEditor.RemoveItems(items);
- }
- /// <summary>
- /// 设置地图类型.默认为Normal
- /// 该方法为所有MapControl实例设置地图类型
- /// </summary>
- /// <param name="ctrl"></param>
- /// <param name="mapType"></param>
- public static void SetMapType(GoogleMapType mapType)
- {
- mMapType = mapType;
- listMapCtrl.ForEach(t =>
- {
- if (t.GetImageLayer() == null) return;
- var provider = t.GetImageLayer().DataProvider as MapTileDataProviderBase;
- provider?.ClearCache();
- t.Refresh();
- });
- }
- #region private
- private static void DrawRect_MouseMove(object sender, MouseEventArgs e)
- {
- var innerData = (sender as MapControl).Tag as InnerData;
- if (!innerData.drawingRect) return;
- innerData.dotItem.Location = innerData.rangeItem.GetCenter();
- var startLon = Math.Round(innerData.rangeItem.Location.GetX(), 3);
- var startLat = Math.Round(innerData.rangeItem.Location.GetY(), 3);
- if (startLon >= 180)
- {
- startLon -= 360;
- }
- if (startLon <= -180)
- {
- startLon += 360;
- }
- var center = innerData.rangeItem.GetCenter();
- var centerLon = Math.Round(center.GetX(), 3);
- if (centerLon >= 180)
- {
- centerLon -= 360;
- }
- if (centerLon <= -180)
- {
- centerLon += 360;
- }
- var centerLat = Math.Round(center.GetY(), 3);
- double endLon;
- if (centerLon < 0 && startLon > 0)
- endLon = startLon + 2 * (centerLon + 360 - startLon);
- else
- endLon = startLon + 2 * (centerLon - startLon);
- var endLat = startLat + 2 * (centerLat - startLat);
- var StartLon = Math.Min(startLon, endLon);
- var StartLat = Math.Min(startLat, endLat);
- var CenterLon = centerLon;
- var CenterLat = centerLat;
- var EndLon = Math.Max(startLon, endLon);
- var EndLat = Math.Max(startLat, endLat);
- double centerLonNew = CenterLon % 360;
- CenterLon = centerLonNew;
- //double LonRange = Math.Round((EndLon - StartLon) / 2, 3);
- //double LatRange = Math.Round((EndLat - StartLat) / 2, 3);
- double LonRange = Math.Round((EndLon - StartLon), 3);
- double LatRange = Math.Round((EndLat - StartLat), 3);
- if (LonRange >= 360)
- {
- }
- innerData.CurrentRect = (StartLon, StartLat, CenterLon, CenterLat, EndLon, EndLat, LonRange, LatRange);
- innerData.mOnRectChanged?.Invoke(innerData.CurrentRect);
- }
- private static void ExportImg_ItemClick(object sender, ItemClickEventArgs e)
- {
- var ctrl = e.Item.Tag as MapControl;
- using (var dialog = new SaveFileDialog())
- {
- dialog.Filter = "PNG图片|*.png";
- dialog.AddExtension = true;
- dialog.FileName = $"Map{DateTime.Now:yyyyMMddHHmmss}.png";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- ctrl.ExportToImage(dialog.FileName, ImageFormat.Png);
- }
- }
- }
- private static void ExportCsv_ItemClick(object sender, ItemClickEventArgs e)
- {
- var ctrl = e.Item.Tag as MapControl;
- using (var dialog = new SaveFileDialog())
- {
- dialog.Filter = "CSV文件|*.csv";
- dialog.AddExtension = true;
- dialog.FileName = $"Pos{DateTime.Now:yyyyMMddHHmmss}.xlsx";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- ctrl.ExportToXlsx(dialog.FileName);
- }
- }
- }
- private static void ClearDrawObj(this MapControl ctrl)
- {
- ctrl.Invoke(new Action(() =>
- {
- try
- {
- var innerData = ctrl.Tag as InnerData;
- ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
- innerData.drawingRect = false;
- innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
- innerData.rangeItem = null;
- if (innerData.mMapStorage != null && innerData.mMapStorage.Items.Any())
- {
- innerData.mMapStorage.Items.Clear();
- }
- //临时
- if (innerData.mMapStorageFixed != null && innerData.mMapStorageFixed.Items.Any())
- innerData.mMapStorageFixed.Items.Clear();
- }
- catch (Exception ex)
- {
- }
- }));
- }
- private static void DistanceLine_ItemClick(object sender, ItemClickEventArgs e)
- {
- var ctrl = e.Item.Tag as MapControl;
- var innerData = ctrl.Tag as InnerData;
- ctrl.MapEditor.SetEditMode();
- var items = innerData.mMapStorage.Items.ToArray();
- foreach (var item in items)
- {
- if (item.Tag != null && item.Tag.ToString() == "DrawDistanceLine")
- innerData.mMapStorage.Items.Remove(item);
- }
- if (innerData.distinctPath != null)
- {
- innerData.distinctPath.Points.Clear();
- }
- innerData.distinctPath = new MapPolyline()
- {
- Stroke = Color.FromArgb(127, 255, 0, 199),
- StrokeWidth = 2,
- IsGeodesic = true,
- CanResize = false,
- CanEdit = false,
- CanRotate = false,
- IsHitTestVisible = false,
- CanMove = true,
- Tag = "DrawDistanceLine"
- };
- innerData.mMapStorage.Items.Add(innerData.distinctPath);
- innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
- innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
- innerData.mMapStorage.Items.Add(innerData.hoverPoint);
- innerData.hoverTip = CreateHoverTip();
- ctrl.MouseClick += AddDistinctPoint;
- ctrl.MouseMove += MovingDistinct;
- ctrl.MouseLeave += MapControl_MouseLeave;
- ctrl.MouseEnter += MapControl_MouseEnter;
- ctrl.DoubleClick += EndDistinct;
- }
- private static void MarkDot_ItemClick(object sender, ItemClickEventArgs e)
- {
- var ctrl = e.Item.Tag as MapControl;
- ctrl.MapEditor.SetTransformMode(MapItemTransform.None);
- var innerData = ctrl.Tag as InnerData;
- innerData.drawingRect = false;
- using (var frm = new MapEditPointView())
- {
- if (frm.ShowDialog() != DialogResult.OK) return;
- var locPoint = new GeoPoint(frm.Lat, frm.Lon);
- MapCustomElement cusItem = new MapCustomElement()
- {
- Location = locPoint,
- UseAnimation = true,
- CanMove = false,
- EnableHighlighting = DefaultBoolean.True,
- EnableSelection = DefaultBoolean.False,
- Text = "",
- ToolTipPattern = $"{frm.Caption}",
- SvgImage = SvgHelper.CreatePentagram(),
- SvgImageSize = new Size(32, 32),
- TextAlignment = DevExpress.XtraMap.TextAlignment.BottomCenter,
- Tag = "DrawMarkDot"
- };
- innerData.mMapStorage.Items.Add(cusItem);
- }
- }
- private static ToolTipControllerShowEventArgs CreateHoverTip()
- {
- ToolTipTitleItem titleItem1 = new ToolTipTitleItem() { Text = $"0千米" };
- titleItem1.Appearance.ForeColor = SystemColors.GrayText;
- titleItem1.Appearance.Font = new Font(AppearanceObject.DefaultFont.FontFamily, 12, FontStyle.Bold);
- SuperToolTip superToolTip = new SuperToolTip();
- superToolTip.Items.Add(titleItem1);
- ToolTipSeparatorItem sepItem = new ToolTipSeparatorItem();
- superToolTip.Items.Add(sepItem);
- ToolTipItem textItem = new ToolTipItem() { Text = "单击添加测距点,双击结束测距" };
- superToolTip.Items.Add(textItem);
- ToolTipControllerShowEventArgs arg = new ToolTipControllerShowEventArgs();
- arg.ShowBeak = true;
- arg.SuperTip = superToolTip;
- return arg;
- }
- private static void MapControl_MouseEnter(object sender, EventArgs e)
- {
- var innerData = (sender as MapControl).Tag as InnerData;
- innerData.hoverPoint.Visible = true;
- }
- private static void MapControl_MouseLeave(object sender, EventArgs e)
- {
- var innerData = (sender as MapControl).Tag as InnerData;
- innerData.hoverPoint.Visible = false;
- }
- private static void AddDistinctPoint(object sender, MouseEventArgs e)
- {
- var innerData = (sender as MapControl).Tag as InnerData;
- var ctrl = sender as MapControl;
- MapCallout disItem = new MapCallout { IsHitTestVisible = false, CanMove = false };
- disItem.Location = ctrl.ScreenPointToCoordPoint(e.Location);
- disItem.Text = $"{CalcLineKm(innerData):F2}千米";
- disItem.Tag = "DrawDistanceLine";
- innerData.mMapStorage.Items.Add(disItem);
- innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
- innerData.hoverPoint = new MapDot() { CanResize = false, CanMove = false, IsHitTestVisible = false, Tag = "DrawDistanceLine", Size = 8 };
- innerData.hoverPoint.Location = ctrl.ScreenPointToCoordPoint(e.Location);
- innerData.hoverPoint.Fill = ColorHelper.GetColor(innerData.hoverPoint.Tag.ToString());
- innerData.mMapStorage.Items.Add(innerData.hoverPoint);
- innerData.distinctPath.Points.Add(innerData.hoverPoint.Location);
- }
- private static void MovingDistinct(object sender, MouseEventArgs e)
- {
- var innerData = (sender as MapControl).Tag as InnerData;
- var ctrl = sender as MapControl;
- var itemPoint = ctrl.ScreenPointToCoordPoint(e.Location);
- innerData.hoverPoint.Location = itemPoint;
- if (innerData.distinctPath.Points.Count > 0)
- {
- ctrl.MapEditor.SetEditMode();
- innerData.distinctPath.Points[innerData.distinctPath.Points.Count - 1] = itemPoint;
- (innerData.hoverTip.SuperTip.Items[0] as ToolTipTitleItem).Text = $"{CalcLineKm(innerData):F2}千米";
- innerData.mapToolTip.ShowHint(innerData.hoverTip, ctrl.PointToScreen(e.Location));
- }
- }
- private static double CalcLineKm(InnerData data)
- {
- double result = 0;
- if (data.distinctPath.Points.Count < 2) return result;
- for (int i = 0; i < data.distinctPath.Points.Count - 1; i++)
- {
- var startPoint = data.distinctPath.Points[i] as GeoPoint;
- var endPoint = data.distinctPath.Points[i + 1] as GeoPoint;
- MapSize sizeInKm = new SphericalMercatorProjection().GeoToKilometersSize(startPoint, new MapSize(Math.Abs(startPoint.Longitude - endPoint.Longitude), Math.Abs(startPoint.Latitude - endPoint.Latitude)));
- double partlength = Math.Sqrt(sizeInKm.Width * sizeInKm.Width + sizeInKm.Height * sizeInKm.Height);
- result += partlength;
- }
- return result;
- }
- public static void ClearMap(this MapControl ctrl)
- {
- var innerData = ctrl.Tag as InnerData;
- innerData.CurrentRect = (0, 0, 0, 0, 0, 0, 0, 0);
- innerData.mMapStorage?.Items.Clear();
- }
- private static void EndDistinct(object sender, EventArgs e)
- {
- var ctrl = sender as MapControl;
- var innerData = ctrl.Tag as InnerData;
- innerData.mapToolTip.HideHint();
- ctrl.MouseClick -= AddDistinctPoint;
- ctrl.MouseMove -= MovingDistinct;
- ctrl.DoubleClick -= EndDistinct;
- ctrl.MouseLeave -= MapControl_MouseLeave;
- ctrl.MouseEnter -= MapControl_MouseEnter;
- }
- //度 转换成 弧度
- public static double DegreesToRadians(double degrees)
- {
- const double degToRadFactor = Math.PI / 180;
- return degrees * degToRadFactor;
- }
- //弧度 转换成 度
- public static double RadiansToDegrees(double radians)
- {
- const double radToDegFactor = 180 / Math.PI;
- return radians * radToDegFactor;
- }
- /**
- * 求B点经纬度
- * @param A 已知点的经纬度,
- * @param distance AB两地的距离 单位km
- * @param angle AB连线与正北方向的夹角(0~360)
- * @return B点的经纬度
- */
- private static MyLatLng getMyLatLng(MyLatLng A, double distance, double angle)
- {
- double dx = distance * 1000 * Math.Sin(DegreesToRadians(angle));
- double dy = distance * 1000 * Math.Cos(DegreesToRadians(angle));
- double bjd = (dx / A.Ed + A.m_RadLo) * 180 / Math.PI;
- double bwd = (dy / A.Ec + A.m_RadLa) * 180 / Math.PI;
- return new MyLatLng(bjd, bwd);
- }
- class MapEditPointView : DevExpress.XtraEditors.XtraForm
- {
- private System.ComponentModel.IContainer components = null;
- private DevExpress.XtraLayout.LayoutControl layoutControl1;
- private DevExpress.XtraLayout.LayoutControlGroup Root;
- private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
- private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
- private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
- private DevExpress.XtraEditors.ButtonEdit txtLon;
- private DevExpress.XtraEditors.ButtonEdit txtLat;
- private DevExpress.XtraEditors.TextEdit txtCaption;
- private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
- private DevExpress.XtraEditors.SimpleButton btnCancel;
- private DevExpress.XtraEditors.SimpleButton btnOk;
- private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
- private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
- private DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider dxErrorProvider1;
- private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions1 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject1 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject2 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject3 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject4 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions2 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject5 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject6 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject7 = new DevExpress.Utils.SerializableAppearanceObject();
- DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject8 = new DevExpress.Utils.SerializableAppearanceObject();
- this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
- this.txtCaption = new DevExpress.XtraEditors.TextEdit();
- this.txtLon = new DevExpress.XtraEditors.ButtonEdit();
- this.txtLat = new DevExpress.XtraEditors.ButtonEdit();
- this.Root = new DevExpress.XtraLayout.LayoutControlGroup();
- this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
- this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
- this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
- this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
- this.btnOk = new DevExpress.XtraEditors.SimpleButton();
- this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
- this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
- this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
- this.dxErrorProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(this.components);
- this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
- this.layoutControl1.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit();
- this.SuspendLayout();
- //
- // layoutControl1
- //
- this.layoutControl1.Controls.Add(this.btnCancel);
- this.layoutControl1.Controls.Add(this.btnOk);
- this.layoutControl1.Controls.Add(this.txtCaption);
- this.layoutControl1.Controls.Add(this.txtLon);
- this.layoutControl1.Controls.Add(this.txtLat);
- this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.layoutControl1.Location = new System.Drawing.Point(0, 0);
- this.layoutControl1.Name = "layoutControl1";
- this.layoutControl1.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(689, 0, 650, 400);
- this.layoutControl1.Root = this.Root;
- this.layoutControl1.Size = new System.Drawing.Size(272, 208);
- this.layoutControl1.TabIndex = 0;
- this.layoutControl1.Text = "layoutControl1";
- //
- // txtCaption
- //
- this.txtCaption.Location = new System.Drawing.Point(12, 29);
- this.txtCaption.Name = "txtCaption";
- this.txtCaption.Properties.Appearance.Options.UseTextOptions = true;
- this.txtCaption.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
- this.txtCaption.Properties.AutoHeight = false;
- this.txtCaption.Properties.MaxLength = 30;
- this.txtCaption.Size = new System.Drawing.Size(248, 22);
- this.txtCaption.StyleController = this.layoutControl1;
- this.txtCaption.TabIndex = 9;
- //
- // txtLon
- //
- this.txtLon.Location = new System.Drawing.Point(12, 80);
- this.txtLon.Name = "txtLon";
- this.txtLon.Properties.Appearance.Options.UseTextOptions = true;
- this.txtLon.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
- this.txtLon.Properties.AutoHeight = false;
- this.txtLon.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
- 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)});
- this.txtLon.Size = new System.Drawing.Size(248, 22);
- this.txtLon.StyleController = this.layoutControl1;
- this.txtLon.TabIndex = 4;
- //
- // txtLat
- //
- this.txtLat.Location = new System.Drawing.Point(12, 131);
- this.txtLat.Name = "txtLat";
- this.txtLat.Properties.Appearance.Options.UseTextOptions = true;
- this.txtLat.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
- this.txtLat.Properties.AutoHeight = false;
- this.txtLat.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
- 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)});
- this.txtLat.Size = new System.Drawing.Size(248, 22);
- this.txtLat.StyleController = this.layoutControl1;
- this.txtLat.TabIndex = 5;
- //
- // Root
- //
- this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
- this.Root.GroupBordersVisible = false;
- this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
- this.layoutControlItem1,
- this.emptySpaceItem1,
- this.layoutControlItem5,
- this.layoutControlItem2,
- this.layoutControlItem3,
- this.layoutControlItem6,
- this.emptySpaceItem2});
- this.Root.Name = "Root";
- this.Root.Size = new System.Drawing.Size(272, 208);
- this.Root.TextVisible = false;
- //
- // layoutControlItem1
- //
- this.layoutControlItem1.Control = this.txtLon;
- this.layoutControlItem1.Location = new System.Drawing.Point(0, 43);
- this.layoutControlItem1.MaxSize = new System.Drawing.Size(0, 51);
- this.layoutControlItem1.MinSize = new System.Drawing.Size(54, 51);
- this.layoutControlItem1.Name = "layoutControlItem1";
- this.layoutControlItem1.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
- this.layoutControlItem1.Size = new System.Drawing.Size(252, 51);
- this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.layoutControlItem1.Text = "经度";
- this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Top;
- this.layoutControlItem1.TextSize = new System.Drawing.Size(24, 14);
- //
- // emptySpaceItem1
- //
- this.emptySpaceItem1.AllowHotTrack = false;
- this.emptySpaceItem1.Location = new System.Drawing.Point(0, 162);
- this.emptySpaceItem1.MaxSize = new System.Drawing.Size(0, 26);
- this.emptySpaceItem1.MinSize = new System.Drawing.Size(104, 26);
- this.emptySpaceItem1.Name = "emptySpaceItem1";
- this.emptySpaceItem1.Size = new System.Drawing.Size(113, 26);
- this.emptySpaceItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
- //
- // layoutControlItem2
- //
- this.layoutControlItem2.Control = this.txtLat;
- this.layoutControlItem2.Location = new System.Drawing.Point(0, 94);
- this.layoutControlItem2.MaxSize = new System.Drawing.Size(0, 51);
- this.layoutControlItem2.MinSize = new System.Drawing.Size(54, 51);
- this.layoutControlItem2.Name = "layoutControlItem2";
- this.layoutControlItem2.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 2, 10, 2);
- this.layoutControlItem2.Size = new System.Drawing.Size(252, 51);
- this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.layoutControlItem2.Text = "纬度";
- this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Top;
- this.layoutControlItem2.TextSize = new System.Drawing.Size(24, 14);
- //
- // layoutControlItem5
- //
- this.layoutControlItem5.Control = this.txtCaption;
- this.layoutControlItem5.Location = new System.Drawing.Point(0, 0);
- this.layoutControlItem5.MaxSize = new System.Drawing.Size(0, 43);
- this.layoutControlItem5.MinSize = new System.Drawing.Size(54, 43);
- this.layoutControlItem5.Name = "layoutControlItem5";
- this.layoutControlItem5.Size = new System.Drawing.Size(252, 43);
- this.layoutControlItem5.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.layoutControlItem5.Text = "标题";
- this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Top;
- this.layoutControlItem5.TextSize = new System.Drawing.Size(24, 14);
- //
- // btnOk
- //
- this.btnOk.Location = new System.Drawing.Point(125, 174);
- this.btnOk.Name = "btnOk";
- this.btnOk.Size = new System.Drawing.Size(65, 22);
- this.btnOk.StyleController = this.layoutControl1;
- this.btnOk.TabIndex = 10;
- this.btnOk.Text = "确定";
- this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
- //
- // layoutControlItem3
- //
- this.layoutControlItem3.Control = this.btnOk;
- this.layoutControlItem3.Location = new System.Drawing.Point(113, 162);
- this.layoutControlItem3.MaxSize = new System.Drawing.Size(69, 26);
- this.layoutControlItem3.MinSize = new System.Drawing.Size(69, 26);
- this.layoutControlItem3.Name = "layoutControlItem3";
- this.layoutControlItem3.Size = new System.Drawing.Size(69, 26);
- this.layoutControlItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
- this.layoutControlItem3.TextVisible = false;
- //
- // btnCancel
- //
- this.btnCancel.Location = new System.Drawing.Point(194, 174);
- this.btnCancel.Name = "btnCancel";
- this.btnCancel.Size = new System.Drawing.Size(66, 22);
- this.btnCancel.StyleController = this.layoutControl1;
- this.btnCancel.TabIndex = 11;
- this.btnCancel.Text = "取消";
- this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
- //
- // layoutControlItem6
- //
- this.layoutControlItem6.Control = this.btnCancel;
- this.layoutControlItem6.Location = new System.Drawing.Point(182, 162);
- this.layoutControlItem6.MaxSize = new System.Drawing.Size(70, 26);
- this.layoutControlItem6.MinSize = new System.Drawing.Size(70, 26);
- this.layoutControlItem6.Name = "layoutControlItem6";
- this.layoutControlItem6.Size = new System.Drawing.Size(70, 26);
- this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
- this.layoutControlItem6.TextVisible = false;
- //
- // dxErrorProvider1
- //
- this.dxErrorProvider1.ContainerControl = this;
- //
- // emptySpaceItem2
- //
- this.emptySpaceItem2.AllowHotTrack = false;
- this.emptySpaceItem2.Location = new System.Drawing.Point(0, 145);
- this.emptySpaceItem2.MinSize = new System.Drawing.Size(104, 1);
- this.emptySpaceItem2.Name = "emptySpaceItem2";
- this.emptySpaceItem2.Size = new System.Drawing.Size(252, 17);
- this.emptySpaceItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
- this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
- //
- // MapEditPointView
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(272, 208);
- this.Controls.Add(this.layoutControl1);
- this.IconOptions.ShowIcon = false;
- this.MaximizeBox = false;
- this.MinimizeBox = false;
- this.Name = "MapEditPointView";
- this.ShowInTaskbar = false;
- this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
- this.Text = "标点";
- ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
- this.layoutControl1.ResumeLayout(false);
- ((System.ComponentModel.ISupportInitialize)(this.txtCaption.Properties)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.txtLon.Properties)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.txtLat.Properties)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit();
- this.ResumeLayout(false);
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- public MapEditPointView()
- {
- InitializeComponent();
- }
- public string Caption
- {
- get
- {
- return txtCaption.Text.Trim();
- }
- set
- {
- txtCaption.Text = value;
- }
- }
- public double Lon
- {
- get
- {
- return double.Parse(txtLon.Text.Trim());
- }
- set
- {
- txtLon.Text = value.ToString();
- }
- }
- public double Lat
- {
- get
- {
- return double.Parse(txtLat.Text.Trim());
- }
- set
- {
- txtLat.Text = value.ToString();
- }
- }
- private void btnOk_Click(object sender, EventArgs e)
- {
- dxErrorProvider1.ClearErrors();
- double lon, lat;
- if (!double.TryParse(txtLon.Text, out lon))
- {
- dxErrorProvider1.SetError(txtLon, "请设置正确的经度");
- return;
- }
- if (!double.TryParse(txtLat.Text, out lat))
- {
- dxErrorProvider1.SetError(txtLat, "请设置正确的纬度");
- return;
- }
- if (lon < -180 || lon > 180)
- {
- dxErrorProvider1.SetError(txtLon, "经度范围[-180,180]");
- return;
- }
- if (lat < -90 || lat > 90)
- {
- dxErrorProvider1.SetError(txtLat, "纬度范围[-90,90]");
- return;
- }
- this.DialogResult = DialogResult.OK;
- }
- private void btnCancel_Click(object sender, EventArgs e)
- {
- this.DialogResult = DialogResult.Cancel;
- }
- }
- #endregion
- //自定义经纬度类
- public class MyLatLng
- {
- public double Rc = 6378137; //赤道半径
- public double Rj = 6356725; //极半径
- public double m_LoDeg, m_LoMin, m_LoSec;
- public double m_LaDeg, m_LaMin, m_LaSec;
- public double m_Longitude, m_Latitude;
- public double m_RadLo, m_RadLa;
- public double Ec;
- public double Ed;
- public MyLatLng(double longitude, double latitude)
- {
- m_LoDeg = (int)longitude;
- m_LoMin = (int)((longitude - m_LoDeg) * 60);
- m_LoSec = (longitude - m_LoDeg - m_LoMin / 60) * 3600;
- m_LaDeg = (int)latitude;
- m_LaMin = (int)((latitude - m_LaDeg) * 60);
- m_LaSec = (latitude - m_LaDeg - m_LaMin / 60) * 3600;
- m_Longitude = longitude;
- m_Latitude = latitude;
- m_RadLo = longitude * Math.PI / 180;
- m_RadLa = latitude * Math.PI / 180;
- Ec = Rj + (Rc - Rj) * (90 - m_Latitude) / 90;
- Ed = Ec * Math.Cos(m_RadLa);
- }
- }
- #region ImageLayer数据源接口实现(本地和Http接口)
- class ImageTileSource : IImageTileSource
- {
- SQLiteConnection con;
- public ImageTileSource()
- {
- var files = Directory.GetFiles(Application.StartupPath, "Data.gmdb", SearchOption.AllDirectories);
- if (files.Length > 0)
- {
- try
- {
- conStr = string.Format(conStr, files[0]);
- con = new SQLiteConnection(conStr);
- con.Open();
- }
- catch
- {
- conStr = null;
- Console.WriteLine("Data.gmdb文件读取出错!");
- }
- }
- else
- {
- conStr = null;
- }
- }
- public string Name => "GMap地图瓦片";
- public bool CanDisposeSourceImage => true;
- public Image GetImage(int x, int y, int level, Size size)
- {
- var data = QueryTile(x, y, level, 0);
- if (data == null) return null;
- return Image.FromStream(new MemoryStream(data));
- }
- 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})";
- string conStr = "Data Source=\"{0}\";Page Size=32768";
- byte[] QueryTile(int x, int y, int zoom, int type)
- {
- if (conStr == null) return null;
- type = (int)mMapType;
- if (type == 0) type = 1818940751;
- using (DbCommand com = con.CreateCommand())
- {
- com.CommandText = string.Format(QuerySql, x, y, zoom, type);
- using (DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
- {
- if (rd.Read())
- {
- long length = rd.GetBytes(0, 0, null, 0, 0);
- byte[] tile = new byte[length];
- rd.GetBytes(0, 0, tile, 0, tile.Length);
- return tile;
- }
- }
- }
- return null;
- }
- }
- class HttpMapDataProvider : MapDataProviderBase
- {
- public HttpMapDataProvider()
- {
- TileSource = new HttpTileSource(this);
- }
- public override MapSize GetMapSizeInPixels(double zoomLevel)
- {
- double imageSize;
- imageSize = HttpTileSource.CalculateTotalImageSize(zoomLevel);
- return new MapSize(imageSize, imageSize);
- }
- protected override Size BaseSizeInPixels
- {
- get { return new Size(Convert.ToInt32(HttpTileSource.tileSize * 2), Convert.ToInt32(HttpTileSource.tileSize * 2)); }
- }
- }
- class HttpTileSource : MapTileSourceBase
- {
- public const int tileSize = 256;
- public const int maxZoomLevel = 14;
- public string HttpServerAddr { get; set; }
- public GoogleMapType MapType { get; set; } = GoogleMapType.Normal;
- internal static double CalculateTotalImageSize(double zoomLevel)
- {
- if (zoomLevel < 1.0)
- return zoomLevel * tileSize * 2;
- return Math.Pow(2.0, zoomLevel) * tileSize;
- }
- public HttpTileSource(ICacheOptionsProvider cacheOptionsProvider) :
- base((int)CalculateTotalImageSize(maxZoomLevel), (int)CalculateTotalImageSize(maxZoomLevel), tileSize, tileSize, cacheOptionsProvider)
- {
- }
- public override Uri GetTileByZoomLevel(int zoomLevel, int tilePositionX, int tilePositionY)
- {
- if (string.IsNullOrWhiteSpace(HttpServerAddr)) return null;
- try
- {
- if (zoomLevel <= maxZoomLevel)
- {
- string imgUrl = $"{HttpServerAddr}/{(int)MapType}/{zoomLevel}/{tilePositionX}/{tilePositionY}";
- //string imgUrl = string.Format("http://192.168.0.214:58089/{0}/{1}/{2}/{3}", (int)GoogleMapType.Normal, zoomLevel, tilePositionX, tilePositionY);
- Uri u = new Uri(imgUrl);
- return u;
- }
- return null;
- }
- catch
- {
- Console.WriteLine($"加载地图数据出错,无法连接到{HttpServerAddr}");
- return null;
- }
- }
- }
- #endregion
- //定位点聚合器
- class PosClusterer : IClusterer
- {
- private MapControl ctrl;
- private IMapDataAdapter owner;
- private MapViewport preViewPoint;
- private DebounceDispatcher dispatcher = new DebounceDispatcher();
- public bool IsBusy { get; private set; }
- public MapItemCollection Items { get; private set; }
- public PosClusterer(MapControl ctrl)
- {
- this.ctrl = ctrl;
- }
- public void SetOwner(IMapDataAdapter owner)
- {
- this.owner = owner;
- Items = new MapItemCollection(owner);
- }
- public void Clusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
- {
- IsBusy = true;
- if (sourceChanged)
- DoClusterize(sourceItems, viewport, sourceChanged);
- else
- dispatcher.Debounce(100, () => DoClusterize(sourceItems, viewport, sourceChanged));
- }
- private void DoClusterize(IEnumerable<MapItem> sourceItems, MapViewport viewport, bool sourceChanged)
- {
- if (preViewPoint == null)
- {
- preViewPoint = viewport;
- return;
- }
- if (!sourceChanged && preViewPoint.ZoomLevel == viewport.ZoomLevel)//地图移动或者MapControl大小发生了改变时直接操作Items避免闪烁
- {
- preViewPoint = viewport;
- }
- else//地图进行了缩放
- {
- Items.Clear();
- var cache = new Dictionary<int, List<MapItem>>();
- foreach (MapDot item in sourceItems)
- {
- var point = ctrl.CoordPointToScreenPoint(item.Location);
- int pointX = (int)point.X;
- int pointY = (int)point.Y;
- bool visible = true;
- if (pointX <= _dotSize || pointX > ctrl.Width - _dotSize)
- visible = false;
- else if (pointY <= _dotSize || pointY > ctrl.Height - _dotSize)
- visible = false;
- pointX /= (_dotSize * 2);
- pointY /= (_dotSize * 2);
- var key = pointX << 16 | pointY;
- if (!visible)
- key = -key;
- if (!cache.ContainsKey(key))
- cache.Add(key, new List<MapItem>());
- cache[key].Add(item);
- }
- var innerData = ctrl.Tag as InnerData;
- innerData._clusterCache.Clear();
- LinkedList<MapItem> temp = new LinkedList<MapItem>();
- foreach (var kv in cache)
- {
- var firstDot = kv.Value[0] as MapDot;
- var firstObj = firstDot.Tag as PosData;
- firstDot.Size = kv.Value.Count > 1 ? _dotSize + 2 : _dotSize;
- firstObj.ClusterCount = kv.Value.Count;
- firstObj.ClusterKey = kv.Key;
- innerData._clusterCache.Add(kv.Key, firstDot);
- temp.AddLast(firstDot);
- }
- Items.AddRange(temp);
- cache.Clear();
- preViewPoint = viewport;
- owner.OnClustered();
- }
- this.IsBusy = false;
- }
- //计算多个坐标的中心位置
- public GeoPoint GetCenterPointFromListOfCoordinates(List<MapItem> geoCoordinateList)
- {
- int total = geoCoordinateList.Count;
- double lat = 0, lon = 0;
- foreach (MapDot g in geoCoordinateList)
- {
- lat += (g.Location as GeoPoint).Latitude * Math.PI / 180;
- lon += (g.Location as GeoPoint).Longitude * Math.PI / 180;
- }
- lat /= total;
- lon /= total;
- return new GeoPoint(lat * 180 / Math.PI, lon * 180 / Math.PI);
- }
- }
- }
|