/// <summary> /// Saves places to a file in GPX format, given pathname /// </summary> /// <param name="strGpxPath">The file (with full path) to save to</param> public void SaveToGpx(string strGpxPath) { gpxType gpx = new gpxType(); gpx.creator = "NASA World Wind"; gpx.version = "1.1"; gpx.wpt = new wptType [this.Items.Count]; int i = 0; foreach (ListViewItem lvi in this.Items) { PlaceItem pi = (PlaceItem)lvi.Tag; wptType wp = new wptType(); wp.name = pi.pn.Name; wp.lat = (decimal)pi.pn.Lat; wp.lon = (decimal)pi.pn.Lon; wp.sym = "Waypoint"; gpx.wpt[i++] = wp; } XmlSerializer ser = new XmlSerializer(typeof(gpxType)); TextWriter tw = new StreamWriter(strGpxPath); ser.Serialize(tw, gpx); tw.Close(); }
private Coordinate CreateGeoPosition(wptType wayPoint) { double lat = (double)wayPoint.lat; double lon = (double)wayPoint.lon; return(wayPoint.eleSpecified ? new Coordinate(lon, lat, (double)wayPoint.ele) : new Coordinate(lon, lat)); }
private static wptType SaveTrackPoint(TrackPoint point) { wptType wp = new wptType(); if (point.AgeOfGpsData.HasValue) { wp.ageofdgpsdataSpecified = true; wp.ageofdgpsdata = point.AgeOfGpsData.Value; } wp.cmt = point.Comment; wp.desc = point.Description; wp.dgpsid = point.DgpsId; if (point.Elevation.HasValue) { wp.eleSpecified = true; wp.ele = (decimal)point.Elevation.Value; } if (false == String.IsNullOrEmpty(point.FixType)) { wp.fixSpecified = true; wp.fix = (fixType)Enum.Parse(typeof(fixType), point.FixType); } if (point.GeoidHeight.HasValue) { wp.geoidheightSpecified = true; wp.geoidheight = point.GeoidHeight.Value; } if (point.HorizontalDilutionOfPrecision.HasValue) { wp.hdopSpecified = true; wp.hdop = point.HorizontalDilutionOfPrecision.Value; } wp.lon = (decimal)point.Location.X; wp.lat = (decimal)point.Location.Y; wp.name = point.Name; if (point.MagneticVariation.HasValue) { wp.magvarSpecified = true; wp.magvar = point.MagneticVariation.Value; } if (point.PositionDilutionOfPrecision.HasValue) { wp.pdopSpecified = true; wp.pdop = point.PositionDilutionOfPrecision.Value; } wp.src = point.SourceOfData; wp.sym = point.Symbol; if (point.Time.HasValue) { wp.timeSpecified = true; wp.time = point.Time.Value; } if (point.VerticalDilutionOfPrecision.HasValue) { wp.vdopSpecified = true; wp.vdop = point.VerticalDilutionOfPrecision.Value; } return(wp); }
private int GetDistance(wptType startPoint, wptType point) { var startIndex = _wayPoints.IndexOf(startPoint); var lastIndex = _wayPoints.IndexOf(point); var distance = _distances.Skip(startIndex).Take(lastIndex - startIndex).Sum() / 1000; return((int)distance); }
public override void delete() { if (Parent != null && Parent is GpxTrackSegmentModel trackSegmentModel && trackSegmentModel.Trackpoints != null) { trackSegmentModel.Trackpoints.Remove(this); } Trackpoint = null; }
private LatLng ToLatLng(wptType point) { return(new LatLng { Lat = (double)point.lat, Lng = (double)point.lon, Alt = (double)point.ele }); }
private MarkerData ToMarkerData(wptType point) { return(new MarkerData { Latlng = ToLatLng(point), Title = point.name, Type = point.type }); }
public void WayPoint_Cast_To_WptType() { var waypoint = new WayPoint(); waypoint.Name = "mannus"; wptType wpt = waypoint; wpt.name.Should().Be("mannus"); }
static private TrackPoint ReadTrackPoint(wptType wptType) { TrackPoint waypoint = new TrackPoint(); if (wptType.ageofdgpsdataSpecified) { waypoint.AgeOfGpsData = wptType.ageofdgpsdata; } waypoint.Comment = wptType.cmt; waypoint.Description = wptType.desc; waypoint.DgpsId = wptType.dgpsid; if (wptType.eleSpecified) { waypoint.Elevation = (double)wptType.ele; } if (wptType.fixSpecified) { waypoint.FixType = wptType.fix.ToString(); } if (wptType.geoidheightSpecified) { waypoint.GeoidHeight = wptType.geoidheight; } if (wptType.hdopSpecified) { waypoint.HorizontalDilutionOfPrecision = wptType.hdop; } waypoint.Location = new Point2 <double>((double)wptType.lon, (double)wptType.lat); if (wptType.magvarSpecified) { waypoint.MagneticVariation = wptType.magvar; } waypoint.Name = wptType.name; if (wptType.pdopSpecified) { waypoint.PositionDilutionOfPrecision = wptType.pdop; } //wptType.sat; waypoint.SourceOfData = wptType.src; waypoint.Symbol = wptType.sym; if (wptType.timeSpecified) { waypoint.Time = wptType.time; } //wptType.type; if (wptType.vdopSpecified) { waypoint.VerticalDilutionOfPrecision = wptType.vdop; } if (wptType.timeSpecified) { waypoint.Time = wptType.time; } return(waypoint); }
public override GpxModel clone() { GpxTrackpointModel newModel = null; wptType trkpt = (wptType)Trackpoint.Clone(); if (trkpt != null) { newModel = new GpxTrackpointModel(null, trkpt); } return(newModel); }
private BikeTouringGISGraphic CreateBikeTouringGISPointGraphic(wptType location, string nameAttribute, GraphicType typeOfPoint) { var mappoint = new MapPoint((double)location.lon, (double)location.lat, new SpatialReference(4326)); var g = new BikeTouringGISGraphic(mappoint, typeOfPoint) { ZIndex = 1 }; g.Attributes["name"] = nameAttribute; return(g); }
public GpxTrackpointModel(GpxModel parent, wptType wpt) { Parent = parent; if (wpt == null) { Trackpoint = new wptType(); Trackpoint.name = "New Trackpoint"; } else { Trackpoint = wpt; } }
public GpxWaypointModel(GpxModel parent, wptType wpt) { Parent = parent; if (wpt == null) { Waypoint = new wptType(); Waypoint.name = "New Waypoint"; } else { Waypoint = wpt; } }
private void gpx_save_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "GPX file|*.gpx"; saveFileDialog1.Title = "Save To GPX File"; saveFileDialog1.ShowDialog(); // If the file name is not an empty string open it for saving. if (saveFileDialog1.FileName != "") { GpxClass track = new GpxClass(); wptTypeCollection trkpt = new wptTypeCollection(); foreach (Location lc in gpx_locations) { wptType wpt = new wptType(); wpt.lat = (decimal)lc.Latitude; wpt.lon = (decimal)lc.Longitude; wpt.ele = (decimal)lc.Altitude; wpt.eleSpecified = true; trkpt.Add(wpt); } trksegType trk_seg = new trksegType(); trk_seg.trkpt = trkpt; trksegTypeCollection trk_seg_cl = new trksegTypeCollection(); trk_seg_cl.Addtrkseg(trk_seg); trkType trk = new trkType(); trk.name = DateTime.Now.ToString("MM/dd/yyyy h:mm tt"); trk.trkseg = trk_seg_cl; track.trk = new trkTypeCollection(); track.trk.Add(trk); track.ToFile(saveFileDialog1.FileName); System.Windows.Forms.MessageBox.Show("GPX file is saved!"); // back to the teleport mode. cur_click_mode = e_click_mode.teleport; gpx_create_button.Content = "Create GPX"; way_points.Text = ""; gpx_locations.Clear(); myMap.Children.Clear(); gpx_save_button.IsEnabled = false; } }
private MarkerData ToMarkerData(wptType point) { return(new MarkerData { Latlng = ToLatLng(point), Title = point.name, Type = point.type, Description = point.desc, Urls = (point.link ?? new linkType[0]) .Select(l => new LinkData { MimeType = l.type, Url = l.href, Text = l.text }) .ToList() }); }
private static wptType ReadWayPoint( XElement element ) { element.RequireArgument<XElement>( "element" ).NotNull<XElement>(); XNamespace ns = element.Name.Namespace; wptType wpt = new wptType(); wpt.lat = Convert.ToDecimal(element.Attribute("lat").Value); wpt.lon = Convert.ToDecimal(element.Attribute("lon").Value); if( element.Element( ns + "ele" ) != null ) wpt.ele = Convert.ToDecimal(element.Element( ns + "ele" ).Value); if( element.Element( ns + "time" ) != null ) wpt.time = Convert.ToDateTime(element.Element( ns + "time").Value); if( element.Element( ns + "magvar" ) != null ) wpt.magvar = Convert.ToDecimal(element.Element( ns + "magvar").Value); if( element.Element( ns + "geoidheight" ) != null ) wpt.geoidheight = Convert.ToDecimal(element.Element( ns + "geoidheight").Value); if( element.Element( ns + "name" ) != null ) wpt.name = element.Element( ns + "name" ).Value; if( element.Element( ns + "cmt" ) != null ) wpt.cmt = element.Element(ns + "cmt" ).Value; if( element.Element( ns + "desc" ) != null ) wpt.desc = element.Element( ns + "desc" ).Value; if( element.Element( ns + "src" ) != null ) wpt.src = element.Element( ns + "src" ).Value; if( element.Element( ns + "link" ) != null ) wpt.link = ReadLinks(element.Elements( ns + "link")); if( element.Element( ns + "sym" ) != null ) wpt.sym = element.Element( ns + "sym" ).Value; if( element.Element( ns + "type" ) != null ) wpt.type = element.Element( ns + "type" ).Value; if( element.Element( ns + "fix" ) != null ) wpt.fix = ReadFix( element.Element( ns + "fix" ) ); if( element.Element( ns + "sat" ) != null ) wpt.sat = element.Element( ns + "sat" ).Value; if( element.Element( ns + "hdop" ) != null ) wpt.hdop = Convert.ToDecimal(element.Element( ns + "hdop").Value); if( element.Element( ns + "vdop" ) != null ) wpt.vdop = Convert.ToDecimal(element.Element(ns + "vdop").Value); if( element.Element( ns + "pdop" ) != null ) wpt.pdop = Convert.ToDecimal(element.Element( ns + "pdop").Value); if( element.Element( ns + "ageofdgpsdata" ) != null ) wpt.ageofdgpsdata = Convert.ToDecimal(element.Element( ns + "ageofdgpsdata").Value); if( element.Element( ns + "dgpsid" ) != null ) wpt.dgpsid = element.Element( ns + "dgpsid" ).Value; //Ignore the extensions return wpt; }
public static Stream ExportGpxRouteStream(IList <GlobalsatRoute> routes) { if (routes == null) { return(null); } gpxType gpxFile = new gpxType(); //gpxFile.creator = "SportTracks KeymazePlugin"; List <rteType> rtes = new List <rteType>(); if (routes != null && routes.Count > 0) { foreach (GlobalsatRoute route in routes) { if (route.wpts != null && route.wpts.Count > 0) { rteType rte = new rteType(); rte.name = route.Name; List <wptType> wpts = new List <wptType>(); foreach (GlobalsatWaypoint g in route.wpts) { wptType wpt = new wptType(); wpt.lat = (decimal)g.Latitude; wpt.lon = (decimal)g.Longitude; wpt.ele = g.Altitude; wpt.eleSpecified = true; wpts.Add(wpt); } rte.rtept = wpts.ToArray(); rtes.Add(rte); } } } gpxFile.rte = rtes.ToArray(); XmlSerializer serializer = new XmlSerializer(gpxFile.GetType()); Stream writer = new MemoryStream(); serializer.Serialize(writer, gpxFile); //writer.Close(); return(writer); }
static void Main() { try { // read a file GpxClass gpx = GpxClass.FromFile("Files\\All Buntzen Trails.gpx"); gpx.rte.ForEach(x => Console.WriteLine("Route: {0}\r\n", x.name)); gpx.wpt.ForEach(x => Console.WriteLine("Waypoint: {0}\r\n", x.name)); gpx.trk.ForEach(x => Console.WriteLine("Track: {0}\r\n", x.name)); // create a new file GpxClass newGpx = new GpxClass() { creator = WindowsIdentity.GetCurrent().Name, version = "Test", wpt = new wptTypeCollection(), }; wptType waypoint = new wptType() { name = "Test Waypoint", cmt = "Comment", desc = "Description", lat = (Decimal)49.3402360, lon = (Decimal)(-122.8770030), time = DateTime.Now, timeSpecified = true, sym = "Waypoint", }; newGpx.wpt.Add(waypoint); newGpx.ToFile("Test.gpx"); CreateTrack(); } catch (Exception ex) { Console.WriteLine("Error processing file:\r\n{0}", ex); } }
public static List <wptType> GetWayPoints(this Geometry geometry) { var wayPoints = new List <wptType>(); if (geometry.GeometryType == GeometryType.Polyline) { var line = geometry as Polyline; foreach (var part in line.Parts) { foreach (var point in part.GetPoints()) { var wpt = new wptType(); wpt.lat = (decimal)point.Y; wpt.lon = (decimal)point.X; wayPoints.Add(wpt); } } } return(wayPoints); }
private static double?GetGarminHeartRateFromWaypoint(wptType wpt) { if (wpt.extensions != null && wpt.extensions.Any != null) { foreach (var element in wpt.extensions.Any) { if (element.NamespaceURI == garminTrackPointExtensionsURI && element.LocalName == "TrackPointExtension") { foreach (XmlNode subElement in element.GetElementsByTagName("hr", garminTrackPointExtensionsURI)) { double hr; if (double.TryParse(subElement.InnerText, out hr)) { return(hr); } } } } } return(null); }
public static Stream ExportGpxWaypointsStream(IList <GlobalsatWaypoint> waypoints) { if (waypoints == null) { return(null); } gpxType gpxFile = new gpxType(); //gpxFile.creator = "SportTracks KeymazePlugin"; List <wptType> wptList = new List <wptType>(); if (waypoints != null && waypoints.Count > 0) { foreach (GlobalsatWaypoint waypoint in waypoints) { wptType wpt = new wptType(); wpt.name = waypoint.WaypointName; wpt.lat = (decimal)waypoint.Latitude; wpt.lon = (decimal)waypoint.Longitude; wpt.ele = (decimal)waypoint.Altitude; wpt.eleSpecified = true; wpt.type = waypoint.IconNr.ToString(); wptList.Add(wpt); } } gpxFile.wpt = wptList.ToArray(); XmlSerializer serializer = new XmlSerializer(gpxFile.GetType()); Stream writer = new MemoryStream(); serializer.Serialize(writer, gpxFile); //writer.Close(); return(writer); }
/* private void ImportGPX10() { if (BeginWork != null) BeginWork(this, new EventArgs()); NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; XmlTextReader sr = new XmlTextReader(fileName); XmlSerializer xSerializer = new XmlSerializer(typeof(gpx10Type)); gpx10Type gpx = (gpx10Type)xSerializer.Deserialize(sr); sr.Close(); XmlNamespaceManager nsManager = new XmlNamespaceManager(sr.NameTable); nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); importResult = new ImportResult(); // route List<RouteSegment> routeSegments = new List<RouteSegment>(); foreach (gpxTrk trk in gpx.trk) { for (int i = trk.trkseg.GetLowerBound(0); i <= trk.trkseg.GetUpperBound(0); i++) { RouteSegment routeSegment = new RouteSegment(); for (int j = trk.trkseg.GetLowerBound(1); j <= trk.trkseg.GetUpperBound(1); j++) { gpxTrkTrksegTrkpt wpt = trk.trkseg[i][j]; double lat = (double)wpt.lat; double lon = (double)wpt.lon; DateTime time = wpt.time; double? heartRate = null; double? altitude = null; routeSegment.Waypoints.Add(new Waypoint(time, new LongLat(lon, lat), altitude, heartRate)); } routeSegments.Add(routeSegment); } } importResult.Route = new Route(routeSegments); // laps LapCollection laps = new LapCollection(); importResult.Laps = laps; if (EndWork != null) EndWork(this, new EventArgs()); } */ private void ImportGPX11() { ImportResult = new ImportResult(); var isGPX10 = (GPXUtil.GetGPXVersion(fileName) == GPXVersion.GPX10); string gpx10convertedFileName = null; string polarConvertedFileName = null; var originalFileName = fileName; if (BeginWork != null) BeginWork(this, new EventArgs()); // check if the file is in gpx 1.0 format and convert it to gpx 1.1 if necessary if (isGPX10) { gpx10convertedFileName = Path.GetTempFileName(); GPXUtil.ConvertGPX10ToGPX11(fileName, gpx10convertedFileName); fileName = gpx10convertedFileName; } // check if the file is an invalid Polar ProTrainer file and correct if necessary if (PolarProTrainerUtil.IsPolarProTrainerGPXFile(fileName)) { polarConvertedFileName = Path.GetTempFileName(); PolarProTrainerUtil.CorrectPolarProTrainerGPXFile(fileName, polarConvertedFileName); fileName = polarConvertedFileName; } var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." }; var sr = new XmlTextReader(fileName); var xSerializer = new XmlSerializer(typeof(gpx11Type)); var gpx11 = (gpx11Type)xSerializer.Deserialize(sr); sr.Close(); var nsManager = new XmlNamespaceManager(sr.NameTable); // add namespace for split times and heart rates (from SportsTracks software) nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); // add namespace for map reading information (QuickRoute native) nsManager.AddNamespace("mr", "http://www.matstroeng.se/quickroute/map-reading"); // pre-store heart rates in dictionary (if present) var heartRates = new Dictionary<DateTime, double>(); // pre-store map-readings in map reading collection (if present) var mapReadings = new List<DateTime>(); if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:heartRateTrack/st:heartRate[@time and @bpm]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { DateTime time; double bpm; if (DateTime.TryParse(node.Attributes["time"].Value, out time) && double.TryParse(node.Attributes["bpm"].Value, NumberStyles.Any, nfi, out bpm)) { time = time.ToUniversalTime(); if(!heartRates.ContainsKey(time)) heartRates.Add(time, bpm); } } } } if(element.Name == "mr:map-reading") { DateTime start, end; if (DateTime.TryParse(element.Attributes["start"].Value, out start) && DateTime.TryParse(element.Attributes["end"].Value, out end)) { mapReadings.Add(start.ToUniversalTime()); mapReadings.Add(end.ToUniversalTime()); } } } } mapReadings = FilterMapReadings(mapReadings); // QuickRoute route var noOfWaypoints = 0; var noOfWaypointsWithTimes = 0; var routeSegments = new List<RouteSegment>(); // first use GPX track if (gpx11.trk != null) { foreach (var trk in gpx11.trk) { foreach (var trkseg in trk.trkseg) { var routeSegment = new RouteSegment(); wptType lastWpt = null; if (trkseg.trkpt != null) { foreach (var wpt in trkseg.trkpt) { if (lastWpt == null || wpt.time != lastWpt.time) { if (wpt.extensions != null && wpt.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double)wpt.lat; var lon = (double)wpt.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(wpt.time)) heartRate = heartRates[wpt.time]; if (wpt.eleSpecified) { altitude = (double?)wpt.ele; } if (wpt.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(wpt.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; lastWpt = wpt; } } noOfWaypoints++; } } } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } } // if no GPX track - use GPX route if (noOfWaypointsWithTimes == 0 && gpx11.rte != null) { foreach (var route in gpx11.rte) { var routeSegment = new RouteSegment(); foreach (var rtept in route.rtept) { if (rtept.extensions != null && rtept.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double) rtept.lat; var lon = (double) rtept.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(rtept.time)) heartRate = heartRates[rtept.time]; if (rtept.eleSpecified) { altitude = (double?) rtept.ele; } if (rtept.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(rtept.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; } } noOfWaypoints++; } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } // add map reading waypoints routeSegments = Route.AddMapReadingWaypoints(routeSegments, mapReadings); importResult.Succeeded = (noOfWaypointsWithTimes > 0); if (ImportResult.Succeeded) { importResult.Route = new Route(routeSegments); // laps var laps = new LapCollection(); var startTime = ImportResult.Route.FirstWaypoint.Time; // from GPX st:split if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:splits/st:split[@time]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { var elapsedTime = double.Parse(node.Attributes["time"].Value, nfi); var lap = new Lap(startTime.AddSeconds(elapsedTime), LapType.Lap); laps.Add(lap); } } } } } // from GPX waypoints if (gpx11.wpt != null && laps.Count == 0) { foreach (var waypoint in gpx11.wpt) { if (waypoint.timeSpecified) { laps.Add(new Lap(waypoint.time, LapType.Lap)); } } } foreach (var rs in routeSegments) { laps.Add(new Lap(rs.FirstWaypoint.Time, LapType.Start)); laps.Add(new Lap(rs.LastWaypoint.Time, LapType.Stop)); } importResult.Laps = laps; } else { if (noOfWaypoints == 0) { importResult.Error = ImportError.NoWaypoints; } else if (noOfWaypointsWithTimes == 0) { importResult.Error = ImportError.NoWaypointTimes; } } if (gpx10convertedFileName != null) { File.Delete(gpx10convertedFileName); fileName = originalFileName; } if (polarConvertedFileName != null) { File.Delete(polarConvertedFileName); fileName = originalFileName; } // import Polar HRM file with same base file name as the gpx file, if existing string hrmFileName = new FileInfo(fileName).FullName.Replace(new FileInfo(fileName).Extension, ".hrm"); if(File.Exists(hrmFileName)) { new PolarHRMImporter().AddLapsAndHRData(hrmFileName, importResult); } if (EndWork != null) EndWork(this, new EventArgs()); }
public void Export() { var writerSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, IndentChars = " " }; var writer = XmlWriter.Create(OutputStream, writerSettings); var xmlSerializer = new XmlSerializer(typeof(gpx11Type)); var stNs = "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"; var mrNs = "http://www.matstroeng.se/quickroute/map-reading"; var ns = new XmlSerializerNamespaces(); ns.Add("st", stNs); if (Session.Route.ContainsWaypointAttribute(WaypointAttribute.MapReadingDuration)) { ns.Add("mr", mrNs); } var xml = new XmlDocument(); var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; var gpx11 = new gpx11Type(); gpx11.creator = "QuickRoute"; gpx11.trk = new trkType[] { new trkType() }; gpx11.extensions = new extensionsType(); var extensionElements = new List <XmlElement>(); // TODO: add map-reading elements if exists XmlElement activityElement = xml.CreateElement("st", "activity", stNs); extensionElements.Add(activityElement); XmlElement heartRateTrackElement = xml.CreateElement("st", "heartRateTrack", stNs); activityElement.AppendChild(heartRateTrackElement); var trksegs = new List <trksegType>(); foreach (var rs in Session.Route.Segments) { var wpts = new List <wptType>(); foreach (var w in rs.Waypoints) { var wpt = new wptType(); wpt.eleSpecified = (w.Altitude != null); if (wpt.eleSpecified) { wpt.ele = (decimal)w.Altitude; } wpt.lon = (decimal)w.LongLat.Longitude; wpt.lat = (decimal)w.LongLat.Latitude; wpt.time = w.Time.ToUniversalTime(); // use ToUniversalTime for backwards compatibility, QR <= v2.2 used local time internally wpt.timeSpecified = true; wpts.Add(wpt); if (w.HeartRate.HasValue) { // add heartrate var heartRateElement = xml.CreateElement("st", "heartRate", stNs); var timeAttribute = xml.CreateAttribute("time"); timeAttribute.Value = w.Time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"); // use ToUniversalTime for backwards compatibility, QR <= v2.2 used local time internally var bpmAttribute = xml.CreateAttribute("bpm"); bpmAttribute.Value = w.HeartRate.Value.ToString(nfi); heartRateElement.Attributes.Append(timeAttribute); heartRateElement.Attributes.Append(bpmAttribute); heartRateTrackElement.AppendChild(heartRateElement); } } var trkseg = new trksegType { trkpt = wpts.ToArray() }; trksegs.Add(trkseg); } gpx11.trk[0].trkseg = trksegs.ToArray(); // add laps as GPX st:split var splitsElement = xml.CreateElement("st", "splits", stNs); // first distances foreach (var lap in Session.Laps) { if (lap.LapType == LapType.Lap) { var splitElement = xml.CreateElement("st", "split", stNs); var distanceAttribute = xml.CreateAttribute("distance"); distanceAttribute.Value = Session.Route.GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, Session.Route.GetParameterizedLocationFromTime(lap.Time)).Value.ToString(nfi); splitElement.Attributes.Append(distanceAttribute); splitsElement.AppendChild(splitElement); } } // then times foreach (var lap in Session.Laps) { if (lap.LapType == LapType.Lap) { var splitElement = xml.CreateElement("st", "split", stNs); var timeAttribute = xml.CreateAttribute("time"); timeAttribute.Value = lap.Time.Subtract(Session.Route.FirstWaypoint.Time).TotalSeconds.ToString(nfi); splitElement.Attributes.Append(timeAttribute); splitsElement.AppendChild(splitElement); } } if (splitsElement.ChildNodes.Count > 0) { activityElement.AppendChild(splitsElement); } // add laps as GPX waypoint elements var lapWaypoints = new List <wptType>(); foreach (var lap in Session.Laps) { if (lap.LapType == LapType.Lap) { var wpt = new wptType(); wpt.time = lap.Time; wpt.timeSpecified = true; var qrWaypoint = session.Route.CreateWaypointFromTime(lap.Time); wpt.lat = (decimal)qrWaypoint.LongLat.Latitude; wpt.lon = (decimal)qrWaypoint.LongLat.Longitude; if (qrWaypoint.Altitude.HasValue) { wpt.ele = (decimal)qrWaypoint.Altitude.Value; wpt.eleSpecified = true; } wpt.name = string.Format(Strings.LapX, lapWaypoints.Count + 1); lapWaypoints.Add(wpt); } } if (lapWaypoints.Count > 0) { gpx11.wpt = lapWaypoints.ToArray(); } // map reading if (Session.Route.ContainsWaypointAttribute(WaypointAttribute.MapReadingDuration)) { var mapReadingsList = Session.Route.GetMapReadingsList(); for (var i = 0; i < mapReadingsList.Count; i += 2) { var mapReadingElement = xml.CreateElement("mr", "map-reading", mrNs); mapReadingElement.SetAttribute("start", mapReadingsList[i].ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); mapReadingElement.SetAttribute("end", mapReadingsList[i + 1].ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); extensionElements.Add(mapReadingElement); } } gpx11.extensions.Any = extensionElements.ToArray(); xmlSerializer.Serialize(writer, gpx11, ns); writer.Close(); }
public static MapPoint LoadWayPointGeometry( wptType wpt ) { wpt.RequireArgument<wptType>( "wpt" ).NotNull<wptType>(); return new MapPoint( ( double ) wpt.lon, ( double ) wpt.lat ); }
public static IDictionary<string, object> LoadWayPointAttributes( wptType wpt, IDictionary<string, object> attributes ) { wpt.RequireArgument<wptType>( "wpt" ).NotNull<wptType>(); attributes.RequireArgument<IDictionary<string, object>>( "attributes" ).NotNull<IDictionary<string, object>>(); attributes.Add( "ele", wpt.ele ); attributes.Add( "time", wpt.time ); attributes.Add( "magvar", wpt.magvar ); attributes.Add( "geoidheight", wpt.geoidheight ); attributes.Add( "name", wpt.name ); attributes.Add( "cmt", wpt.cmt ); attributes.Add( "desc", wpt.desc ); attributes.Add( "src", wpt.src ); attributes.Add( "link", wpt.link ); attributes.Add( "sym", wpt.sym ); attributes.Add( "type", wpt.type ); attributes.Add( "fix", wpt.fix ); attributes.Add( "sat", wpt.sat ); attributes.Add( "hdop", wpt.hdop ); attributes.Add( "vdop", wpt.vdop ); attributes.Add( "pdop", wpt.pdop ); attributes.Add( "ageofdgpsdata", wpt.ageofdgpsdata ); attributes.Add( "dgpsid", wpt.dgpsid ); return attributes; }
/// <summary> /// Saves the route to a gpx file. /// </summary> /// <param name="file"></param> /// <param name="route"></param> internal static void Save(Stream stream, Route route) { XmlStreamSource source = new XmlStreamSource(stream); GpxDocument output_document = new GpxDocument(source); gpxType output_gpx = new gpxType(); output_gpx.trk = new trkType[1]; // initialize all objects. List <wptType> segments = new List <wptType>(); trkType track = new trkType(); List <wptType> poi_gpx = new List <wptType>(); track.trkseg = new trksegType[1]; // ============= CONSTRUCT TRACK SEGMENT ============== trksegType track_segment = new trksegType(); // loop over all points. for (int idx = 0; idx < route.Entries.Length; idx++) { // get the current entry. RoutePointEntry entry = route.Entries[idx]; // ================== INITIALIZE A NEW SEGMENT IF NEEDED! ======== wptType waypoint; if (entry.Points != null) { // loop over all points and create a waypoint for each. for (int p_idx = 0; p_idx < entry.Points.Length; p_idx++) { RoutePoint point = entry.Points[p_idx]; waypoint = new wptType(); waypoint.lat = (decimal)point.Latitude; waypoint.lon = (decimal)point.Longitude; waypoint.name = point.Name; poi_gpx.Add(waypoint); } } // insert poi's. double longitde = entry.Longitude; double latitude = entry.Latitude; waypoint = new wptType(); waypoint.lat = (decimal)entry.Latitude; waypoint.lon = (decimal)entry.Longitude; segments.Add(waypoint); } // put the segment in the track. track_segment.trkpt = segments.ToArray(); track.trkseg[0] = track_segment; // set the track to the output. output_gpx.trk[0] = track; output_gpx.wpt = poi_gpx.ToArray(); // save the ouput. output_document.Gpx = output_gpx; output_document.Save(); }
public string ToXmlString() { GpxClass gpx = new GpxClass() { creator = "Blue Diamond", trk = new trkTypeCollection() }; trkType track = new trkType() { name = Name, }; track.trkseg = new trksegTypeCollection(); trksegType segment = new trksegType() { trkpt = new wptTypeCollection() }; track.trkseg.Add(segment); foreach(var pt in this.Points) { wptType wpt = new wptType() { lat = (decimal)pt.Latitude, lon = (decimal)pt.Longitude, ele = (decimal)pt.Altitude, eleSpecified = true, time = pt.TimeStamp, }; segment.trkpt.Add(wpt); } gpx.trk.Add(track); try { var gpx11 = ToGpx1_1(gpx); XmlSerializer serializer = new XmlSerializer(gpx11.GetType()); Utf8StringWriter sw = new Utf8StringWriter(); serializer.Serialize(sw, gpx11); return sw.ToString(); } catch (Exception ex) { Trace.TraceError("error serializing:\r\n{0}",ex); return null; } //return gpx.ToXml(); }
/// <summary> /// Saves places to a file in GPX format, given pathname /// </summary> /// <param name="strGpxPath">The file (with full path) to save to</param> public void SaveToGpx(string strGpxPath) { gpxType gpx = new gpxType(); gpx.creator = "NASA World Wind"; gpx.version = "1.1"; gpx.wpt = new wptType [this.Items.Count]; int i = 0; foreach(ListViewItem lvi in this.Items) { PlaceItem pi = (PlaceItem)lvi.Tag; wptType wp = new wptType(); wp.name = pi.pn.Name; wp.lat = (decimal)pi.pn.Lat; wp.lon = (decimal)pi.pn.Lon; wp.sym = "Waypoint"; gpx.wpt[i++] = wp; } XmlSerializer ser = new XmlSerializer(typeof(gpxType)); TextWriter tw = new StreamWriter(strGpxPath); ser.Serialize(tw, gpx); tw.Close(); }
/// <summary> /// todo - both of these fxns should return lists and should jitter the point by a fixed amount determined by the accuracy to account for points that are right on an edge. /// </summary> /// <param name="point"></param> /// <returns></returns> public static string GetLocationCode(wptType point) { return(GetLocationCode(Convert.ToDouble(point.lat), Convert.ToDouble(point.lon))); }
private LatLngZ ToLatLngZ(wptType point) { return new LatLngZ { lat = (double)point.lat, lng = (double)point.lon, z = (double)point.ele }; }
private MarkerData ToMarkerData(wptType point) { return new MarkerData { latlng = ToLatLngZ(point), title = point.name }; }
private Coordinate CreateGeoPosition(wptType wayPoint) { double lat = (double)wayPoint.lat; double lon = (double)wayPoint.lon; return wayPoint.eleSpecified ? new Coordinate(lon, lat, (double)wayPoint.ele) : new Coordinate(lon, lat); }
private void displayTrack(gpxType track, string sPhotoPath) { displayProgressionText("Début du traitement"); gmap.Overlays.Clear(); gmap.Refresh(); #region extraction des points de passage if (track == null || track.trk == null) { return; } displayProgressionText("Extraction des points de passage"); List <wptType> listePoints = new List <wptType>(); trkType[] trk = track.trk; for (int trki = 0; trki < trk.Length; trki++) { for (int trksegi = 0; trksegi < trk[trki].trkseg.Length; trksegi++) { for (int trkpti = 0; trkpti < trk[trki].trkseg[trksegi].trkpt.Length; trkpti++) { if (trk[trki].trkseg[trksegi].trkpt[trkpti].timeSpecified) { listePoints.Add(trk[trki].trkseg[trksegi].trkpt[trkpti]); } } } } if (listePoints.Count == 0) { return; } // tri des photos par date de prise de vue listePoints = listePoints.OrderBy(x => x.time).ToList(); #endregion #region extraction des images et horodatage displayProgressionText("Extraction des images et horodatage"); List <Photo.PhotoInfo> listPhoto = new List <Photo.PhotoInfo>(); List <string> photoFiles = Directory.EnumerateFiles(sPhotoPath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".JPG") || s.EndsWith(".jpg")).ToList <string>(); foreach (string sPhoto in photoFiles) { string dateString = recupDatePriseDeVueImage(sPhoto); if (String.IsNullOrEmpty(dateString) == false) { DateTime date = DateTime.ParseExact(dateString, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture); listPhoto.Add(new Photo.PhotoInfo(sPhoto, date)); } } // tri des photos par date de prise de vue listPhoto = listPhoto.OrderBy(x => x.PriseDeVue).ToList(); #endregion #region fait correspondre les heures des photos à des positions GPX displayProgressionText("Recherche de correspondance entre les photos et les points GPS"); foreach (Photo.PhotoInfo photo in listPhoto) { wptType type = listePoints.Find(t => (t.timeSpecified && t.time.ToLocalTime() >= photo.PriseDeVue && (t.time.ToLocalTime() - photo.PriseDeVue).TotalMinutes < 10)); if (type != null) { photo.setGpsPosition((double)type.lat, (double)type.lon, type.time.ToLocalTime()); } } #endregion // http://www.independent-software.com/gmap-net-beginners-tutorial-adding-clickable-markers-to-your-map-updated-for-visual-studio-2015-and-gmap-net-1-7/ GMapOverlay routes = new GMapOverlay("chemin"); List <PointLatLng> pointsRoute = new List <PointLatLng>(); GMapOverlay markers = new GMapOverlay("markers"); foreach (wptType pt in listePoints) { pointsRoute.Add(new PointLatLng((double)pt.lat, (double)pt.lon)); } displayProgressionText("Redimension des photos"); // temp directory to store thumbs string tempPath = System.IO.Path.GetTempPath() + Application.ProductName + Path.DirectorySeparatorChar + "thumbs"; if (Directory.Exists(tempPath) == false) { try { Directory.CreateDirectory(tempPath); } catch { } } int index = 0; List <Photo.PhotoInfo> listCorrespondante = listPhoto.FindAll(p => p.PositionValid); foreach (Photo.PhotoInfo photo in listCorrespondante) { index++; displayProgression(index, listCorrespondante.Count); displayProgressionText("Redimension des photos " + index + "/" + listCorrespondante.Count); //C:\Users\Nicolas\Documents\Visual Studio 2010\Projects\PhotoGPS\Examples\JPG\_A9A1192.jpg // PhotoGPS_Examples_JPG__A9A1192.jpg List <string> partNames = photo.Path.Split('\\').ToList <string>(); bool bContinue = true; int partNumber = partNames.Count - 1; string newName = partNames[partNumber]; partNumber--; while (bContinue) { if (partNames.Count - partNumber > 3) { bContinue = false; } if (partNumber < 0) { bContinue = false; } newName = partNames[partNumber] + "_" + newName; partNumber--; } string newDirectory = tempPath + Path.DirectorySeparatorChar + newName; if (File.Exists(newDirectory) == false) { // création de la miniature Bitmap bmp = ResizeWidth(photo.Path, 100); bmp.Save(newDirectory); } GMapMarker marker = new GMarkerGoogle(new PointLatLng((double)photo.Lat, (double)photo.Lon), new Bitmap(newDirectory)); marker.Tag = photo; markers.Markers.Add(marker); } GMapRoute route = new GMapRoute(pointsRoute, "A walk in the park"); route.Stroke = new Pen(Color.Red, 3); routes.Routes.Add(route); gmap.Overlays.Add(routes); gmap.Overlays.Add(markers); gmap.ZoomAndCenterRoute(route); displayProgressionText(String.Empty); displayProgression(0, 0); }