public Arc(
     Longitude longitudeDifference,
     Latitude latitudeDifference)
 {
     LongitudeDifference = longitudeDifference;
     LatitudeDifference = latitudeDifference;
 }
 /// <summary>
 /// Create a new geographical coordinate or position on a map.
 /// </summary>
 /// <param name="Latitude">The Latitude (south to nord).</param>
 /// <param name="Longitude">The Longitude (parallel to equator).</param>
 /// <param name="Altitude">The (optional) Altitude.</param>
 /// <param name="Name">An optional name for this geo location.</param>
 public AdditionalGeoLocation(Latitude    Latitude,
                              Longitude   Longitude,
                              Altitude?   Altitude  = null,
                              I18NString  Name      = null)
 {
     this.Name = Name != null ? Name : new I18NString();
 }
Exemplo n.º 3
0
        /// <summary>
        /// Create a new abstract shape.
        /// </summary>
        /// <param name="Id">The Id of the shape.</param>
        /// <param name="Latitude">The latitude of the shape center.</param>
        /// <param name="Longitude">The longitude of the shape center.</param>
        /// <param name="Altitude">The altitude of the shape center.</param>
        /// <param name="GeoWidth">The geographical width of the shape center.</param>
        /// <param name="GeoHeight">The geographical height of the shape center.</param>
        public AShape(String[] Geometries, Latitude Latitude, Longitude Longitude, Altitude Altitude, Latitude Latitude2, Longitude Longitude2, Color StrokeColor, Double StrokeThickness, Color FillColor)
        {
            this.Id         = Id;
            this.Latitude   = Latitude;
            this.Longitude  = Longitude;
            this.Altitude   = Altitude;
            this.Latitude2  = Latitude2;
            this.Longitude2 = Longitude2;

            var PathGeometry16 = PathGeometry.Parse(Geometries[8]);

            var GD16 = new GeometryDrawing(new SolidColorBrush(FillColor), new Pen(new SolidColorBrush(StrokeColor), StrokeThickness), PathGeometry16);

            var DrawingGroup = new DrawingGroup();
            DrawingGroup.Children.Add(GD16);

            this.Fill = new DrawingBrush()
            {
                Drawing = DrawingGroup,
                //Viewport = new Rect(0, 0, 1, 1),
                TileMode = TileMode.None,
                Stretch = Stretch.UniformToFill
            };

            Bounds = DrawingGroup.Bounds;
            var w = Bounds.Width;
            var h = Bounds.Height;
        }
Exemplo n.º 4
0
 public GeoBoundingBox(Latitude  Latitude,
                       Longitude Longitude,
                       Latitude  Latitude2,
                       Longitude Longitude2)
     : this(Latitude,  Longitude,  new Altitude(0),
            Latitude2, Longitude2, new Altitude(0))
 {
 }
Exemplo n.º 5
0
 /// <summary>
 /// Create a new abstract shape.
 /// </summary>
 /// <param name="Id">The Id of the shape.</param>
 /// <param name="Latitude">The latitude of the shape center.</param>
 /// <param name="Longitude">The longitude of the shape center.</param>
 /// <param name="Altitude">The altitude of the shape center.</param>
 /// <param name="GeoWidth">The geographical width of the shape center.</param>
 /// <param name="GeoHeight">The geographical height of the shape center.</param>
 public AShape(String Id, Latitude Latitude, Longitude Longitude, Altitude Altitude, Latitude Latitude2, Longitude Longitude2)
 {
     this.Id         = Id;
     this.Latitude   = Latitude;
     this.Longitude  = Longitude;
     this.Altitude   = Altitude;
     this.Latitude2  = Latitude2;
     this.Longitude2 = Longitude2;
 }
Exemplo n.º 6
0
        public void HemisphereAngleConstructorTest1()
        {
            Angle angle = new Angle(0);

            Longitude longitude = new Longitude(angle, CardinalDirection.West);

            Assert.AreEqual(angle, longitude.Value);
            Assert.AreEqual(angle, longitude.RawValue);
        }
