| | | 1 | | using System.Globalization; |
| | | 2 | | using System.IO; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using Itinero.Geo; |
| | | 6 | | |
| | | 7 | | namespace Itinero.MapMatching.IO.GeoJson; |
| | | 8 | | |
| | | 9 | | public static class TrackExtensions |
| | | 10 | | { |
| | | 11 | | public static string ToGeoJson(this Track track) |
| | 0 | 12 | | { |
| | 0 | 13 | | using var stream = new MemoryStream(); |
| | 0 | 14 | | using (var jsonWriter = new Utf8JsonWriter(stream)) |
| | 0 | 15 | | { |
| | 0 | 16 | | jsonWriter.WriteFeatureCollectionStart(); |
| | 0 | 17 | | jsonWriter.WriteFeatures(track); |
| | 0 | 18 | | jsonWriter.WriteFeatureCollectionEnd(); |
| | 0 | 19 | | } |
| | | 20 | | |
| | 0 | 21 | | return Encoding.UTF8.GetString(stream.ToArray()); |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | public static void WriteFeatures(this Utf8JsonWriter jsonWriter, Track track) |
| | 0 | 25 | | { |
| | 0 | 26 | | for (var n = 0; n < track.Count; n++) |
| | 0 | 27 | | { |
| | 0 | 28 | | var trackPoint = track[n]; |
| | | 29 | | |
| | 0 | 30 | | var nodeLocation = (trackPoint.Location.longitude, trackPoint.Location.latitude, (float?)null); |
| | 0 | 31 | | jsonWriter.WriteFeatureStart(); |
| | 0 | 32 | | jsonWriter.WriteGeometryStart(); |
| | 0 | 33 | | jsonWriter.WritePoint((nodeLocation)); |
| | 0 | 34 | | jsonWriter.WriteProperties(new (string key, string value)[] |
| | 0 | 35 | | { |
| | 0 | 36 | | ("type", "track-point"), ("track-point-id", n.ToString()) |
| | 0 | 37 | | }); |
| | 0 | 38 | | jsonWriter.WriteFeatureEnd(); |
| | | 39 | | |
| | 0 | 40 | | if (n == 0) continue; |
| | | 41 | | |
| | 0 | 42 | | var previousTrackPoint = track[n - 1]; |
| | 0 | 43 | | var previousLocation = (previousTrackPoint.Location.longitude, previousTrackPoint.Location.latitude, |
| | 0 | 44 | | (float?)null); |
| | 0 | 45 | | var length = |
| | 0 | 46 | | nodeLocation.DistanceEstimateInMeter( |
| | 0 | 47 | | previousLocation); |
| | 0 | 48 | | jsonWriter.WriteFeatureStart(); |
| | 0 | 49 | | jsonWriter.WriteGeometryStart(); |
| | 0 | 50 | | jsonWriter.WriteLineString(new (double longitude, double latitude, float? e)[] { previousLocation, nodeLocat |
| | 0 | 51 | | jsonWriter.WriteProperties(new (string key, string value)[] |
| | 0 | 52 | | { |
| | 0 | 53 | | ("type", "track"), ("length", length.ToString(CultureInfo.InvariantCulture)) |
| | 0 | 54 | | }); |
| | 0 | 55 | | jsonWriter.WriteFeatureEnd(); |
| | 0 | 56 | | } |
| | 0 | 57 | | } |
| | | 58 | | } |