GpxWriter loadTrack(List <Track> tracks, Stream stream, string link_Href = "https://rutoteca.es/", string link_Text = "Rutoteca", string mimeType = "text/html", string name = "Rutoteca", string descripcion = "Visita Rutoteca el mayor almacen de rutas homologadas de España") { GpxWriter newGpx = new GpxWriter(stream); tracks.ForEach(t => { var newMetadata = new Gpx.GpxMetadata(); newMetadata.Link = new GpxLink(); newMetadata.Link.Href = link_Href; newMetadata.Link.MimeType = mimeType; newMetadata.Link.Text = link_Text; newMetadata.Name = name; newMetadata.Description = descripcion; newGpx.WriteMetadata(newMetadata); GpxTrack newTrack = new GpxTrack(); var newSegment = new Gpx.GpxTrackSegment(); var inicio = t.GpxPoint.First().Time; t.GpxPoint.ToList().ForEach(pt => { newSegment.TrackPoints.Add(SetGpxPoint(pt, inicio)); }); newTrack.Segments.Add(newSegment); newGpx.WriteTrack(newTrack); } ); return(newGpx); }
/// <summary> /// Guarda todo en un fichero /// </summary> public void SaveInFile(string filePath) { var fileStream = File.OpenWrite(filePath); GpxWriter writer = loadTrack(_tracks, fileStream); writer.Dispose(); }
/// <summary> /// Exports track by asking user for destination path and then using GpxWriter to write /// track to file /// </summary> /// <param name="track">track to export</param> /// <returns>task to wait on</returns> public static async Task ExportTrackAsync(Track track) { string exportFilename = await AskUserExportFilenameAsync(track.Name + ".gpx"); if (exportFilename == null) { return; } string exportPath = Path.Combine(FileSystem.CacheDirectory, exportFilename); try { GpxWriter.WriteTrack(exportPath, track); await ShareFile(exportPath, "application/gpx+xml"); } catch (Exception ex) { App.LogError(ex); await App.Current.MainPage.DisplayAlert( Constants.AppTitle, "Error while exporting track: " + ex.Message, "OK"); } }
public void TestWriteTrack() { // set up const string TrackName = "Test Track"; var track = new Track { Name = TrackName, TrackPoints = new System.Collections.Generic.List <TrackPoint> { new TrackPoint(47.754076, 12.352277, 1234.0, null) { Time = DateTime.Today + TimeSpan.FromHours(1.0) }, new TrackPoint(46.017779, 11.900711, 778.2, null) { Time = DateTime.Today + TimeSpan.FromHours(2.0) }, } }; // run string text = string.Empty; using (var stream = new MemoryStream()) { GpxWriter.WriteTrack(stream, track); text = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); } // check Debug.WriteLine("xml = " + text); Assert.IsTrue(text.Contains(TrackName), "gpx must contain track name"); }
private void newGpxFile(string Name, string Path) { FileStream readFile = File.Open(Path, FileMode.Open); FileStream writeFile = File.OpenWrite("../../Files/" + Name); GpxReader reader = new GpxReader(readFile); GpxWriter writer = new GpxWriter(writeFile); while (reader.Read()) { switch (reader.ObjectType) { case GpxObjectType.Metadata: writer.WriteMetadata(reader.Metadata); break; case GpxObjectType.WayPoint: writer.WriteWayPoint(reader.WayPoint); break; case GpxObjectType.Route: writer.WriteRoute(reader.Route); break; case GpxObjectType.Track: writer.WriteTrack(reader.Track); break; } } readFile.Close(); writeFile.Close(); }
/// <summary> /// Saves content of the GpxDocument to file. /// </summary> /// <param name="path">Path to the file.</param> public void Save(string path) { using (GpxWriter writer = new GpxWriter(path, new GpxWriterSettings() { WriteMetadata = true })) { this.Save(writer); } }
public void Constructor_StreamSettings_SetsSettingsAndMarkSettingsAsReadOnly() { var stream = new MemoryStream(); var settings = new GpxWriterSettings(); using (var target = new GpxWriter(stream, settings)) { Assert.Same(settings, target.Settings); Assert.True(target.Settings.IsReadOnly); } }
public void Dispose_ClosesOutputStreamIfWritingToStream() { MemoryStream stream = new MemoryStream(); var target = new GpxWriter(stream, new GpxWriterSettings()); target.Dispose(); Assert.False(stream.CanRead); }
public void Constructor_PathSettings_SetsSettingsAndMakesThemReadOnly() { string path = "TestFiles\\gpxwriter-constructor-test.gpx"; var settings = new GpxWriterSettings(); using (var target = new GpxWriter(path, settings)) { Assert.Same(settings, target.Settings); Assert.True(target.Settings.IsReadOnly); } }
public void Constructor_PathSettings_SetsSettingsAndMakesThemReadOnly() { string path = PathHelper.GetTempFilePath("gpxwriter-constructor-test-1.gpx"); var settings = new GpxWriterSettings(); using (var target = new GpxWriter(path, settings)) { Assert.Same(settings, target.Settings); Assert.True(target.Settings.IsReadOnly); } }
public void Constructor_PathSettings_CreatesOutputFile() { string filename = PathHelper.GetTempFilePath("gpxwriter-constructor-creates-output-test.gpx"); var settings = new GpxWriterSettings(); using (var target = new GpxWriter(filename, settings)) { ; } Assert.True(File.Exists(filename)); }
public void Dispose_ClosesOutputStreamIfWritingToFiles() { string path = PathHelper.GetTempFilePath("gpxwriter-closes-output-filestream-test.osm"); var target = new GpxWriter(path, new GpxWriterSettings()); target.Dispose(); FileStream testStream = null; testStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); testStream.Dispose(); }
public void Constructor_PathSettings_CreatesOutputFile() { string filename = "TestFiles\\gpxwriter-constructor-creates-output-test.gpx"; File.Delete(filename); var settings = new GpxWriterSettings(); using (var target = new GpxWriter(filename, settings)) { ; } Assert.True(File.Exists(filename)); }
public void Dispose_ClosesOutputStreamIfWritingToFiles() { string path = "TestFiles\\gpxwriter-closes-output-filestream-test.osm"; File.Delete(path); var target = new GpxWriter(path, new GpxWriterSettings()); target.Dispose(); FileStream testStream = null; Assert.DoesNotThrow(() => testStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)); testStream.Dispose(); }
public void Constructor_PathSettings_CreatesGpxFileWithRootElement() { string path = PathHelper.GetTempFilePath("gpxwriter-constructor-test-2.gpx"); string generatorName = "SpatialLite"; using (GpxWriter target = new GpxWriter(path, new GpxWriterSettings() { WriteMetadata = false, GeneratorName = generatorName })) { } XDocument written = XDocument.Load(path); XDocument expected = XDocument.Load(TestDataReader.Open("gpx-empty-file.gpx")); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected)); }
public void Write_WritesRouteWithoutMetadataIfWriteMetadataIsFalse() { MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = false })) { target.Write(_routeWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(TestDataReader.Open("gpx-route-single-route.gpx")); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected)); }
public void Write_WritesTrackWithMetadata() { MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = true })) { target.Write(_trackWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(TestDataReader.Open("gpx-track-with-metadata.gpx")); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected)); }
public void Write_WritesWaypointWithoutMetadataIfMetadataIsNull() { MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = false })) { target.Write(_waypoint); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_waypoint_simple)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public void Constructor_StreamSettings_CreatesGpxFileWithRootElement() { string generatorName = "SpatialLite"; var stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = false, GeneratorName = generatorName })) { } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_empty_file)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public void Write_DoesntWriteTrackMetadataIfWriteMetadataIsFalse() { MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = false })) { target.Write(_trackWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_track_single_track_segment)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public void Write_WritesRouteWithMetadata() { MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = true })) { target.Write(_routeWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_route_with_metadata)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
static void Main(string[] args) { var input = new FileStream(@"C:\perso\Night ride\Night ride 2nd part.gpx", FileMode.Open); var output = new FileStream(@"C:\perso\Night ride\Night ride 2nd part_with_timespamp.gpx", FileMode.Create); DateTime startTime = DateTime.Parse("2020-07-06T23:35:28"); DateTime endTime = DateTime.Parse("2020-07-07T00:35:28"); double totalPoints = 1379; int p = 0; using (GpxReader reader = new GpxReader(input)) { using (GpxWriter writer = new GpxWriter(output)) { while (reader.Read()) { switch (reader.ObjectType) { case GpxObjectType.Metadata: writer.WriteMetadata(reader.Metadata); break; case GpxObjectType.WayPoint: writer.WriteWayPoint(reader.WayPoint); break; case GpxObjectType.Route: writer.WriteRoute(reader.Route); break; case GpxObjectType.Track: var track = reader.Track; foreach (var seg in track.Segments) { foreach (var point in seg.TrackPoints) { point.Time = startTime.AddSeconds(p * (endTime - startTime).TotalSeconds / totalPoints); Console.WriteLine($"time = {point.Time}"); p++; } } writer.WriteTrack(track); break; } } } } }
public void Write_WritesRouteWithoutUnnecessaryElements() { _routeWithMetadata.Metadata.Source = null; MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = true })) { target.Write(_routeWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(TestDataReader.Open("gpx-route-with-metadata-selection.gpx")); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected)); }
/// <summary> /// Guarda todo en un fichero /// </summary> public void SaveInStream(Stream stream, string link_Href = "https://rutoteca.es/", string link_Text = "Rutoteca", string mimeType = "text/html", string name = "Rutoteca", string descripcion = "Visita Rutoteca el mayor almacen de rutas homologadas de España") { GpxWriter writer = loadTrack(_tracks, stream, link_Href, link_Text, mimeType, name, descripcion); writer.Dispose(); }
public void Constructor_PathSettings_CreatesGpxFileWithRootElement() { string path = "TestFiles\\gpx-writer-constructor-test.gpx"; File.Delete(path); string generatorName = "SpatialLite"; using (GpxWriter target = new GpxWriter(path, new GpxWriterSettings() { WriteMetadata = false, GeneratorName = generatorName })) { } XDocument written = XDocument.Load(path); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_empty_file)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public void Write_TrackWithEntityDetailsButNullValues_WritesTrackWithoutUnnecessaryElements() { MemoryStream stream = new MemoryStream(); _trackWithMetadata.Metadata.Source = null; using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = true })) { target.Write(_trackWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_track_with_metadata_selection)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public void Write_WritesWaypointWithoutUnnecessaryElements() { _waypointWithMetadata.Metadata.SatellitesCount = null; _waypointWithMetadata.Metadata.Name = null; MemoryStream stream = new MemoryStream(); using (GpxWriter target = new GpxWriter(stream, new GpxWriterSettings() { WriteMetadata = true })) { target.Write(_waypointWithMetadata); } XDocument written = XDocument.Load(new MemoryStream(stream.ToArray())); XDocument expected = XDocument.Load(new MemoryStream(GpxTestData.gpx_waypoint_with_metadata_selection)); Assert.True(XDocumentExtensions.DeepEqualsWithNormalization(written, expected, null)); }
public static IList <Coordinates> GetGPXPoints() { IList <Coordinates> lst = new List <Coordinates>(); //Reading the GOX Debug.Log(("Reading GPX")); StreamReader input = new StreamReader(@"C:\Users\Chris\Documents\UnityProjects\CreateObject\Assets\gpxfiles\Heffers.gpx", Encoding.Default); // StreamReader input = new StreamReader(@"C:\Users\Chris\Documents\UnityProjects\CreateObject\Assets\chop.gpx", Encoding.Default); // StreamReader input = new StreamReader(@"C:\Users\Chris\Documents\UnityProjects\CreateObject\Assets\Perth worlds qualifier.gpx", Encoding.Default); MemoryStream m = new MemoryStream(); using (GpxReader reader = new GpxReader(input.BaseStream)) { using (GpxWriter writer = new GpxWriter(m)) { while (reader.Read()) { switch (reader.ObjectType) { case GpxObjectType.Metadata: Debug.Log(("Metadata")); writer.WriteMetadata(reader.Metadata); break; case GpxObjectType.WayPoint: Debug.Log(("Point")); writer.WriteWayPoint(reader.WayPoint); break; case GpxObjectType.Route: Debug.Log(("Route")); writer.WriteRoute(reader.Route); break; case GpxObjectType.Track: Debug.Log(("Track")); writer.WriteTrack(reader.Track); //Set a local origin //GPSEncoder.SetLocalOrigin(new Vector2((float)originCoords.latitude, (float)originCoords.longitude)); //Coordinates origin = new Coordinates(1.289639, -3532648, 1); IList <GpxTrackSegment> segments = reader.Track.Segments; IList <GpxTrackPoint> tp = segments[0].TrackPoints; foreach (GpxTrackPoint item in tp) { Debug.Log(("lat" + item.Latitude)); Debug.Log(("lng" + item.Longitude)); Debug.Log(("e" + item.Elevation)); //Coordinates c = new Coordinates(item.Latitude, item.Longitude, item.Elevation.Value); //Vector3 v = c.convertCoordinateToVector(); Coordinates currentLocation; currentLocation = new Coordinates(item.Latitude, item.Longitude, item.Elevation.Value); lst.Add(currentLocation); // UnityEngine.GameObject o = (GameObject)Instantiate(prefab, new Vector3(v.x, v.y, v.z), Quaternion.identity); //UnityEngine.GameObject o = (GameObject)Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity); // o.transform.parent = sourceGO.transform; } break; } } } } return(lst); }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); #if DEBUG if (args == null || args.Length < 1) { args = new[] { "test" }; } #endif if (args == null || args.Length < 1) { // show help. Log.Fatal("Could not parse arguments"); ShowHelp(); return; } if (args[0] == "help") { ShowHelp(); return; } if (args[0] == "test") { args = new[] { "test.geojson", "test.gpx" }; Log.Information($"Running test using: {args[0]}"); } if (!string.IsNullOrEmpty(args[0])) { // check if the input exists. if (!File.Exists(args[0])) { Log.Fatal($"Input file not found: {args[0]}"); ShowHelp(); return; } if (args.Length == 1) { args = new[] { args[0], args[0] + ".gpx" }; Log.Information($"No second argument found, using output: {args[1]}"); } } // enable logging. OsmSharp.Logging.Logger.LogAction = (origin, level, message, parameters) => { var formattedMessage = $"{origin} - {message}"; switch (level) { case "critical": Log.Fatal(formattedMessage); break; case "error": Log.Error(formattedMessage); break; case "warning": Log.Warning(formattedMessage); break; case "verbose": Log.Verbose(formattedMessage); break; case "information": Log.Information(formattedMessage); break; case "debug": Log.Debug(formattedMessage); break; } }; Itinero.Logging.Logger.LogAction = (origin, level, message, parameters) => { var formattedMessage = $"{origin} - {message}"; switch (level) { case "critical": Log.Fatal(formattedMessage); break; case "error": Log.Error(formattedMessage); break; case "warning": Log.Warning(formattedMessage); break; case "verbose": Log.Verbose(formattedMessage); break; case "information": Log.Information(formattedMessage); break; case "debug": Log.Debug(formattedMessage); break; } }; // validate arguments. if (args.Length < 2) { Log.Fatal("At least two arguments expected."); return; } var inputFile = args[0]; if (!File.Exists(inputFile)) { Log.Fatal($"Input file {inputFile} not found!"); return; } var outputPath = new FileInfo(args[1]).DirectoryName; if (!Directory.Exists(outputPath)) { Log.Fatal($"Output path {outputPath} not found!"); return; } var profileName = "car.shortest"; if (args.Length >= 3 && args[2] == "fastest") { // apply fastest only on request. profileName = "car"; } Log.Information($"Using profile '{profileName}'"); // read the locations. Coordinate[] locations; if (inputFile.ToLowerInvariant().EndsWith(".geojson")) { locations = GeoJson.GeoJsonReader1.Read(args[0]).ToArray(); } else { locations = CSV.CSVReader.Read(args[0]).Select(r => new Coordinate((float)r.Latitude, (float)r.Longitude)).ToArray(); } // build router db if needed. var routerDb = RouterDbBuilder.BuildRouterDb(profileName); // cut out a part of the router db. var box = locations.BuildBoundingBox().Value.Resize(0.01f); routerDb = routerDb.ExtractArea((l) => box.Overlaps(l.Latitude, l.Longitude)); // create and configure the optimizer. var router = new Router(routerDb); var optimizer = router.Optimizer(new OptimizerConfiguration(modelMapperRegistry: new ModelMapperRegistry( new ByEdgeDirectedModelMapper(1000)))); // run the optimization. var profile = routerDb.GetSupportedProfile(profileName); var route = optimizer.Optimize(profile.FullName, locations, out _, 0, 0, turnPenalty: 60); if (route.IsError) { Log.Fatal("Calculating route failed {@errorMessage}", route.ErrorMessage); return; } File.WriteAllText(args[1] + ".geojson", route.Value.ToGeoJson()); // set a description/name on stops. foreach (var stop in route.Value.Stops) { if (!stop.Attributes.TryGetValue("order", out var order) || !stop.Attributes.TryGetValue("index", out var index)) { continue; } stop.Attributes.AddOrReplace("Name", $"{order}"); stop.Attributes.AddOrReplace("Description", $"Stop {index} @ {order}"); } route.Value.ShapeMeta = null; // convert to GPX. var features = route.Value.ToFeatureCollection(); using (var stream = File.Open(args[1], FileMode.Create)) { var writerSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, CloseOutput = true }; using (var wr = XmlWriter.Create(stream, writerSettings)) { GpxWriter.Write(wr, null, new GpxMetadata("StreetScan"), features.Features, null); } } }