Exemplo n.º 7
0
        public void GeoCoordinateInitializerTest()
        {
            var Random = new Random();
            var RandomLatitude  = new Latitude ((Random.NextDouble() - 0.5) * 180);
            var RandomLongitude = new Longitude((Random.NextDouble() - 0.5) * 180);

            var GeoCoordinate1 = new GeoCoordinate(RandomLatitude, RandomLongitude);
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate1.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate1.Longitude.Value, 0.0000001);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Add a map feature of the given dimensions at the given geo coordinate.
 /// </summary>
 /// <param name="Id">The unique identification of the feature.</param>
 /// <param name="Latitude">The latitude of the feature.</param>
 /// <param name="Longitude">The longitude of the feature.</param>
 /// <param name="Width">The longitude of the feature.</param>
 /// <param name="Height">The longitude of the feature.</param>
 /// <param name="Fill">The fill brush of the feature.</param>
 /// <param name="Stroke">The stroke brush of the feature.</param>
 /// <param name="StrokeThickness">The thickness of the stroke.</param>
 public Feature AddFeature(String     Id,
                           Latitude   Latitude,
                           Longitude  Longitude,
                           Double     Width,
                           Double     Height,
                           Color      Color)
 {
     return AddFeature(Id,
                       new GeoCoordinate(Latitude, Longitude),
                       Width, Height,
                       Color);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new instance from a specified <see cref="Latitude"/> and <see cref="Longitude"/>
        /// </summary>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        public Position(Longitude longitude,Latitude latitude)
        {
            if (longitude == null)
            {
                throw new ArgumentNullException("longitude");
            }
            if (latitude == null)
            {
                throw new ArgumentNullException("latitude");
            }

            Longitude = longitude;
            Latitude = latitude;
        }
Exemplo n.º 10
0
 /// <summary>
 /// Add a map feature of the given dimensions at the given geo coordinate.
 /// </summary>
 /// <param name="Id">The unique identification of the feature.</param>
 /// <param name="Latitude">The latitude of the feature.</param>
 /// <param name="Longitude">The longitude of the feature.</param>
 /// <param name="Width">The longitude of the feature.</param>
 /// <param name="Height">The longitude of the feature.</param>
 /// <param name="Fill">The fill brush of the feature.</param>
 /// <param name="Stroke">The stroke brush of the feature.</param>
 /// <param name="StrokeThickness">The thickness of the stroke.</param>
 public Feature AddFeature(String     Id,
                           Latitude   Latitude,
                           Longitude  Longitude,
                           Double     Width,
                           Double     Height,
                           Brush      Fill,
                           Brush      Stroke,
                           Double     StrokeThickness)
 {
     return AddFeature(Id,
                       new GeoCoordinate(Latitude, Longitude),
                       Width, Height,
                       Fill, Stroke, StrokeThickness);
 }
Exemplo n.º 11
0
        public Feature AddPath(String Id, Latitude Latitude, Longitude Longitude, Double Width, Double Height, Color Color)
        {
            var XY = GeoCalculations.GeoCoordinate2ScreenXY(Latitude, Longitude, MapControl.ZoomLevel);

            var PathGeometry1 = PathGeometry.Parse("M51,42c-5-4-11-7-19-7c-6,0-12,1-20,5l10-35c20-8,30-4,39,2l-10,35z");
            var PathGeometry2 = PathGeometry.Parse("M106,13c-21,9-31,4-40-2l-10,35c9,6,20,11,40,2l10-35z");
            var PathGeometry3 = PathGeometry.Parse("M39,83c-9-6-18-10-39-2l10-35c21-9,31-4,39,2l-10,35z");
            var PathGeometry4 = PathGeometry.Parse("M55,52c9,6,18,10,39,2l-10,35c-21,8-30,3-39-3l10-34z");

            var pathText = PathGeometry1.ToString();

            var GD1 = new GeometryDrawing(new SolidColorBrush(Color.FromRgb(0xE0, 0x60, 0x30)), null, PathGeometry1);
            var GD2 = new GeometryDrawing(new SolidColorBrush(Color.FromRgb(0x70, 0xB0, 0x40)), null, PathGeometry2);
            var GD3 = new GeometryDrawing(new SolidColorBrush(Color.FromRgb(0x40, 0x90, 0xc0)), null, PathGeometry3);
            var GD4 = new GeometryDrawing(new SolidColorBrush(Color.FromRgb(0xF0, 0xD0, 0x50)), null, PathGeometry4);

            var DrawingGroup = new DrawingGroup();
            DrawingGroup.Children.Add(GD1);
            DrawingGroup.Children.Add(GD2);
            DrawingGroup.Children.Add(GD3);
            DrawingGroup.Children.Add(GD4);

            var DrawingBrush = new DrawingBrush() {
                Drawing  = DrawingGroup,
                TileMode = TileMode.None
            };

            var Feature = new Feature(Id, new RectangleGeometry() { Rect = DrawingGroup.Bounds }) {
                Latitude   = Latitude,
                Longitude  = Longitude,
                Width      = DrawingGroup.Bounds.Width,
                Height     = DrawingGroup.Bounds.Height,
                Fill       = DrawingBrush,
                ToolTip    = Id
            };

            // The position on the map will be set within the PaintMap() method!
            this.Children.Add(Feature);

            return Feature;
        }
Exemplo n.º 12
0
        public GeoBoundingBox(Latitude  Latitude,
                              Longitude Longitude,
                              Altitude  Altitude,
                              Latitude  Latitude2,
                              Longitude Longitude2,
                              Altitude  Altitude2)
        {
            this.GeoCoordinate1 = new GeoCoordinate(Latitude,  Longitude,  Altitude);
            this.Latitude       = Latitude;
            this.Longitude      = Longitude;
            this.Altitude       = Altitude;

            this.GeoCoordinate2 = new GeoCoordinate(Latitude2, Longitude2, Altitude2);
            this.Latitude2      = Latitude2;
            this.Longitude2     = Longitude2;
            this.Altitude2      = Altitude2;

            this.GeoWidth       = GeoCoordinate1.DistanceKM(new GeoCoordinate(GeoCoordinate1.Latitude, GeoCoordinate2.Longitude)); // Longitude West  <-> East
            this.GeoHeight      = GeoCoordinate1.DistanceKM(new GeoCoordinate(GeoCoordinate2.Latitude, GeoCoordinate1.Longitude)); // Latitude  North <-> South
            this.GeoAlitude     = Altitude2. Value - Altitude. Value;
        }
Exemplo n.º 13
0
        public void Ctor_DegreesMinutesSecondsDirection()
        {
            var longitude = new Longitude(79, 58, 56, Direction.W);

            this.AssertCoordinateData(longitude);
        }
Exemplo n.º 14
0
        public void Ctor_DegreesDirection()
        {
            var longitude = new Longitude(79.9822166667m, Direction.W);

            this.AssertCoordinateData(longitude);
        }
Exemplo n.º 15
0
        public void Ctor_Degrees()
        {
            var longitude = new Longitude(-79.98222m);

            this.AssertCoordinateData(longitude);
        }
 public Longitude(Longitude longitude)
     : this(longitude.Degrees, longitude.Minutes) { }
Exemplo n.º 17
0
        protected override void OnSentenceChanged()
        {
            // First, process the basic info for the sentence
            base.OnSentenceChanged();

            // Cache the sentence words
            string[] words = base.Words;
            int wordCount = words.Length;

            /*
             * $GPRMC

                 Recommended minimum specific GPS/Transit data

                 eg1. $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
                 eg2. $GPRMC,225446,A,4916.45,N,12311.12,W,000.5,054.7,191194,020.3,E*68


                            225446       Time of fix 22:54:46 UTC
                            A            Navigation receiver warning A = OK, V = warning
                            4916.45,N    Latitude 49 deg. 16.45 min North
                            12311.12,W   Longitude 123 deg. 11.12 min West
                            000.5        Speed over ground, Knots
                            054.7        Course Made Good, True
                            191194       Date of fix  19 November 1994
                            020.3,E      Magnetic variation 20.3 deg East
                            *68          mandatory checksum


                 eg3. $GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70
                               1    2    3    4    5     6    7    8      9     10  11 12


                       1   220516     Time Stamp
                       2   A          validity - A-ok, V-invalid
                       3   5133.82    current Latitude
                       4   N          North/South
                       5   00042.24   current Longitude
                       6   W          East/West
                       7   173.8      Speed in knots
                       8   231.8      True course
                       9   130694     Date Stamp
                       10  004.2      Variation
                       11  W          East/West
                       12  *70        checksum


                 eg4. $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh
                 1    = UTC of position fix
                 2    = Data status (V=navigation receiver warning)
                 3    = Latitude of fix
                 4    = N or S
                 5    = Longitude of fix
                 6    = E or W
                 7    = Speed over ground in knots
                 8    = Track made good in degrees True
                 9    = UT date
                 10   = Magnetic variation degrees (Easterly var. subtracts from true course)
                 11   = E or W
                 12   = Checksum
             */


            // Do we have enough words to parse the fix status?
            if (wordCount >= 2 && words[1].Length != 0)
            {
                #region Fix status 

                // Get the fix flag
                _FixStatus = words[1].Equals("A", StringComparison.OrdinalIgnoreCase) ? FixStatus.Fix : FixStatus.NoFix;

                #endregion
            }
            else
            {
                // The fix status is invalid
                _FixStatus = FixStatus.Unknown;
            }

            // Do we have enough words to parse the UTC date/time?
            if (wordCount >= 9 && words[0].Length != 0 && words[8].Length != 0)
            {
                #region Parse the UTC time

                string utcTimeWord = words[0];
                int utcHours = int.Parse(utcTimeWord.Substring(0, 2), NmeaCultureInfo);                 // AA
                int utcMinutes = int.Parse(utcTimeWord.Substring(2, 2), NmeaCultureInfo);               // BB
                int utcSeconds = int.Parse(utcTimeWord.Substring(4, 2), NmeaCultureInfo);               // CC
                int utcMilliseconds = 0;
                if(utcTimeWord.Length > 6)
                    utcMilliseconds = Convert.ToInt32(float.Parse(utcTimeWord.Substring(6), NmeaCultureInfo) * 1000, NmeaCultureInfo);    // DDDD

                #endregion

                #region Parse the UTC date

                string utcDateWord = words[8];
                int utcDay = int.Parse(utcDateWord.Substring(0, 2), NmeaCultureInfo);
                int utcMonth = int.Parse(utcDateWord.Substring(2, 2), NmeaCultureInfo);
                int utcYear = int.Parse(utcDateWord.Substring(4, 2), NmeaCultureInfo) + 2000;

                #endregion

                #region Build a UTC date/time

                _UtcDateTime = new DateTime(utcYear, utcMonth, utcDay, utcHours, utcMinutes, utcSeconds, utcMilliseconds, DateTimeKind.Utc);

                #endregion
            }
            else
            {
                // The UTC date/time is invalid
                _UtcDateTime = DateTime.MinValue;
            }

            // Do we have enough data to parse the location?
            if (wordCount >= 6 && words[2].Length != 0 && words[3].Length != 0 && words[4].Length != 0 && words[5].Length != 0)
            {
                #region Parse the latitude

                string latitudeWord = words[2];
                int latitudeHours = int.Parse(latitudeWord.Substring(0, 2), NmeaCultureInfo);
                double latitudeDecimalMinutes = double.Parse(latitudeWord.Substring(2), NmeaCultureInfo);
                LatitudeHemisphere latitudeHemisphere =
                    words[3].Equals("N", StringComparison.Ordinal) ? LatitudeHemisphere.North : LatitudeHemisphere.South;

                #endregion

                #region Parse the longitude

                string longitudeWord = words[4];
                int longitudeHours = int.Parse(longitudeWord.Substring(0, 3), NmeaCultureInfo);
                double longitudeDecimalMinutes = double.Parse(longitudeWord.Substring(3), NmeaCultureInfo);
                LongitudeHemisphere longitudeHemisphere =
                    words[5].Equals("E", StringComparison.Ordinal) ? LongitudeHemisphere.East : LongitudeHemisphere.West;

                #endregion

                #region Build a Position from the latitude and longitude

                _Position = new Position(
                                new Latitude(latitudeHours, latitudeDecimalMinutes, latitudeHemisphere),
                                new Longitude(longitudeHours, longitudeDecimalMinutes, longitudeHemisphere));

                #endregion
            }
            else
            {
                _Position = Position.Invalid;
            }

            // Do we have enough info to process speed?
            if (wordCount >= 7 && words[6].Length != 0)
            {
                #region Speed

                // The speed is the sixth word, expressed in knots                
                _Speed = new Speed(double.Parse(words[6], NmeaCultureInfo), SpeedUnit.Knots);

                #endregion
            }
            else
            {
                // The speed is invalid
                _Speed = Speed.Invalid;
            }

            // do we have enough info to process the bearing?
            if (wordCount >= 8 && words[7].Length != 0)
            {
                #region Bearing

                // The bearing is the seventh word
                _Bearing = new Azimuth(double.Parse(words[7], NmeaCultureInfo));

                #endregion
            }
            else
            {
                // The bearing is invalid
                _Bearing = Azimuth.Invalid;
            }

            // Do we have enough info for magnetic variation?
            if (wordCount >= 10 && words[9].Length != 0)
            {
                // Parse the value
                _MagneticVariation = new Longitude(double.Parse(words[9], NmeaCultureInfo));
            }
            else
            {
                // The magnetic variation is invalid
                _MagneticVariation = Longitude.Invalid;
            }
        }
Exemplo n.º 18
0
        private IReadOnlyDictionary <string, string> GetProperties(DiscordGuild guild, WhConfig whConfig, string city, string raidImageUrl)
        {
            var pkmnInfo        = MasterFile.GetPokemon(PokemonId, Form);
            var name            = IsEgg ? "Egg" /*TODO: Localize*/ : Translator.Instance.GetPokemonName(PokemonId);
            var form            = Translator.Instance.GetFormName(Form);
            var costume         = Translator.Instance.GetCostumeName(Costume);
            var evo             = Translator.Instance.GetEvolutionName(Evolution);
            var gender          = Gender.GetPokemonGenderIcon();
            var level           = Level;
            var move1           = Translator.Instance.GetMoveName(FastMove);
            var move2           = Translator.Instance.GetMoveName(ChargeMove);
            var types           = pkmnInfo?.Types;
            var type1           = types?[0];
            var type2           = types?.Count > 1 ? types?[1] : PokemonType.None;
            var type1Emoji      = types?[0].GetTypeEmojiIcons();
            var type2Emoji      = pkmnInfo?.Types?.Count > 1 ? types?[1].GetTypeEmojiIcons() : string.Empty;
            var typeEmojis      = $"{type1Emoji} {type2Emoji}";
            var weaknesses      = Weaknesses == null ? string.Empty : string.Join(", ", Weaknesses);
            var weaknessesEmoji = types?.GetWeaknessEmojiIcons();
            var perfectRange    = PokemonId.MaxCpAtLevel(20);
            var boostedRange    = PokemonId.MaxCpAtLevel(25);
            var worstRange      = PokemonId.MinCpAtLevel(20);
            var worstBoosted    = PokemonId.MinCpAtLevel(25);
            var exEmojiId       = MasterFile.Instance.Emojis["ex"];
            var exEmoji         = exEmojiId > 0 ? $"<:ex:{exEmojiId}>" : "EX";
            var teamEmojiId     = MasterFile.Instance.Emojis[Team.ToString().ToLower()];
            var teamEmoji       = teamEmojiId > 0 ? $"<:{Team.ToString().ToLower()}:{teamEmojiId}>" : Team.ToString();

            var gmapsLink               = string.Format(Strings.GoogleMaps, Latitude, Longitude);
            var appleMapsLink           = string.Format(Strings.AppleMaps, Latitude, Longitude);
            var wazeMapsLink            = string.Format(Strings.WazeMaps, Latitude, Longitude);
            var scannerMapsLink         = string.Format(whConfig.Urls.ScannerMap, Latitude, Longitude);
            var staticMapLink           = StaticMap.GetUrl(whConfig.Urls.StaticMap, whConfig.StaticMaps["raids"], Latitude, Longitude, raidImageUrl, Team);
            var gmapsLocationLink       = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, gmapsLink);
            var appleMapsLocationLink   = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, appleMapsLink);
            var wazeMapsLocationLink    = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, wazeMapsLink);
            var scannerMapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, scannerMapsLink);
            var address = new Location(null, city, Latitude, Longitude).GetAddress(whConfig);
            //var staticMapLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? staticMapLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, staticMapLink);

            var now           = DateTime.UtcNow.ConvertTimeFromCoordinates(Latitude, Longitude);
            var startTimeLeft = now.GetTimeRemaining(StartTime).ToReadableStringNoSeconds();
            var endTimeLeft   = now.GetTimeRemaining(EndTime).ToReadableStringNoSeconds();

            const string defaultMissingValue = "?";
            var          dict = new Dictionary <string, string>
            {
                //Raid boss properties
                { "pkmn_id", PokemonId.ToString() },
                { "pkmn_id_3", PokemonId.ToString("D3") },
                { "pkmn_name", name },
                { "pkmn_img_url", raidImageUrl },
                { "evolution", evo },
                { "evolution_id", Convert.ToInt32(Evolution).ToString() },
                { "evolution_id_3", Evolution.ToString("D3") },
                { "form", form },
                { "form_id", Form.ToString() },
                { "form_id_3", Form.ToString("D3") },
                { "costume", costume },
                { "costume_id", Costume.ToString() },
                { "costume_id_3", Costume.ToString("D3") },
                { "is_egg", Convert.ToString(IsEgg) },
                { "is_ex", Convert.ToString(IsExEligible) },
                { "ex_emoji", exEmoji },
                { "team", Team.ToString() },
                { "team_id", Convert.ToInt32(Team).ToString() },
                { "team_emoji", teamEmoji },
                { "cp", CP ?? defaultMissingValue },
                { "lvl", level ?? defaultMissingValue },
                { "gender", gender ?? defaultMissingValue },
                { "move_1", move1 ?? defaultMissingValue },
                { "move_2", move2 ?? defaultMissingValue },
                { "moveset", $"{move1}/{move2}" },
                { "type_1", type1?.ToString() ?? defaultMissingValue },
                { "type_2", type2?.ToString() ?? defaultMissingValue },
                { "type_1_emoji", type1Emoji },
                { "type_2_emoji", type2Emoji },
                { "types", $"{type1}/{type2}" },
                { "types_emoji", typeEmojis },
                { "weaknesses", weaknesses },
                { "weaknesses_emoji", weaknessesEmoji },
                { "perfect_cp", perfectRange.ToString() },
                { "perfect_cp_boosted", boostedRange.ToString() },
                { "worst_cp", worstRange.ToString() },
                { "worst_cp_boosted", worstBoosted.ToString() },

                //Time properties
                { "start_time", StartTime.ToLongTimeString() },
                { "start_time_24h", StartTime.ToString("HH:mm:ss") },
                { "start_time_left", startTimeLeft },
                { "end_time", EndTime.ToLongTimeString() },
                { "end_time_24h", EndTime.ToString("HH:mm:ss") },
                { "end_time_left", endTimeLeft },

                //Location properties
                { "geofence", city ?? defaultMissingValue },
                { "lat", Latitude.ToString() },
                { "lng", Longitude.ToString() },
                { "lat_5", Latitude.ToString("0.00000") },
                { "lng_5", Longitude.ToString("0.00000") },

                //Location links
                { "tilemaps_url", staticMapLink },
                { "gmaps_url", gmapsLocationLink },
                { "applemaps_url", appleMapsLocationLink },
                { "wazemaps_url", wazeMapsLocationLink },
                { "scanmaps_url", scannerMapsLocationLink },

                { "address", address?.Address },

                //Gym properties
                { "gym_id", GymId },
                { "gym_name", GymName },
                { "gym_url", GymUrl },

                // Discord Guild properties
                { "guild_name", guild?.Name },
                { "guild_img_url", guild?.IconUrl },

                { "date_time", DateTime.Now.ToString() },

                //Misc properties
                { "br", "\r\n" }
            };

            return(dict);
        }
Exemplo n.º 19
0
        public void GeoCoordinateToStringAndBackParsingTest()
        {
            var Random = new Random();
            var RandomLatitude  = new Latitude ((Random.NextDouble() - 0.5) * 180);
            var RandomLongitude = new Longitude((Random.NextDouble() - 0.5) * 180);

            var GeoCoordinate1 = new GeoCoordinate(RandomLatitude, RandomLongitude);
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate1.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate1.Longitude.Value, 0.0000001);

            var GeoCoordinate2 = GeoCoordinate.ParseString(GeoCoordinate1.ToGeoString());
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate2.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate2.Longitude.Value, 0.0000001);

            var GeoCoordinate3 = GeoCoordinate.ParseString(GeoCoordinate1.ToGeoString(GeoFormat.Decimal));
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate3.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate3.Longitude.Value, 0.0000001);

            var GeoCoordinate4 = GeoCoordinate.ParseString(GeoCoordinate1.ToGeoString(GeoFormat.Sexagesimal));
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate4.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate4.Longitude.Value, 0.0000001);

            var GeoCoordinate5 = GeoCoordinate.ParseString(RandomLatitude.ToString() + ", " + RandomLongitude.ToString());
            Assert.AreEqual(RandomLatitude.Value,  GeoCoordinate5.Latitude.Value,  0.0000001);
            Assert.AreEqual(RandomLongitude.Value, GeoCoordinate5.Longitude.Value, 0.0000001);
        }
Exemplo n.º 20
0
 /// <summary>
 /// Initialize the values.
 /// </summary>
 public SPOS()
 {
     SPOS_Latitude = new Latitude();
     SPOS_Longitude = new Longitude();
     SPOS_WaterDepth = AdcpCommands.DEFAULT_WATER_DEPTH;
     SPOS_PsensHeight = AdcpCommands.DEFAULT_PSEN_HEIGHT;
 }
Exemplo n.º 21
0
 /// <summary>
 /// Add a map feature of the given dimensions at the given geo coordinate.
 /// </summary>
 /// <param name="Id">The unique identification of the feature.</param>
 /// <param name="Latitude">The latitude of the feature.</param>
 /// <param name="Longitude">The longitude of the feature.</param>
 /// <param name="Altitude">The altitude of the feature.</param>
 /// <param name="Fill">The fill brush of the feature.</param>
 /// <param name="Stroke">The stroke brush of the feature.</param>
 /// <param name="StrokeThickness">The thickness of the stroke.</param>
 public VoronoiFeature AddFeature(String Id,
                                  Latitude   Latitude,
                                  Longitude  Longitude,
                                  Altitude   Altitude,
                                  Brush      Fill,
                                  Brush      Stroke,
                                  Double     StrokeThickness)
 {
     return AddFeature(Id,
                       new GeoCoordinate(Latitude, Longitude, Altitude),
                       Fill,
                       Stroke, StrokeThickness);
 }
Exemplo n.º 22
0
 public void SetDegrees_NegativeInvalidDegreesMinutesSeconds_Exception()
 {
     var longitude = new Longitude();
     var ex        = Assert.Throws <ArgumentOutOfRangeException>(() => longitude.SetCoordinate(-200, 26, 46));
 }
Exemplo n.º 23
0
        protected override void OnSentenceChanged()
        {
            // First, process the basic info for the sentence
            base.OnSentenceChanged();

            // Cache the sentence words
            string[] words     = base.Words;
            int      wordCount = words.Length;

            /*
             * $GPRMC
             *
             *   Recommended minimum specific GPS/Transit data
             *
             *   eg1. $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
             *   eg2. $GPRMC,225446,A,4916.45,N,12311.12,W,000.5,054.7,191194,020.3,E*68
             *
             *
             *              225446       Time of fix 22:54:46 UTC
             *              A            Navigation receiver warning A = OK, V = warning
             *              4916.45,N    Latitude 49 deg. 16.45 min North
             *              12311.12,W   Longitude 123 deg. 11.12 min West
             *              000.5        Speed over ground, Knots
             *              054.7        Course Made Good, True
             *              191194       Date of fix  19 November 1994
             *              020.3,E      Magnetic variation 20.3 deg East
             * 68          mandatory checksum
             *
             *
             *   eg3. $GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70
             *                 1    2    3    4    5     6    7    8      9     10  11 12
             *
             *
             *         1   220516     Time Stamp
             *         2   A          validity - A-ok, V-invalid
             *         3   5133.82    current Latitude
             *         4   N          North/South
             *         5   00042.24   current Longitude
             *         6   W          East/West
             *         7   173.8      Speed in knots
             *         8   231.8      True course
             *         9   130694     Date Stamp
             *         10  004.2      Variation
             *         11  W          East/West
             *         12  *70        checksum
             *
             *
             *   eg4. $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh
             *   1    = UTC of position fix
             *   2    = Data status (V=navigation receiver warning)
             *   3    = Latitude of fix
             *   4    = N or S
             *   5    = Longitude of fix
             *   6    = E or W
             *   7    = Speed over ground in knots
             *   8    = Track made good in degrees True
             *   9    = UT date
             *   10   = Magnetic variation degrees (Easterly var. subtracts from true course)
             *   11   = E or W
             *   12   = Checksum
             */


            // Do we have enough words to parse the fix status?
            if (wordCount >= 2 && words[1].Length != 0)
            {
                #region Fix status

                // Get the fix flag
                _FixStatus = words[1].Equals("A", StringComparison.OrdinalIgnoreCase) ? FixStatus.Fix : FixStatus.NoFix;

                #endregion
            }
            else
            {
                // The fix status is invalid
                _FixStatus = FixStatus.Unknown;
            }

            // Do we have enough words to parse the UTC date/time?
            if (wordCount >= 9 && words[0].Length != 0 && words[8].Length != 0)
            {
                #region Parse the UTC time

                string utcTimeWord     = words[0];
                int    utcHours        = int.Parse(utcTimeWord.Substring(0, 2), NmeaCultureInfo);       // AA
                int    utcMinutes      = int.Parse(utcTimeWord.Substring(2, 2), NmeaCultureInfo);       // BB
                int    utcSeconds      = int.Parse(utcTimeWord.Substring(4, 2), NmeaCultureInfo);       // CC
                int    utcMilliseconds = 0;
                if (utcTimeWord.Length > 6)
                {
                    utcMilliseconds = Convert.ToInt32(float.Parse(utcTimeWord.Substring(6), NmeaCultureInfo) * 1000, NmeaCultureInfo);    // DDDD
                }
                #endregion

                #region Parse the UTC date

                string utcDateWord = words[8];
                int    utcDay      = int.Parse(utcDateWord.Substring(0, 2), NmeaCultureInfo);
                int    utcMonth    = int.Parse(utcDateWord.Substring(2, 2), NmeaCultureInfo);
                int    utcYear     = int.Parse(utcDateWord.Substring(4, 2), NmeaCultureInfo) + 2000;

                #endregion

                #region Build a UTC date/time

                _UtcDateTime = new DateTime(utcYear, utcMonth, utcDay, utcHours, utcMinutes, utcSeconds, utcMilliseconds, DateTimeKind.Utc);

                #endregion
            }
            else
            {
                // The UTC date/time is invalid
                _UtcDateTime = DateTime.MinValue;
            }

            // Do we have enough data to parse the location?
            if (wordCount >= 6 && words[2].Length != 0 && words[3].Length != 0 && words[4].Length != 0 && words[5].Length != 0)
            {
                #region Parse the latitude

                string             latitudeWord           = words[2];
                int                latitudeHours          = int.Parse(latitudeWord.Substring(0, 2), NmeaCultureInfo);
                double             latitudeDecimalMinutes = double.Parse(latitudeWord.Substring(2), NmeaCultureInfo);
                LatitudeHemisphere latitudeHemisphere     =
                    words[3].Equals("N", StringComparison.Ordinal) ? LatitudeHemisphere.North : LatitudeHemisphere.South;

                #endregion

                #region Parse the longitude

                string longitudeWord                    = words[4];
                int    longitudeHours                   = int.Parse(longitudeWord.Substring(0, 3), NmeaCultureInfo);
                double longitudeDecimalMinutes          = double.Parse(longitudeWord.Substring(3), NmeaCultureInfo);
                LongitudeHemisphere longitudeHemisphere =
                    words[5].Equals("E", StringComparison.Ordinal) ? LongitudeHemisphere.East : LongitudeHemisphere.West;

                #endregion

                #region Build a Position from the latitude and longitude

                _Position = new Position(
                    new Latitude(latitudeHours, latitudeDecimalMinutes, latitudeHemisphere),
                    new Longitude(longitudeHours, longitudeDecimalMinutes, longitudeHemisphere));

                #endregion
            }
            else
            {
                _Position = Position.Invalid;
            }

            // Do we have enough info to process speed?
            if (wordCount >= 7 && words[6].Length != 0)
            {
                #region Speed

                // The speed is the sixth word, expressed in knots
                _Speed = new Speed(double.Parse(words[6], NmeaCultureInfo), SpeedUnit.Knots);

                #endregion
            }
            else
            {
                // The speed is invalid
                _Speed = Speed.Invalid;
            }

            // do we have enough info to process the bearing?
            if (wordCount >= 8 && words[7].Length != 0)
            {
                #region Bearing

                // The bearing is the seventh word
                _Bearing = new Azimuth(double.Parse(words[7], NmeaCultureInfo));

                #endregion
            }
            else
            {
                // The bearing is invalid
                _Bearing = Azimuth.Invalid;
            }

            // Do we have enough info for magnetic variation?
            if (wordCount >= 10 && words[9].Length != 0)
            {
                // Parse the value
                _MagneticVariation = new Longitude(double.Parse(words[9], NmeaCultureInfo));
            }
            else
            {
                // The magnetic variation is invalid
                _MagneticVariation = Longitude.Invalid;
            }
        }
Exemplo n.º 24
0
        public void RawAngleConstructorTest5()
        {
            Angle angle = new Angle(-180);

            Longitude longitude = new Longitude(angle);

            Assert.AreEqual(CardinalDirection.West, longitude.Hemisphere);
            Assert.AreEqual(-angle, longitude.Value);
            Assert.AreEqual(angle, longitude.RawValue);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Corrects this classes properties after the base sentence was changed.
        /// </summary>
        private new void SetPropertiesFromSentence()
        {
            // Cache the sentence words
            string[] words     = Words;
            int      wordCount = words.Length;

            /*
             * $GPRMC
             *
             *   Recommended minimum specific GPS/Transit data
             *
             *   eg1. $GPRMC, 081836, A, 3751.65, S, 14507.36, E, 000.0, 360.0, 130998, 011.3, E*62
             *   eg2. $GPRMC, 225446, A, 4916.45, N, 12311.12, W, 000.5, 054.7, 191194, 020.3, E*68
             *
             *              225446       Time of fix 22:54:46 UTC
             *              A            Navigation receiver warning A = OK, V = warning
             *              4916.45, N    Latitude 49 deg. 16.45 min North
             *              12311.12, W   Longitude 123 deg. 11.12 min West
             *              000.5        Speed over ground, Knots
             *              054.7        Course Made Good, True
             *              191194       Date of fix  19 November 1994
             *              020.3, E      Magnetic variation 20.3 deg East
             * 68          mandatory checksum
             *
             *   eg3. $GPRMC, 220516, A, 5133.82, N, 00042.24, W, 173.8, 231.8, 130694, 004.2, W*70
             *                 1      2    3      4    5       6    7      8      9      10   11 12
             *
             *         1   220516     Time Stamp
             *         2   A          validity - A-ok, V-invalid
             *         3   5133.82    current Latitude
             *         4   N          North/South
             *         5   00042.24   current Longitude
             *         6   W          East/West
             *         7   173.8      Speed in knots
             *         8   231.8      True course
             *         9   130694     Date Stamp
             *         10  004.2      Variation
             *         11  W          East/West
             *         12  *70        checksum
             *
             *   eg4. $GPRMC, hhmmss.ss, A, llll.ll, a, yyyyy.yy, a, x.x, x.x, ddmmyy, x.x, a*hh
             *   1    = UTC of position fix
             *   2    = Data status (V=navigation receiver warning)
             *   3    = Latitude of fix
             *   4    = N or S
             *   5    = Longitude of fix
             *   6    = E or W
             *   7    = Speed over ground in knots
             *   8    = Track made good in degrees True
             *   9    = UT date
             *   10   = Magnetic variation degrees (Easterly var. subtracts from true course)
             *   11   = E or W
             *   12   = Checksum
             */

            FixStatus   = ParseFixStatus(1);
            UtcDateTime = ParseUtcDateTime(0, 8);
            Position    = ParsePosition(2, 3, 4, 5);
            Speed       = ParseSpeed(6, SpeedUnit.Knots);
            Bearing     = ParseAzimuth(7);


            // Do we have enough info for magnetic variation?
            if (wordCount > 10 && words[9].Length != 0 && words[10].Length != 0)
            {
                MagneticVariation = new Longitude(double.Parse(words[9], NmeaCultureInfo), words[10].Equals("E", StringComparison.Ordinal) ? LongitudeHemisphere.East : LongitudeHemisphere.West);
            }
            else
            {
                MagneticVariation = Longitude.Invalid;
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Compares the current instance to the specified position using the specified numeric precision.
 /// </summary>
 /// <param name="other">A <strong>Position</strong> object to compare with.</param>
 /// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param>
 /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns>
 /// <remarks>This method is typically used when positions do not mark the same location unless they are
 /// extremely close to one another.  Conversely, a low or even negative value for <strong>Precision</strong>
 /// allows positions to be considered equal even when they do not precisely match.</remarks>
 public bool Equals(Position3D other, int decimals)
 {
     return(Latitude.Equals(other.Latitude, decimals) &&
            Longitude.Equals(other.Longitude, decimals) &&
            _altitude.Equals(other.Altitude, decimals));
 }
Exemplo n.º 27
0
 public static string AsDegreesMinutesSeconds(Longitude longitude)
 {
     return AsDegreesMinutesSeconds(longitude.Value, longitude.Hemisphere);
 }
Exemplo n.º 28
0
 /// <summary>
 ///     Serves as a hash function for the GeoCoordinate.
 /// </summary>
 /// <returns>
 ///     A hash code for the current GeoCoordinate.
 /// </returns>
 public override int GetHashCode()
 {
     return(Latitude.GetHashCode() ^ Longitude.GetHashCode());
 }
Exemplo n.º 29
0
 /// <summary>
 /// Converts the given world coordinates and zoom level to the X and Y number of map tiles.
 /// </summary>
 /// <param name="Latitude">The latitude.</param>
 /// <param name="Longitude">The longitude.</param>
 /// <param name="ZoomLevel">The ZoomLevel.</param>
 /// <returns>The TileX and TileY number as a tuple.</returns>
 public static Tuple<UInt64, UInt64> WorldCoordinates_2_Tile(Latitude Latitude, Longitude Longitude, UInt32 ZoomLevel)
 {
     return new Tuple<UInt64, UInt64>(
         (UInt64) Math.Floor(((Longitude.Value + 180.0) / 360.0) * (1 << (Int32) ZoomLevel)),
         (UInt64) Math.Floor((1.0 - Math.Log (
                                                       Math.Tan(Latitude.Value * Math.PI / 180.0) +
                                                 1.0 / Math.Cos(Latitude.Value * Math.PI / 180.0)
                                             ) / Math.PI)
                             / 2.0 * (1 << (Int32) ZoomLevel))
     );
 }
Exemplo n.º 30
0
 /// <summary>
 /// Converts the given <paramref name="longitude"/> to degrees in the range of [-180, 180]
 /// where 0 is the prime meridian.
 /// </summary>
 /// <param name="longitude">The longitude to convert.</param>
 /// <returns>Returns the longitude in degrees.</returns>
 public static double ToDegrees(this Longitude longitude) =>
 longitude.GetDirectionFactor() * (longitude.Degrees + longitude.Minutes / 60.0 + longitude.Seconds / 3600.0);
Exemplo n.º 31
0
 /// <summary>
 /// Compares the current instance to the specified position.
 /// </summary>
 /// <param name="other">A <strong>Position</strong> object to compare with.</param>
 /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns>
 /// <remarks>The two objects are compared at up to four digits of precision.</remarks>
 public bool Equals(Position3D other)
 {
     return(Latitude.Equals(other.Latitude) &&
            Longitude.Equals(other.Longitude) &&
            _altitude.Equals(other.Altitude));
 }
Exemplo n.º 32
0
 public GeoPosition(Latitude latitude, Longitude longitude, Length altitude = null)
 {
     _latitude = latitude;
     _longitude = longitude;
     _altitude = altitude;
 }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Position3D"/> struct.
 /// </summary>
 /// <param name="longitude">The longitude.</param>
 /// <param name="latitude">The latitude.</param>
 /// <param name="altitude">The altitude.</param>
 public Position3D(Longitude longitude, Latitude latitude, Distance altitude)
 {
     _position = new Position(latitude, longitude);
     _altitude = altitude;
 }
Exemplo n.º 34
0
 public static GeoPosition New(Latitude latitude, Longitude longitude, Length altitude)
 {
     return new GeoPosition(latitude, longitude, altitude);
 }
Exemplo n.º 35
0
        public void Not_allow_longitude_could_be_greater_than_180()
        {
            Action position = () => new Coordinates(Latitude.FromScalar(-90), Longitude.FromScalar(240));

            position.Should().Throw <ArgumentException>().WithMessage(CoreStrings.InvalidLongitude);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Overrides OnSentanceChanged for the GPVTGSentence
        /// </summary>
        protected override void OnSentenceChanged()
        {
            // First, process the basic info for the sentence
            base.OnSentenceChanged();

            // Cache the sentence words
            string[] words = base.Words;
            int wordCount = words.Length;

            /*
             * $GPVTG

                Track Made Good and Ground Speed.

                eg1. $GPVTG,360.0,T,348.7,M,000.0,N,000.0,K*43
                eg2. $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K


                           054.7,T      True track made good
                           034.4,M      Magnetic track made good
                           005.5,N      Ground speed, knots
                           010.2,K      Ground speed, Kilometers per hour


                eg3. $GPVTG,t,T,,,s.ss,N,s.ss,K*hh
                1    = Track made good
                2    = Fixed text 'T' indicates that track made good is relative to true north
                3    = not used
                4    = not used
                5    = Speed over ground in knots
                6    = Fixed text 'N' indicates that speed over ground in in knots
                7    = Speed over ground in kilometers/hour
                8    = Fixed text 'K' indicates that speed over ground is in kilometers/hour

             * 
             * 
             */

            #region Bearing

            if (wordCount >= 1 && words[0].Length != 0)
                _Bearing = Azimuth.Parse(words[0], NmeaCultureInfo);
            else
                _Bearing = Azimuth.Invalid;

            #endregion

            #region Magnetic Variation

            if (wordCount >= 3 && words[2].Length != 0)
                _MagneticVariation = new Longitude(double.Parse(words[2], NmeaCultureInfo) - _Bearing.DecimalDegrees);
            else
                _MagneticVariation = Longitude.Invalid;

            #endregion

            #region Speed

            /* Speed is reported as both knots and KM/H.  We can parse either of the values.
             * First, try to parse knots.  If that fails, parse KM/h.
             */

            if (wordCount > 6 && words[5].Length != 0)
            {
                _Speed = new Speed(
                    // Parse the numeric portion
                    double.Parse(words[5], NmeaCultureInfo),
                    // Use knots 
                    SpeedUnit.Knots);
            }
            else if (wordCount > 8 && words[7].Length != 0)
            {
                _Speed = new Speed(
                    // Parse the numeric portion
                    double.Parse(words[7], NmeaCultureInfo),
                    // Use knots 
                    SpeedUnit.KilometersPerHour);
            }
            else
            {
                // Invalid speed
                _Speed = Speed.Invalid;
            }

            #endregion
        }
Exemplo n.º 37
0
 private static int GetDirectionFactor(this Longitude longitude) =>
 longitude.Direction == LongitudeDirection.East ? 1 : -1;
Exemplo n.º 38
0
 /// <summary>
 /// Does the initialize.
 /// </summary>
 private void DoInitialize()
 {
     _altitude = Distance.Invalid;
     _altitudeAboveEllipsoid = _altitude;
     _bearing = Azimuth.Invalid;
     _heading = Azimuth.Invalid;
     _fixStatus = FixStatus.Unknown;
     _horizontalDop = DilutionOfPrecision.Maximum;
     _magneticVariation = Longitude.Invalid;
     _position = Position.Invalid;
     _speed = Speed.Invalid;
     _meanDop = DilutionOfPrecision.Invalid;
     _verticalDop = DilutionOfPrecision.Invalid;
     if (_satellites != null)
         _satellites.Clear();
 }
Exemplo n.º 39
0
        public void Ctor_DegreesMinutesSeconds()
        {
            var longitude = new Longitude(-79, 58, 56);

            this.AssertCoordinateData(longitude);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Updates the difference between Magnetic North and True North.
        /// </summary>
        /// <param name="value">The value.</param>
        protected virtual void SetMagneticVariation(Longitude value)
        {
            // If the new value is the same or it's invalid, ignore it
            if (_magneticVariation.Equals(value) || value.IsInvalid)
                return;

            // Yes.  Set the new value
            _magneticVariation = value;

            // And notify of the change
            if (MagneticVariationAvailable != null)
                MagneticVariationAvailable(this, new LongitudeEventArgs(_magneticVariation));
        }
Exemplo n.º 41
0
 public void SetDegrees_InvalidDegrees_Exception(decimal degrees)
 {
     var longitude = new Longitude();
     var ex        = Assert.Throws <ArgumentOutOfRangeException>(() => longitude.SetCoordinate(degrees));
 }
Exemplo n.º 42
0
 public override int GetHashCode() =>
 unchecked ((Latitude.GetHashCode() * 397) ^ Longitude.GetHashCode());
Exemplo n.º 43
0
 public void SetDegrees_InvalidDegreesMinutes_Exception()
 {
     var longitude = new Longitude();
     var ex        = Assert.Throws <ArgumentOutOfRangeException>(() => longitude.SetCoordinate(200, 26.767m));
 }
Exemplo n.º 44
0
 public override string ToString() =>
 Latitude.ToString("#0.0#######", CultureInfo.InvariantCulture) + "," +
 Longitude.ToString("#0.0#######", CultureInfo.InvariantCulture);
Exemplo n.º 45
0
        protected override void OnSentenceChanged()
        {
            // First, process the basic info for the sentence
            base.OnSentenceChanged();

            // Cache the sentence words
            string[] words     = base.Words;
            int      wordCount = words.Length;

            /*
             * $GPVTG
             *
             *  Track Made Good and Ground Speed.
             *
             *  eg1. $GPVTG,360.0,T,348.7,M,000.0,N,000.0,K*43
             *  eg2. $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K
             *
             *
             *             054.7,T      True track made good
             *             034.4,M      Magnetic track made good
             *             005.5,N      Ground speed, knots
             *             010.2,K      Ground speed, Kilometers per hour
             *
             *
             *  eg3. $GPVTG,t,T,,,s.ss,N,s.ss,K*hh
             *  1    = Track made good
             *  2    = Fixed text 'T' indicates that track made good is relative to true north
             *  3    = not used
             *  4    = not used
             *  5    = Speed over ground in knots
             *  6    = Fixed text 'N' indicates that speed over ground in in knots
             *  7    = Speed over ground in kilometers/hour
             *  8    = Fixed text 'K' indicates that speed over ground is in kilometers/hour
             *
             *
             *
             */

            #region Bearing

            if (wordCount >= 1 && words[0].Length != 0)
            {
                _Bearing = Azimuth.Parse(words[0], NmeaCultureInfo);
            }
            else
            {
                _Bearing = Azimuth.Invalid;
            }

            #endregion

            #region Magnetic Variation

            if (wordCount >= 3 && words[2].Length != 0)
            {
                _MagneticVariation = new Longitude(double.Parse(words[2], NmeaCultureInfo) - _Bearing.DecimalDegrees);
            }
            else
            {
                _MagneticVariation = Longitude.Invalid;
            }

            #endregion

            #region Speed

            /* Speed is reported as both knots and KM/H.  We can parse either of the values.
             * First, try to parse knots.  If that fails, parse KM/h.
             */

            if (wordCount > 6 && words[5].Length != 0)
            {
                _Speed = new Speed(
                    // Parse the numeric portion
                    double.Parse(words[5], NmeaCultureInfo),
                    // Use knots
                    SpeedUnit.Knots);
            }
            else if (wordCount > 8 && words[7].Length != 0)
            {
                _Speed = new Speed(
                    // Parse the numeric portion
                    double.Parse(words[7], NmeaCultureInfo),
                    // Use knots
                    SpeedUnit.KilometersPerHour);
            }
            else
            {
                // Invalid speed
                _Speed = Speed.Invalid;
            }

            #endregion
        }
Exemplo n.º 46
0
 /// <inheritdoc />
 public bool Equals(GeoPosition other)
 {
     return(Nullable.Equals(Altitude, other.Altitude) && Longitude.Equals(other.Longitude) && Latitude.Equals(other.Latitude));
 }
Exemplo n.º 47
0
        public GprmcSentence(DateTime utcDateTime, bool isFixAcquired, Position position, Speed speed, Azimuth bearing, Longitude magneticVariation)
        {
            // Use a string builder to create the sentence text
            StringBuilder builder = new StringBuilder(128);

            /* GPRMC sentences have the following format:
             *
             * $GPRMC,040302.663,A,3939.7,N,10506.6,W,0.27,358.86,200804,,*1A
             */

            // Append the command word, $GPRMC
            builder.Append("$GPRMC");

            // Append a comma
            builder.Append(',');

            #region Append the UTC time

            builder.Append(utcDateTime.Hour.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Minute.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Second.ToString("0#", NmeaCultureInfo));
            builder.Append(".");
            builder.Append(utcDateTime.Millisecond.ToString("00#", NmeaCultureInfo));

            #endregion

            // Append a comma
            builder.Append(',');

            #region Append the fix status

            // Write fix information
            if (isFixAcquired)
            {
                builder.Append("A");
            }
            else
            {
                builder.Append("V");
            }

            #endregion

            // Append a comma
            builder.Append(',');

            #region Append the position

            // Append latitude in the format HHMM.MMMM.
            builder.Append(position.Latitude.ToString("HHMM.MMMM,I,", NmeaCultureInfo));
            // Append Longitude in the format HHHMM.MMMM.
            builder.Append(position.Longitude.ToString("HHHMM.MMMM,I,", NmeaCultureInfo));

            #endregion

            // Append the speed (in knots)
            builder.Append(speed.ToKnots().ToString("v.v", NmeaCultureInfo));

            // Append a comma
            builder.Append(',');

            // Append the bearing
            builder.Append(bearing.ToString("d.d", NmeaCultureInfo));

            // Append a comma
            builder.Append(',');

            #region Append the UTC date

            // Append UTC date
            builder.Append(utcDateTime.Day.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Month.ToString("0#", NmeaCultureInfo));

            // Append the year (year minus 2000)
            int year = utcDateTime.Year - 2000;
            builder.Append(year.ToString("0#", NmeaCultureInfo));

            #endregion

            // Append a comma
            builder.Append(',');

            // Append magnetic variation
            builder.Append(magneticVariation.ToString("d.d", NmeaCultureInfo));

            // Set this object's sentence
            SetSentence(builder.ToString());

            // Finally, append the checksum
            AppendChecksum();
        }
Exemplo n.º 48
0
        private IReadOnlyDictionary <string, string> GetProperties(DiscordGuild guild, WhConfig whConfig, string city, GymDetailsData oldGym)
        {
            var exEmojiId = MasterFile.Instance.Emojis["ex"];
            var exEmoji   = string.IsNullOrEmpty(MasterFile.Instance.CustomEmojis["ex"]) ? exEmojiId > 0
                ? string.Format(Strings.EmojiSchema, "ex", exEmojiId): "EX"
                : MasterFile.Instance.CustomEmojis["ex"];
            var teamEmojiId = MasterFile.Instance.Emojis[Team.ToString().ToLower()];
            var teamEmoji   = string.IsNullOrEmpty(MasterFile.Instance.CustomEmojis[Team.ToString().ToLower()])
                ? teamEmojiId > 0
                    ? string.Format(Strings.EmojiSchema, Team.ToString().ToLower(), teamEmojiId)
                    : Team.ToString()
                : MasterFile.Instance.CustomEmojis[Team.ToString().ToLower()];
            var oldTeamEmojiId = MasterFile.Instance.Emojis[oldGym?.Team.ToString().ToLower()];
            var oldTeamEmoji   = string.IsNullOrEmpty(MasterFile.Instance.CustomEmojis[oldGym?.Team.ToString().ToLower()])
                ? oldTeamEmojiId > 0
                    ? string.Format(Strings.EmojiSchema, oldGym?.Team.ToString().ToLower(), oldTeamEmojiId)
                    : oldGym?.Team.ToString()
                : MasterFile.Instance.CustomEmojis[oldGym.Team.ToString().ToLower()];

            var gmapsLink       = string.Format(Strings.GoogleMaps, Latitude, Longitude);
            var appleMapsLink   = string.Format(Strings.AppleMaps, Latitude, Longitude);
            var wazeMapsLink    = string.Format(Strings.WazeMaps, Latitude, Longitude);
            var scannerMapsLink = string.Format(whConfig.Urls.ScannerMap, Latitude, Longitude);
            var gymImageUrl     = $"https://raw.githubusercontent.com/nileplumb/PkmnHomeIcons/ICONS/ICONS/gym/{Convert.ToInt32(Team)}.png"; // TODO: Build gym image url
            var staticMapLink   = StaticMap.GetUrl(whConfig.Urls.StaticMap, whConfig.StaticMaps["gyms"], Latitude, Longitude, gymImageUrl);
            //var staticMapLink = string.Format(whConfig.Urls.StaticMap, Latitude, Longitude);//whConfig.Urls.StaticMap.Gyms.Enabled ? string.Format(whConfig.Urls.StaticMap.Gyms.Url, Latitude, Longitude) : string.Empty
            var gmapsLocationLink       = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, gmapsLink);
            var appleMapsLocationLink   = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, appleMapsLink);
            var wazeMapsLocationLink    = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, wazeMapsLink);
            var scannerMapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, scannerMapsLink);
            var address = new Location(null, city, Latitude, Longitude).GetAddress(whConfig);
            //var staticMapLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? staticMapLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, staticMapLink);

            const string defaultMissingValue = "?";
            var          dict = new Dictionary <string, string>
            {
                //Main properties
                { "gym_id", GymId },
                { "gym_name", GymName },
                { "gym_url", Url },
                { "gym_team", Team.ToString() },
                { "gym_team_id", Convert.ToInt32(Team).ToString() },
                { "gym_team_emoji", teamEmoji },
                { "old_gym_team", oldGym.Team.ToString() },
                { "old_gym_team_id", Convert.ToInt32(oldGym.Team).ToString() },
                { "old_gym_team_emoji", oldTeamEmoji },
                { "team_changed", Convert.ToString(oldGym?.Team != Team) },
                { "in_battle", Convert.ToString(InBattle) },
                { "under_attack", Convert.ToString(InBattle) },
                { "is_ex", Convert.ToString(SponsorId) },
                { "ex_emoji", exEmoji },
                { "slots_available", SlotsAvailable == 0
                                        ? "Full"
                                        : SlotsAvailable == 6
                                            ? "Empty"
                                            : SlotsAvailable.ToString("N0") },

                //Location properties
                { "geofence", city ?? defaultMissingValue },
                { "lat", Latitude.ToString() },
                { "lng", Longitude.ToString() },
                { "lat_5", Latitude.ToString("0.00000") },
                { "lng_5", Longitude.ToString("0.00000") },

                //Location links
                { "tilemaps_url", staticMapLink },
                { "gmaps_url", gmapsLocationLink },
                { "applemaps_url", appleMapsLocationLink },
                { "wazemaps_url", wazeMapsLocationLink },
                { "scanmaps_url", scannerMapsLocationLink },

                { "address", address?.Address },

                // Discord Guild properties
                { "guild_name", guild?.Name },
                { "guild_img_url", guild?.IconUrl },

                { "date_time", DateTime.Now.ToString() },

                //Misc properties
                { "br", "\r\n" }
            };

            return(dict);
        }
Exemplo n.º 49
0
        private IReadOnlyDictionary <string, string> GetProperties(DiscordClient client, WhConfig whConfig, string city)
        {
            string icon;

            if (HasInvasion)
            {
                //TODO: Load from local file
                icon = "https://map.ver.sx/static/img/pokestop/i0.png";
            }
            else if (HasLure)
            {
                icon = string.Format(whConfig.Urls.QuestImage, Convert.ToInt32(LureType));
            }
            else
            {
                icon = Url;
            }
            var gmapsLink             = string.Format(Strings.GoogleMaps, Latitude, Longitude);
            var appleMapsLink         = string.Format(Strings.AppleMaps, Latitude, Longitude);
            var wazeMapsLink          = string.Format(Strings.WazeMaps, Latitude, Longitude);
            var staticMapLink         = Utils.PrepareStaticMapUrl(whConfig.Urls.StaticMap, icon, Latitude, Longitude);
            var gmapsLocationLink     = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? gmapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, gmapsLink);
            var appleMapsLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? appleMapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, appleMapsLink);
            var wazeMapsLocationLink  = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? wazeMapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, wazeMapsLink);
            //var staticMapLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? staticMapLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, staticMapLink);
            var invasion           = new TeamRocketInvasion(GruntType);
            var leaderString       = GetGruntLeaderString(GruntType);
            var invasionEncounters = invasion.GetPossibleInvasionEncounters();

            const string defaultMissingValue = "?";
            var          dict = new Dictionary <string, string>
            {
                //Main properties
                { "has_lure", Convert.ToString(HasLure) },
                { "lure_type", LureType.ToString() },
                { "lure_expire_time", LureExpireTime.ToLongTimeString() },
                { "lure_expire_time_left", LureExpireTime.GetTimeRemaining().ToReadableStringNoSeconds() },
                { "has_invasion", Convert.ToString(HasInvasion) },
                { "grunt_type", invasion.Type == PokemonType.None ? leaderString : invasion?.Type.ToString() },
                { "grunt_type_emoji", invasion.Type == PokemonType.None ? leaderString : client.Guilds.ContainsKey(whConfig.Discord.EmojiGuildId) ?
                  invasion.Type.GetTypeEmojiIcons(client.Guilds[whConfig.Discord.GuildId]) :
                  string.Empty },
                { "grunt_gender", invasion.Gender.ToString() },
                { "invasion_expire_time", InvasionExpireTime.ToLongTimeString() },
                { "invasion_expire_time_left", InvasionExpireTime.GetTimeRemaining().ToReadableStringNoSeconds() },
                { "invasion_encounters", $"**Encounter Reward Chance:**\r\n" + invasionEncounters },

                //Location properties
                { "geofence", city ?? defaultMissingValue },
                { "lat", Latitude.ToString() },
                { "lng", Longitude.ToString() },
                { "lat_5", Math.Round(Latitude, 5).ToString() },
                { "lng_5", Math.Round(Longitude, 5).ToString() },

                //Location links
                { "tilemaps_url", staticMapLink },
                { "gmaps_url", gmapsLocationLink },
                { "applemaps_url", appleMapsLocationLink },
                { "wazemaps_url", wazeMapsLocationLink },

                //Pokestop properties
                { "pokestop_id", PokestopId ?? defaultMissingValue },
                { "pokestop_name", Name ?? defaultMissingValue },
                { "pokestop_url", Url ?? defaultMissingValue },

                //Misc properties
                { "br", "\r\n" }
            };

            return(dict);
        }
Exemplo n.º 50
0
        /// <summary>
        /// Converts the current instance to a geodetic (latitude/longitude) coordinate using the specified ellipsoid.
        /// </summary>
        /// <param name="ellipsoid">The ellipsoid.</param>
        /// <returns>A <strong>Position</strong> object containing the converted result.</returns>
        /// <remarks>The conversion formula will convert the Cartesian coordinate to
        /// latitude and longitude using the WGS1984 ellipsoid (the default ellipsoid for
        /// GPS coordinates).  The resulting three-dimensional coordinate is accurate to within two millimeters
        /// (2 mm).</remarks>
        public Position3D ToPosition3D(Ellipsoid ellipsoid)
        {
            if (ellipsoid == null)
            {
                throw new ArgumentNullException("ellipsoid");
            }

            #region New code

            /*
             * % ECEF2LLA - convert earth-centered earth-fixed (ECEF)
             * %            cartesian coordinates to latitude, longitude,
             * %            and altitude
             * %
             * % USAGE:
             * % [lat, lon, alt] = ecef2lla(x, y, z)
             * %
             * % lat = geodetic latitude (radians)
             * % lon = longitude (radians)
             * % alt = height above WGS84 ellipsoid (m)
             * % x = ECEF X-coordinate (m)
             * % y = ECEF Y-coordinate (m)
             * % z = ECEF Z-coordinate (m)
             * %
             * % Notes: (1) This function assumes the WGS84 model.
             * %        (2) Latitude is customary geodetic (not geocentric).
             * %        (3) Inputs may be scalars, vectors, or matrices of the same
             * %            size and shape. Outputs will have that same size and shape.
             * %        (4) Tested but no warranty; use at your own risk.
             * %        (5) Michael Kleder, April 2006
             *
             * function [lat, lon, alt] = ecef2lla(x, y, z)
             *
             * % WGS84 ellipsoid constants:
             * a = 6378137;
             * e = 8.1819190842622e-2;
             *
             * % calculations:
             * b   = sqrt(a^2*(1-e^2));
             * ep  = sqrt((a^2-b^2)/b^2);
             * p   = sqrt(x.^2+y.^2);
             * th  = atan2(a*z, b*p);
             * lon = atan2(y, x);
             * lat = atan2((z+ep^2.*b.*sin(th).^3), (p-e^2.*a.*cos(th).^3));
             * N   = a./sqrt(1-e^2.*sin(lat).^2);
             * alt = p./cos(lat)-N;
             *
             * % return lon in range [0, 2*pi)
             * lon = mod(lon, 2*pi);
             *
             * % correct for numerical instability in altitude near exact poles:
             * % (after this correction, error is about 2 millimeters, which is about
             * % the same as the numerical precision of the overall function)
             *
             * k=abs(x)<1 & abs(y)<1;
             * alt(k) = abs(z(k))-b;
             *
             * return
             */

            double x = _x.ToMeters().Value;
            double y = _y.ToMeters().Value;
            double z = _z.ToMeters().Value;

            //% WGS84 ellipsoid constants:
            // a = 6378137;

            double a = ellipsoid.EquatorialRadius.ToMeters().Value;

            // e = 8.1819190842622e-2;

            double e = ellipsoid.Eccentricity;

            //% calculations:
            // b   = sqrt(a^2*(1-e^2));

            double b = Math.Sqrt(Math.Pow(a, 2) * (1 - Math.Pow(e, 2)));

            // ep  = sqrt((a^2-b^2)/b^2);

            double ep = Math.Sqrt((Math.Pow(a, 2) - Math.Pow(b, 2)) / Math.Pow(b, 2));

            // p   = sqrt(x.^2+y.^2);

            double p = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));

            // th  = atan2(a*z, b*p);

            double th = Math.Atan2(a * z, b * p);

            // lon = atan2(y, x);

            double lon = Math.Atan2(y, x);

            // lat = atan2((z+ep^2.*b.*sin(th).^3), (p-e^2.*a.*cos(th).^3));

            double lat = Math.Atan2((z + Math.Pow(ep, 2) * b * Math.Pow(Math.Sin(th), 3)), (p - Math.Pow(e, 2) * a * Math.Pow(Math.Cos(th), 3)));

            // N   = a./sqrt(1-e^2.*sin(lat).^2);

            double n = a / Math.Sqrt(1 - Math.Pow(e, 2) * Math.Pow(Math.Sin(lat), 2));

            // alt = p./cos(lat)-N;

            double alt = p / Math.Cos(lat) - n;

            //% return lon in range [0, 2*pi)
            // lon = mod(lon, 2*pi);

            lon = lon % (2 * Math.PI);

            //% correct for numerical instability in altitude near exact poles:
            //% (after this correction, error is about 2 millimeters, which is about
            //% the same as the numerical precision of the overall function)

            // k=abs(x)<1 & abs(y)<1;

            bool k = Math.Abs(x) < 1.0 && Math.Abs(y) < 1.0;

            // alt(k) = abs(z(k))-b;

            if (k)
            {
                alt = Math.Abs(z) - b;
            }

            // return

            return(new Position3D(
                       Distance.FromMeters(alt),
                       Latitude.FromRadians(lat),
                       Longitude.FromRadians(lon)));

            #endregion New code
        }
 public Coordinate(Longitude longitude, Latitude latitude)
 {
     _Longitude = longitude;
     _Latitude = latitude;
 }
Exemplo n.º 52
0
        public override string ToString()
        {
            var nfi = CultureInfo.InvariantCulture.NumberFormat;

            return($"[{Latitude?.ToString(nfi)}, {Longitude?.ToString(nfi)}] {Info}");
        }
Exemplo n.º 53
0
 /// <summary>
 /// Creates a new instance containing the specified Longitude object.
 /// </summary>
 /// <param name="longitude">The longitude.</param>
 public LongitudeEventArgs(Longitude longitude)
 {
     _longitude = longitude;
 }
Exemplo n.º 54
0
 protected bool Equals(GeoPoint other)
 {
     return(Longitude.Equals(other.Longitude) && Latitude.Equals(other.Latitude) &&
            Easting == other.Easting && Northing == other.Northing);
 }
Exemplo n.º 55
0
		/// <summary>
		/// Creates a new instance containing the specified Longitude object.
		/// </summary>

		public LongitudeEventArgs(Longitude longitude)
		{
			_Longitude = longitude;
		}
Exemplo n.º 56
0
        public static GeoCoordinate ParseGeoCoordinatesXML(XElement GeoCoordinatesXML,
                                                           OnExceptionDelegate OnException = null)
        {
            var EVSEGoogleXML              = GeoCoordinatesXML.Element(OICPNS.CommonTypes + "Google");
            var EVSEDecimalDegreeXML       = GeoCoordinatesXML.Element(OICPNS.CommonTypes + "DecimalDegree");
            var EVSEDegreeMinuteSecondsXML = GeoCoordinatesXML.Element(OICPNS.CommonTypes + "DegreeMinuteSeconds");

            if ((EVSEGoogleXML != null && EVSEDecimalDegreeXML != null) ||
                (EVSEGoogleXML != null && EVSEDegreeMinuteSecondsXML != null) ||
                (EVSEDecimalDegreeXML != null && EVSEDegreeMinuteSecondsXML != null))
            {
                throw new ApplicationException("Invalid GeoCoordinates XML tag: Should only include one of the following XML tags Google, DecimalDegree or DegreeMinuteSeconds!");
            }

            if (EVSEGoogleXML != null)
            {
                var Coordinates = EVSEGoogleXML.Value.Split(new Char[] { ',' }, StringSplitOptions.None);

                if (!Longitude.TryParse(Coordinates[0],
                                        out Longitude LongitudeValue))
                {
                    throw new ApplicationException("Invalid longitude in Google format provided!");
                }

                if (!Latitude.TryParse(Coordinates[1],
                                       out Latitude LatitudeValue))
                {
                    throw new ApplicationException("Invalid latitude in Google format provided!");
                }

                return(new GeoCoordinate(LatitudeValue,
                                         LongitudeValue));
            }

            if (EVSEDecimalDegreeXML != null)
            {
                if (!Longitude.TryParse(EVSEDecimalDegreeXML.ElementValueOrFail(OICPNS.CommonTypes + "Longitude",
                                                                                "No GeoCoordinates DecimalDegree Longitude XML tag provided!"),
                                        out Longitude LongitudeValue))
                {
                    throw new ApplicationException("Invalid Longitude XML tag provided!");
                }

                if (!Latitude.TryParse(EVSEDecimalDegreeXML.ElementValueOrFail(OICPNS.CommonTypes + "Latitude",
                                                                               "No GeoCoordinates DecimalDegree Latitude XML tag provided!"),
                                       out Latitude LatitudeValue))
                {
                    throw new ApplicationException("Invalid Latitude XML tag provided!");
                }

                return(new GeoCoordinate(LatitudeValue,
                                         LongitudeValue));
            }

            if (EVSEDegreeMinuteSecondsXML != null)
            {
                throw new NotImplementedException("GeoCoordinates DegreeMinuteSeconds XML parsing!");
            }

            throw new ApplicationException("Invalid GeoCoordinates XML tag: Should at least include one of the following XML tags Google, DecimalDegree or DegreeMinuteSeconds!");
        }
Exemplo n.º 57
0
        /// <summary>
        /// Creates a GprmcSentence from the specified parameters
        /// </summary>
        /// <param name="utcDateTime"></param>
        /// <param name="isFixAcquired"></param>
        /// <param name="position"></param>
        /// <param name="speed"></param>
        /// <param name="bearing"></param>
        /// <param name="magneticVariation"></param>
        public GprmcSentence(DateTime utcDateTime, bool isFixAcquired, Position position, Speed speed, Azimuth bearing, Longitude magneticVariation)
        {
            // Use a string builder to create the sentence text
            StringBuilder builder = new StringBuilder(128);

            /* GPRMC sentences have the following format:
             * 
             * $GPRMC,040302.663,A,3939.7,N,10506.6,W,0.27,358.86,200804,,*1A
             */

            // Append the command word, $GPRMC
            builder.Append("$GPRMC");

            // Append a comma
            builder.Append(',');

            #region Append the UTC time

            builder.Append(utcDateTime.Hour.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Minute.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Second.ToString("0#", NmeaCultureInfo));
            builder.Append(".");
            builder.Append(utcDateTime.Millisecond.ToString("00#", NmeaCultureInfo));

            #endregion

            // Append a comma
            builder.Append(',');            

            #region Append the fix status

            // Write fix information
            if (isFixAcquired)
                builder.Append("A");
            else
                builder.Append("V");

            #endregion

            // Append a comma
            builder.Append(',');

            #region Append the position

            // Append latitude in the format HHMM.MMMM. 
            builder.Append(position.Latitude.ToString("HHMM.MMMM,I,", NmeaCultureInfo));
            // Append Longitude in the format HHHMM.MMMM.
            builder.Append(position.Longitude.ToString("HHHMM.MMMM,I,", NmeaCultureInfo));

            #endregion

            // Append the speed (in knots)
            builder.Append(speed.ToKnots().ToString("v.v", NmeaCultureInfo));

            // Append a comma
            builder.Append(',');

            // Append the bearing
            builder.Append(bearing.ToString("d.d", NmeaCultureInfo));

            // Append a comma
            builder.Append(',');

            #region Append the UTC date

            // Append UTC date
            builder.Append(utcDateTime.Day.ToString("0#", NmeaCultureInfo));
            builder.Append(utcDateTime.Month.ToString("0#", NmeaCultureInfo));

            // Append the year (year minus 2000)
            int year = utcDateTime.Year - 2000;
            builder.Append(year.ToString("0#", NmeaCultureInfo));

            #endregion

            // Append a comma
            builder.Append(',');

            // Append magnetic variation
            builder.Append(magneticVariation.ToString("d.d", NmeaCultureInfo));

            // Set this object's sentence
            SetSentence(builder.ToString());

            // Finally, append the checksum
            AppendChecksum();
        }
Exemplo n.º 58
0
        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
        public void ReadXml(XmlReader reader)
        {
            /* The position class uses the GML 3.0 specification for XML.
             *
             * <gml:pos>X Y</gml:pos>
             *
             * ... but it is also helpful to be able to READ older versions
             * of GML, such as this one for GML 2.0:
             *
             * <gml:coord>
             *      <gml:X>double</gml:X>
             *      <gml:Y>double</gml:Y>  // optional
             *      <gml:Z>double</gml:Z>  // optional
             * </gml:coord>
             *
             */

            // .NET Complains if we don't assign values
            _position = Position.Empty;
            _altitude = Distance.Empty;
            Longitude longitude = Longitude.Empty;
            Latitude  latitude  = Latitude.Empty;

            // Move to the <gml:pos> or <gml:coord> element
            if (!reader.IsStartElement("pos", Xml.GML_XML_NAMESPACE) &&
                !reader.IsStartElement("coord", Xml.GML_XML_NAMESPACE))
            {
                reader.ReadStartElement();
            }

            switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture))
            {
            case "pos":
                // Read the "X Y" string, then split by the space between them
                string[] values = reader.ReadElementContentAsString().Split(' ');
                // Deserialize the longitude
                longitude = new Longitude(values[0], CultureInfo.InvariantCulture);

                // Deserialize the latitude
                if (values.Length >= 2)
                {
                    latitude = new Latitude(values[1], CultureInfo.InvariantCulture);
                }

                // Deserialize the altitude
                if (values.Length == 3)
                {
                    _altitude = Distance.FromMeters(double.Parse(values[2], CultureInfo.InvariantCulture));
                }

                // Make the position
                _position = new Position(latitude, longitude);
                break;

            case "coord":
                // Read the <gml:coord> start tag
                reader.ReadStartElement();

                // Now read up to 3 elements: X, and optionally Y or Z
                for (int index = 0; index < 3; index++)
                {
                    switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture))
                    {
                    case "x":
                        longitude = new Longitude(reader.ReadElementContentAsDouble());
                        break;

                    case "y":
                        latitude = new Latitude(reader.ReadElementContentAsDouble());
                        break;

                    case "z":
                        // Read Z as meters (there's no unit type in the spec :P morons)
                        _altitude = Distance.FromMeters(reader.ReadElementContentAsDouble());
                        break;
                    }

                    // If we're at an end element, stop
                    if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }

                // Make the position
                _position = new Position(latitude, longitude);

                // Read the </gml:coord> end tag
                reader.ReadEndElement();
                break;
            }

            reader.Read();
        }
Exemplo n.º 59
0
        /// <summary>
        /// Converts the given world coordinates and zoom level to the X and Y number of map tiles.
        /// </summary>
        /// <param name="Latitude">The latitude.</param>
        /// <param name="Longitude">The longitude.</param>
        /// <param name="ZoomLevel">The ZoomLevel.</param>
        /// <returns>The TileX and TileY number as a tuple.</returns>
        public static Tuple<UInt64, UInt64> WorldCoordinates_2_Screen(Latitude Latitude, Longitude Longitude, UInt32 ZoomLevel)
        {
            var MapSize = Math.Pow(2.0, ZoomLevel) * 256;

            return new Tuple<UInt64, UInt64>(
                (UInt64) (((Longitude.Value + 180.0) / 360.0) * MapSize),
                (UInt64) (((1.0 - Math.Log(
                                                              Math.Tan(Latitude.Value * Math.PI / 180.0) +
                                                        1.0 / Math.Cos(Latitude.Value * Math.PI / 180.0)
                                                    ) / Math.PI)
                                    / 2.0) * MapSize)
            );
        }
Exemplo n.º 60
0
        public void RawAngleConstructorTest2()
        {
            Angle angle = new Angle(0);

            Longitude longitude = new Longitude(angle);

            Assert.AreEqual(angle, longitude.Value);
            Assert.AreEqual(angle, longitude.RawValue);
        }