Exemple #1
0
        /// <summary>
        /// Converts the coordinates to Decimal Degrees.
        /// </summary>
        /// <returns>Coordintes in Decimal Degrees</returns>
        public override DecimalDegrees ToDecimalDegrees()
        {
            double _180_OVER_PI = 180d / Math.PI;
            GeodeticCoordinates geodeticCoordinates = new MGRS().convertToGeodetic(mgrsCoordinates);

            return(new DecimalDegrees(Math.Round(geodeticCoordinates.longitude * _180_OVER_PI, 5), Math.Round(geodeticCoordinates.latitude * _180_OVER_PI, 5)));
        }
Exemple #2
0
 static void Main(string[] args)
 {
     try {
         // See also example-GeoCoords.cpp
         {
             // Sample forward calculation
             double lat = 33.3, lon = 44.4; // Baghdad
             int    zone;
             bool   northp;
             double x, y;
             UTMUPS.Forward(lat, lon, out zone, out northp, out x, out y, -1, true);
             string mgrs;
             MGRS.Forward(zone, northp, x, y, lat, 5, out mgrs);
             Console.WriteLine(mgrs);
         }
         {
             // Sample reverse calculation
             string mgrs = "38SMB4488";
             int    zone, prec;
             bool   northp;
             double x, y;
             MGRS.Reverse(mgrs, out zone, out northp, out x, out y, out prec, true);
             double lat, lon;
             UTMUPS.Reverse(zone, northp, x, y, out lat, out lon, true);
             Console.WriteLine(String.Format("Latitude: {0} Longitude: {1}", lat, lon));
         }
     }
     catch (GeographicErr e) {
         Console.WriteLine(String.Format("Caught exception: {0}", e.Message));
     }
 }
Exemple #3
0
        public void TestForward(double lat, double lon, string expeted)
        {
            var(zone, northp, x, y) = UTMUPS.Forward(lat, lon);
            var mgrs = MGRS.Forward(zone, northp, x, y, 5);

            Assert.AreEqual(expeted, mgrs);
        }
Exemple #4
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            PointF text = new PointF(CMB_coordsystem.Right + 3, 3);

            //Enum.GetValues(typeof(CoordsSystems), CMB_coordsystem.Text);

            if (System == CoordsSystems.GEO.ToString())
            {
                e.Graphics.DrawString(Lat.ToString("0.000000") + " " + Lng.ToString("0.000000") + "   " + Alt.ToString("0.00"), this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
            }
            else if (System == CoordsSystems.UTM.ToString())
            {
                UTM utm = (UTM)point;
                //utm.East.ToString("0.00") + " " + utm.North.ToString("0.00")
                e.Graphics.DrawString(utm.ToString() + "   " + Alt.ToString("0.00"), this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
            }
            else if (System == CoordsSystems.MGRS.ToString())
            {
                MGRS mgrs = (MGRS)point;
                mgrs.Precision = 5;
                e.Graphics.DrawString(mgrs.ToString() + "   " + Alt.ToString("0.00"), this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
            }
        }
 private void OnConvertLatLon(object sender, EventArgs e)
 {
     try
     {
         int    zone;
         bool   northp;
         double x, y;
         string str;
         double lat = Double.Parse(m_latitudeTextBox.Text);
         double lon = Double.Parse(m_longitudeTextBox.Text);
         UTMUPS.Forward(lat, lon, out zone, out northp, out x, out y, (int)UTMUPS.ZoneSpec.STANDARD, true);
         m_utmPoleCheckBox.Checked = northp;
         m_utmXTextBox.Text        = x.ToString();
         m_utmYTextBox.Text        = y.ToString();
         m_utmZoneTextBox.Text     = zone.ToString();
         MGRS.Forward(zone, northp, x, y, 8, out str);
         m_mgrsTextBox.Text = str;
         OSGB.Forward(lat, lon, out x, out y);
         m_osgbXTextBox.Text = x.ToString();
         m_osgbYTextBox.Text = y.ToString();
         OSGB.GridReference(x, y, 8, out str);
         m_osgbTextBox.Text = str;
     }
     catch (Exception xcpt)
     {
         MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemple #6
0
        public string GetMGRS()
        {
            Geographic geo = new Geographic(Lng, Lat);

            MGRS mgrs = (MGRS)geo;

            return(mgrs.ToString());
        }
        /// <summary>
        /// Reset the location from a string. See <see cref="GeoCoords(string, bool, bool)"/>.
        /// </summary>
        /// <param name="s">1-element, 2-element, or 3-element string representation of the position.</param>
        /// <param name="centerp">governs the interpretation of <see cref="MGRS"/> coordinates.</param>
        /// <param name="longfirst">governs the interpretation of geographic coordinates.</param>
        public void Reset(string s, bool centerp = true, bool longfirst = false)
        {
            var sa = s.Split(" \t\n\v\f\r,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (sa.Length == 1)
            {
                int prec;
                (_zone, _northp, _easting, _northing, prec) = MGRS.Reverse(sa[0].AsSpan(), centerp);
                (_lat, _long) = UTMUPS.Reverse(_zone, _northp, _easting, _northing, out _gamma, out _k);
            }
            else if (sa.Length == 2)
            {
                (_lat, _long) = DMS.Decode(sa[0], sa[1], longfirst);
                _long         = AngNormalize(_long);
                (_zone, _northp, _easting, _northing) = UTMUPS.Forward(_lat, _long, out _gamma, out _k);
            }
            else if (sa.Length == 3)
            {
                int zoneind, coordind;
                if (sa[0].Length > 0 && char.IsLetter(sa[0][sa[0].Length - 1]))
                {
                    zoneind  = 0;
                    coordind = 1;
                }
                else if (sa[2].Length > 0 && char.IsLetter(sa[2][sa[2].Length - 1]))
                {
                    zoneind  = 2;
                    coordind = 0;
                }
                else
                {
                    throw new GeographicException("Neither " + sa[0] + " nor " + sa[2]
                                                  + " of the form UTM/UPS Zone + Hemisphere"
                                                  + " (ex: 38n, 09s, n)");
                }

                (_zone, _northp) = UTMUPS.DecodeZone(sa[zoneind].AsSpan());
                for (int i = 0; i < 2; ++i)
                {
                    if (i != 0)
                    {
                        _northing = sa[coordind + i].ParseDouble();
                    }
                    else
                    {
                        _easting = sa[coordind + i].ParseDouble();
                    }
                }

                (_lat, _long) = UTMUPS.Reverse(_zone, _northp, _easting, _northing, out _gamma, out _k);
                FixHemisphere();
            }
            else
            {
                throw new GeographicException("Coordinate requires 1, 2, or 3 elements");
            }
            CopyToAlt();
        }
Exemple #8
0
    private void DrawCoordinate(Graphics graphics, IPoint p, string[] coordinateModes, Pen pen, System.Drawing.Font font,
                                SolidBrush textBrush, SolidBrush shadowBrush, StringFormat format)
    {
        DrawCross(graphics, p, pen, 10);

        double x = p.Coordinate.X;
        double y = p.Coordinate.Y;

        if (AppSettings.MapUnits == "feet")
        {
            x *= Constants.MetersPerFoot;
            y *= Constants.MetersPerFoot;
        }

        double lon;
        double lat;

        CoordinateSystem.ToGeodetic(x, y, out lon, out lat);

        double xOffset = 2;

        foreach (string mode in coordinateModes)
        {
            string yText;
            string xText;

            switch (mode)
            {
            case "dms":
                yText = (lat < 0 ? "S " : "N ") + ToDms(lat);
                xText = (lon < 0 ? "W " : "E ") + ToDms(lon);
                break;

            case "dd":
                yText = (lat < 0 ? "S " : "N ") + Math.Abs(lat).ToString("0.000000") + "°";
                xText = (lon < 0 ? "W " : "E ") + Math.Abs(lon).ToString("0.000000") + "°";
                break;

            case "usng":
                yText = "";
                MGRS mgrs = new MGRS();
                mgrs.ToGrid(lon, lat, out xText);
                break;

            default:
                string unit = AppSettings.MapUnits == "feet" ? " ft" : " m";
                yText = "N " + p.Coordinate.Y.ToString("#,##0") + unit;
                xText = "E " + p.Coordinate.X.ToString("#,##0") + unit;
                break;
            }


            DrawText(graphics, p, String.Format("{0}\n{1}", yText, xText), font, textBrush, shadowBrush, xOffset, -3, format);

            SizeF size = graphics.MeasureString((xText.Length > yText.Length ? xText : yText) + "..", font);
            xOffset += size.Width / _resolution;
        }
    }
Exemple #9
0
    private void DrawCoordinate(Graphics graphics, IPoint p, string[] coordinateModes, Pen pen, System.Drawing.Font font,
                                SolidBrush textBrush, SolidBrush shadowBrush, StringFormat format)
    {
        DrawCross(graphics, p, pen, 10);

        Coordinate g       = _appSettings.MapCoordinateSystem.ToGeodetic(p.Coordinate);
        double     xOffset = 2;

        foreach (string mode in coordinateModes)
        {
            string yText;
            string xText;

            switch (mode)
            {
            case "dms":
                yText = (g.Y < 0 ? "S " : "N ") + ToDms(g.Y);
                xText = (g.X < 0 ? "W " : "E ") + ToDms(g.X);
                break;

            case "dd":
                yText = (g.Y < 0 ? "S " : "N ") + Math.Abs(g.Y).ToString("0.000000") + "°";
                xText = (g.X < 0 ? "W " : "E ") + Math.Abs(g.X).ToString("0.000000") + "°";
                break;

            case "usng":
                yText = "";
                MGRS mgrs = new MGRS();
                xText = mgrs.ToGrid(g);
                break;

            default:
                Coordinate c = p.Coordinate;

                if (!_appSettings.MapCoordinateSystem.Equals(_appSettings.MeasureCoordinateSystem))
                {
                    c = _appSettings.MeasureCoordinateSystem.ToProjected(g);

                    if (!Double.IsNaN(_appSettings.MarkupShiftX) && !Double.IsNaN(_appSettings.MarkupShiftY))
                    {
                        c = c.Translate(-_appSettings.MarkupShiftX, -_appSettings.MarkupShiftY);
                    }
                }

                string unit = _appSettings.MeasureCoordinateSystem.MapUnits == "feet" ? " ft" : " m";
                yText = "N " + c.Y.ToString("#,##0") + unit;
                xText = "E " + c.X.ToString("#,##0") + unit;
                break;
            }

            DrawText(graphics, p, String.Format("{0}\n{1}", yText, xText), font, textBrush, shadowBrush, xOffset, -3, format);

            SizeF size = graphics.MeasureString((xText.Length > yText.Length ? xText : yText) + "..", font);
            xOffset += size.Width / _resolution;
        }
    }
Exemple #10
0
        /// <summary>
        /// Notify property changed
        /// </summary>
        /// <param name="propName">Property Name</param>
        public void NotifyPropertyChanged(string propName)
        {
            switch (propName)
            {
            case "CelestialInfo":
                if (!EagerLoadSettings.Celestial || celestialInfo == null)
                {
                    return;
                }                                                                          //Prevent Null Exceptions and calls while eagerloading is off
                celestialInfo.CalculateCelestialTime(latitude.DecimalDegree, longitude.DecimalDegree, geoDate);
                break;

            case "UTM":
                if (!EagerLoadSettings.UTM_MGRS || UTM == null)
                {
                    return;
                }
                utm.ToUTM(latitude.ToDouble(), longitude.ToDouble(), utm);
                break;

            case "utm":
                //Adjust case and notify of change.
                //Use to notify without calling ToUTM()
                propName = "UTM";
                break;

            case "MGRS":
                if (!EagerLoadSettings.UTM_MGRS || MGRS == null)
                {
                    return;
                }
                MGRS.ToMGRS(utm);
                break;

            case "Cartesian":
                if (!EagerLoadSettings.Cartesian || Cartesian == null)
                {
                    return;
                }
                Cartesian.ToCartesian(this);
                break;

            case "ECEF":
                if (!EagerLoadSettings.ECEF)
                {
                    return;
                }
                ECEF.ToECEF(this);
                break;

            default:
                break;
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        private void OnValidate(object sender, EventArgs e)
        {
            try
            {
                string str;
                int    prec, zone, zout;
                bool   northp;
                double x, y, x1, y1, gamma, k, lat, lon;
                OSGB.Forward(52.0, -2.0, out x, out y, out gamma, out k);
                OSGB.Forward(52.0, -2.0, out x1, out y1);
                if (x != x1 || y != y1)
                {
                    throw new Exception("Error in OSGB.Forward");
                }
                OSGB.Reverse(x, y, out lat, out lon, out gamma, out k);
                OSGB.Reverse(x, y, out x1, out y1);
                if (lat != x1 || lon != y1)
                {
                    throw new Exception("Error in OSGB.Reverse");
                }
                OSGB.GridReference(x, y, 8, out str);
                OSGB.GridReference(str, out x1, out y1, out prec, true);
                UTMUPS.StandardZone(32.0, -80.0, (int)UTMUPS.ZoneSpec.STANDARD);
                UTMUPS.UTMShift();
                UTMUPS.StandardZone(32.0, -86.0, (int)UTMUPS.ZoneSpec.STANDARD);
                UTMUPS.Forward(32.0, -86.0, out zone, out northp, out x, out y, out gamma, out k, (int)UTMUPS.ZoneSpec.STANDARD, true);
                UTMUPS.Forward(32.0, -86.0, out zone, out northp, out x1, out y1, (int)UTMUPS.ZoneSpec.STANDARD, true);
                if (x != x1 || y != y1)
                {
                    throw new Exception("Error in UTMUPS.Forward");
                }
                UTMUPS.Reverse(zone, northp, x, y, out lat, out lon, out gamma, out k, true);
                UTMUPS.Reverse(zone, northp, x, y, out x1, out y1, true);
                if (lat != x1 || lon != y1)
                {
                    throw new Exception("Error in UTMUPS.Reverse");
                }
                UTMUPS.Transfer(zone, northp, x, y, zone + 1, true, out x1, out y1, out zout);
                str  = UTMUPS.EncodeZone(zone, northp, true);
                prec = UTMUPS.EncodeEPSG(zone, northp);
                UTMUPS.DecodeZone(str, out zone, out northp);
                UTMUPS.DecodeEPSG(prec, out zone, out northp);
                MGRS.Forward(zone, northp, x, y, 8, out str);
                MGRS.Forward(zone, northp, x, y, 32.0, 8, out str);
                MGRS.Reverse(str, out zone, out northp, out x, out y, out prec, true);

                MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception xcpt)
            {
                MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #12
0
        public void TestReverse(double lat, double lon, string input)
        {
            var(zone, northp, x, y, _) = MGRS.Reverse(input);
            var(olat, olon)            = UTMUPS.Reverse(zone, northp, x, y);

            Assert.AreEqual(olat, lat, 1e-5);

            // No need to check longitude when near pole.
            if (Math.Abs(lat) != 90)
            {
                Assert.AreEqual(olon, lon, 1e-5);
            }
        }
        private void OnConvertMGRS(object sender, EventArgs e)
        {
            int    zone, prec;
            bool   northp;
            double x, y, lat, lon;

            MGRS.Reverse(m_mgrsTextBox.Text, out zone, out northp, out x, out y, out prec, true);
            m_utmPoleCheckBox.Checked = northp;
            m_utmXTextBox.Text        = x.ToString();
            m_utmYTextBox.Text        = y.ToString();
            m_utmZoneTextBox.Text     = zone.ToString();
            UTMUPS.Reverse(zone, northp, x, y, out lat, out lon, true);
            m_latitudeTextBox.Text  = lat.ToString();
            m_longitudeTextBox.Text = lon.ToString();
        }
 private void OnConvertUTMUPS(object sender, EventArgs e)
 {
     try
     {
         double lat, lon;
         string str;
         double x    = Double.Parse(m_utmXTextBox.Text);
         double y    = Double.Parse(m_utmYTextBox.Text);
         int    zone = Int32.Parse(m_utmZoneTextBox.Text);
         UTMUPS.Reverse(zone, m_utmPoleCheckBox.Checked, x, y, out lat, out lon, true);
         m_latitudeTextBox.Text  = lat.ToString();
         m_longitudeTextBox.Text = lon.ToString();
         MGRS.Forward(zone, m_utmPoleCheckBox.Checked, x, y, 8, out str);
         m_mgrsTextBox.Text = str;
     }
     catch (Exception xcpt)
     {
         MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemple #15
0
 /// <summary>
 /// Gets the standard zone.
 /// </summary>
 /// <param name="lat">latitude (degrees).</param>
 /// <param name="lon">longitude (degrees).</param>
 /// <param name="setzone">
 /// zone override (optional). If omitted, use the standard rules for picking the zone.
 /// If setzone is given then use that zone if it is non-negative, otherwise apply the rules given in <see cref="ZoneSpec"/>.
 /// </param>
 /// <returns></returns>
 /// <remarks>
 /// This is exact.
 /// </remarks>
 public static int StandardZone(double lat, double lon, int setzone = (int)ZoneSpec.Standard)
 {
     if (!(setzone >= (int)ZoneSpec.MinPseudoZone && setzone <= (int)ZoneSpec.MaxZone))
     {
         throw new GeographicException($"Illegal zone requested {setzone}");
     }
     if (setzone >= (int)ZoneSpec.MinZone || setzone == (int)ZoneSpec.Invalid)
     {
         return(setzone);
     }
     if (double.IsNaN(lat) || double.IsNaN(lon)) // Check if lat or lon is a NaN
     {
         return((int)ZoneSpec.Invalid);
     }
     if (setzone == (int)ZoneSpec.UTM || (lat >= -80 && lat < 84))
     {
         int ilon = (int)Floor(AngNormalize(lon));
         if (ilon == 180)
         {
             ilon = -180;              // ilon now in [-180,180)
         }
         int zone = (ilon + 186) / 6;
         int band = MGRS.LatitudeBand(lat);
         if (band == 7 && zone == 31 && ilon >= 3) // The Norway exception
         {
             zone = 32;
         }
         else if (band == 9 && ilon >= 0 && ilon < 42) // The Svalbard exception
         {
             zone = 2 * ((ilon + 183) / 12) + 1;
         }
         return(zone);
     }
     else
     {
         return((int)ZoneSpec.UPS);
     }
 }
Exemple #16
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            PointF text = new PointF(CMB_coordsystem.Right + 3, 3);

            if (System == CoordsSystems.GEO.ToString())
            {
                if (Vertical)
                {
                    e.Graphics.DrawString(Lat.ToString("0.000000") + "\n" + Lng.ToString("0.000000") + "\n" + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
                    e.Graphics.DrawString(AltSource, this.Font, new SolidBrush(this.ForeColor),
                                          new PointF(CMB_coordsystem.Left, CMB_coordsystem.Bottom + 4), StringFormat.GenericDefault);
                }
                else
                {
                    e.Graphics.DrawString(Lat.ToString("0.000000") + " " + Lng.ToString("0.000000") + "   " + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
                }
            }
            else if (System == CoordsSystems.UTM.ToString())
            {
                try
                {
                    if (point.Latitude > 84 || point.Latitude < -80 || point.Longitude >= 180 || point.Longitude <= -180)
                    {
                        return;
                    }

                    UTM utm = (UTM)point;
                    //utm.East.ToString("0.00") + " " + utm.North.ToString("0.00")
                    string[] parts = utm.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (Vertical)
                    {
                        e.Graphics.DrawString(parts[0] + "\n" + parts[1] + "\n" + parts[2] + "\n" + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
                        e.Graphics.DrawString(AltSource, this.Font, new SolidBrush(this.ForeColor),
                                              new PointF(CMB_coordsystem.Left, CMB_coordsystem.Bottom + 4), StringFormat.GenericDefault);
                    }
                    else
                    {
                        e.Graphics.DrawString(utm.ToString() + "   " + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
                    }
                }
                catch { }
            }
            else if (System == CoordsSystems.MGRS.ToString())
            {
                try
                {
                    if (point.Latitude > 84 || point.Latitude < -80 || point.Longitude >= 180 || point.Longitude <= -180)
                    {
                        return;
                    }

                    MGRS mgrs = (MGRS)point;
                    mgrs.Precision = 5;

                    if (Vertical)
                    {
                        e.Graphics.DrawString(mgrs.ToString() + "\n" + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), new Point(5, CMB_coordsystem.Bottom + 2), StringFormat.GenericDefault);
                        e.Graphics.DrawString(AltSource, this.Font, new SolidBrush(this.ForeColor),
                                              new PointF(CMB_coordsystem.Right + 4, CMB_coordsystem.Top), StringFormat.GenericDefault);
                    }
                    else
                    {
                        e.Graphics.DrawString(mgrs.ToString() + "   " + Alt.ToString("0.00") + AltUnit, this.Font, new SolidBrush(this.ForeColor), text, StringFormat.GenericDefault);
                    }
                }
                catch { }
            }
        }
Exemple #17
0
        /// <summary>
        /// Converts to Military Grid Reference System
        /// </summary>
        /// <returns>Military Grid Reference System</returns>
        public override MilitaryGridReferenceSystem ToMilitaryGridReferenceSystem()
        {
            MGRSorUSNGCoordinates mgrs = new MGRS().convertFromGeodetic(this.geodeticCoordinates, 5);

            return(new MilitaryGridReferenceSystem(mgrs));
        }
Exemple #18
0
        /// <summary>
        /// Notify property changed
        /// </summary>
        /// <param name="propName">Property Name</param>
        public void NotifyPropertyChanged(string propName)
        {
            switch (propName)
            {
            case "CelestialInfo":
                if (!EagerLoadSettings.Celestial)
                {
                    return;
                }                                                 //Prevent calls while eagerloading is off
                if (EagerLoadSettings.Celestial && celestialInfo == null)
                {
                    celestialInfo = new Celestial(false);
                }                                                                                                      //Create object if EagerLoading is on and object is null (EagerLoading turned on later).
                celestialInfo.CalculateCelestialTime(latitude.DecimalDegree, longitude.DecimalDegree, geoDate, EagerLoadSettings);
                break;

            case "UTM":
                if (!EagerLoadSettings.UTM_MGRS)
                {
                    return;
                }
                else if (EagerLoadSettings.UTM_MGRS && utm == null)
                {
                    utm = new UniversalTransverseMercator(latitude.ToDouble(), longitude.ToDouble(), this, equatorial_radius, inverse_flattening);
                }
                else
                {
                    utm.ToUTM(latitude.ToDouble(), longitude.ToDouble(), utm);
                }
                break;

            case "utm":
                //Adjust case and notify of change.
                //Use to notify without calling ToUTM()
                propName = "UTM";
                break;

            case "MGRS":
                if (!EagerLoadSettings.UTM_MGRS || !EagerLoadSettings.Extensions.MGRS || utm == null)
                {
                    return;
                }
                else if (EagerLoadSettings.UTM_MGRS && EagerLoadSettings.Extensions.MGRS && mgrs == null)
                {
                    mgrs = new MilitaryGridReferenceSystem(utm);
                }
                else
                {
                    MGRS.ToMGRS(utm);
                }
                break;

            case "Cartesian":
                if (!EagerLoadSettings.Cartesian)
                {
                    return;
                }
                else if (EagerLoadSettings.Cartesian && cartesian == null)
                {
                    cartesian = new Cartesian(this);
                }
                else
                {
                    Cartesian.ToCartesian(this);
                }
                break;

            case "ECEF":
                if (!EagerLoadSettings.ECEF)
                {
                    return;
                }
                else if (EagerLoadSettings.ECEF && ecef == null)
                {
                    ecef = new ECEF(this);
                }
                else
                {
                    ECEF.ToECEF(this);
                }
                break;

            default:
                break;
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
Exemple #19
0
 public void UTMUPSSantityCheck()
 {
     MGRS.Check();
 }
Exemple #20
0
        public void Execute(params object[] list)
        {
            string addr = (string)list [0];

            if (addr.Substring(0, 5) == "COORD")
            {
                addr = addr.Substring(addr.IndexOf(":") + 1);
                FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** Converting Gauss-Krüger to Latitude/Longitude: " + addr);
                GaussKrueger gauss = new GaussKrueger(int.Parse(addr.Substring(0, addr.IndexOf(" ")).Trim()), int.Parse(addr.Substring(addr.IndexOf(" ") + 1).Trim()));
                MGRS         mgrs  = (MGRS)gauss;
                Geographic   geo   = (Geographic)mgrs;
                double       lon   = geo.Longitude;
                double       lat   = geo.Latitude;

                string key            = "AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T";
                Uri    geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", addr, key));
                System.Collections.Generic.Dictionary <string, string> Result;
                Result = new System.Collections.Generic.Dictionary <string, string> ();
                System.Net.WebClient WCC = new WebClient();
                Result.Add("lat", (System.Math.Round(lat, 5)).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                Result.Add("lng", (System.Math.Round(lon, 5)).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                try {
                    System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => {
                        return(true);
                    };
                    System.Net.WebClient WC = new System.Net.WebClient();
                    FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** downloading map...");
                    WC.DownloadFile("http://dev.virtualearth.net/REST/V1/Imagery/Map/AerialWithLabels/" + (lat).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "/16?pp=" + (lat).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + ";10;&mapSize=600,700&mapLayer=TrafficFlow&key=AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T", "/tmp/map.jpg");
                    //WC.DownloadFile("https://maps.googleapis.com/maps/api/staticmap?center="+(lat).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+","+(lon ).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+"&zoom=13&scale=2&size=400x900&maptype=roadmap&format=png&visual_refresh=true&markers=size:big%7Ccolor:red%7Clabel:Einsatzort%7C"+(lat ).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+","+(lon ).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat),"/tmp/map.png");
                    string XFile = System.IO.File.ReadAllText("web/" + ((string)list [1]).Replace(" ", "_") + ".xml");
                    XFile = XFile.Replace("<Property name=\"Tag\">MAP</Property>", "<Property name=\"Tag\">MAP</Property>\r\n      <Property name=\"Image\">\r\n        <Binary>" + System.Convert.ToBase64String(System.IO.File.ReadAllBytes("/tmp/map.jpg")) + "</Binary>\r\n</Property>");
                    FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** put map to panel-xml...");
                    System.IO.File.WriteAllText("web/panel.xml", XFile);
                    System.IO.File.WriteAllText("web/" + ((string)list [1]).Replace(" ", "_") + ".xml", XFile);
                } catch (Exception exx) {
                    FeuerwehrCloud.Helper.Logger.WriteLine(exx.ToString());
                }
                RaiseFinish("text", Result);
            }
            else
            {
                FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** Trying to get coordinates from: " + addr);
                try {
                    System.Collections.Generic.Dictionary <string, string> Result;
                                        #if GOOGLE
                    Geocoding.Address[] addresses = GeC.Geocode((string)list[0]).ToArray();
                    Result = new System.Collections.Generic.Dictionary <string, string> ();
                    Result.Add("lat", (addresses [0].Coordinates.Latitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                    Result.Add("lng", (addresses [0].Coordinates.Longitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                    try {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return(true); };
                        System.Net.WebClient WC = new System.Net.WebClient();
                        WC.DownloadFile("https://maps.googleapis.com/maps/api/staticmap?center=" + (addresses [0].Coordinates.Latitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (addresses [0].Coordinates.Longitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "&zoom=13&scale=2&size=400x900&maptype=roadmap&format=png&visual_refresh=true&markers=size:big%7Ccolor:red%7Clabel:Einsatzort%7C" + (addresses [0].Coordinates.Latitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (addresses [0].Coordinates.Longitude).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat), "/tmp/map.png");
                        string XFile = System.IO.File.ReadAllText("/FeuerwehrCloud/DEIVA/panel.xml");
                        XFile = XFile.Replace("<Property name=\"Tag\">MAP</Property>", "<Property name=\"Tag\">MAP</Property>\r\n      <Property name=\"Image\">\r\n        <Binary>" + System.Convert.ToBase64String(System.IO.File.ReadAllBytes("/tmp/map.png")) + "</Binary>\r\n</Property>");
                        System.IO.File.WriteAllText("/FeuerwehrCloud/DEIVA/panel.xml", XFile);
                    } catch (Exception ex) {
                        FeuerwehrCloud.Helper.Logger.WriteLine(ex.ToString());
                    }
                    RaiseFinish("text", Result);
                                        #else
                    // StaticMap with Routes!
                    //http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes?mapSize=800,800&wp.0=Sonnenstr.3,Rosenheim;64;1&wp.1=Hoffeldstr.10,Rosenheim;66;2&key=AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T

                    string key            = "AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T";
                    Uri    geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", addr, key));
                    Result = new System.Collections.Generic.Dictionary <string, string> ();
                    System.Net.WebClient WCC = new WebClient();
                    try {
                        string str = WCC.DownloadString(geocodeRequest);
                        if (str.IndexOf("\"Point\",\"coordinates\":") > -1)
                        {
                            FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** Address found!");
                            dynamic jsonDe = JsonConvert.DeserializeObject(str);
                            float   lat    = jsonDe.resourceSets [0].resources [0].point.coordinates [0];
                            float   lon    = jsonDe.resourceSets [0].resources [0].point.coordinates [1];
                            Result.Add("lat", (System.Math.Round(lat, 5)).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                            Result.Add("lng", (System.Math.Round(lon, 5)).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
                            try {
                                System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => {
                                    return(true);
                                };
                                System.Net.WebClient WC = new System.Net.WebClient();
                                FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** downloading map...");
                                //WC.DownloadFile ("http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/" + (lat).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "/14?pp=" + (lat).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + ";47;!&mapSize=400,700&mapLayer=TrafficFlow&key=AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T", "/tmp/map.jpg");
                                WC.DownloadFile("http://dev.virtualearth.net/REST/V1/Imagery/Map/AerialWithLabels/" + (lat).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "/16?pp=" + (lat).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "," + (lon).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + ";10;&mapSize=500,700&mapLayer=TrafficFlow&key=AsSta3yGavJt7O8i-SokTyANtvF1HfBoPK5GdD_xgl4ul6ZBmBB3Ru7gX7pof0_T", "/tmp/map.jpg");
                                //WC.DownloadFile("https://maps.googleapis.com/maps/api/staticmap?center="+(lat).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+","+(lon ).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+"&zoom=13&scale=2&size=400x900&maptype=roadmap&format=png&visual_refresh=true&markers=size:big%7Ccolor:red%7Clabel:Einsatzort%7C"+(lat ).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat)+","+(lon ).ToString (System.Globalization.CultureInfo.InvariantCulture.NumberFormat),"/tmp/map.png");
                                string XFile = System.IO.File.ReadAllText("web/panel.xml");
                                XFile = XFile.Replace("<Property name=\"Tag\">MAP</Property>", "<Property name=\"Tag\">MAP</Property>\r\n      <Property name=\"Image\">\r\n        <Binary>" + System.Convert.ToBase64String(System.IO.File.ReadAllBytes("/tmp/map.jpg")) + "</Binary>\r\n</Property>");
                                FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** put map to panel-xml...");
                                System.IO.File.WriteAllText("web/panel.xml", XFile);
                            } catch (Exception exx) {
                                FeuerwehrCloud.Helper.Logger.WriteLine(exx.ToString());
                            }
                            FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** done...!");
                            RaiseFinish("text", Result);
                        }
                        else
                        {
                            FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** Address not found ... :/");
                            FeuerwehrCloud.Helper.Logger.WriteLine(str);
                            // Keine Koordinaten gefunden... :/
                        }
                    } catch (Exception ex) {
                        if (ex.GetType().ToString() == "System.Net.WebException")
                        {
                            if (ex.Message == "NameResolutionFailure")
                            {
                                // PANIC! We don't have internet!!!!
                            }
                        }
                        FeuerwehrCloud.Helper.Logger.WriteLine("|  + [GeoCoder] *** Exception... :/");
                        FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                    }
                                        #endif
                } catch (Exception ex) {
                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                }
            }
        }
Exemple #21
0
        public static DD MGRS2DD(MGRS mgrs)
        {
            var Convert = new ConversionMGRS2DD();

            return(Convert.Convert(mgrs));
        }
 public static DD MGRS2DD(MGRS mgrs)
 {
     var Convert = new ConversionMGRS2DD();
     return Convert.Convert(mgrs);
 }
Exemple #23
0
 /// <summary>
 /// Gets <see cref="MGRS"/> string for the alternate zone. See <see cref="ToMGRSString(int)"/>.
 /// </summary>
 /// <param name="prec">precision (relative to about 1m).</param>
 /// <returns>A <see cref="MGRS"/> string.</returns>
 public string ToAltMGRSString(int prec = 0)
 => MGRS.Forward(_alt_zone, _northp, _alt_easting, _alt_northing, _lat, Max(-1, Min(6, prec) + 5));
        /// <summary><para>Die Funktion wandelt militärische MGRS-Koordinaten (Military Grid Reference System, UTMREF) in UTM-Koordinaten um.
        /// <para>Die Funktion ist nur für interne Berechnungen bestimmt.</para></para></summary>
        /// <remarks><para>
        /// Hintergründe zum Problem der Koordinatentransformationen sowie entsprechende  mathematische 
        /// Formeln können den einschlägigen Fachbüchern oder dem Internet entnommen werden.<p />
        /// Quellen: 
        /// Bundesamt für Kartographie und Geodäsie<br />
        /// <a href="http://www.bkg.bund.de" target="_blank">http://www.bkg.bund.de</a><br />
        /// <a href="http://crs.bkg.bund.de" target="_blank">http://crs.bkg.bund.de</a><br />
        /// </para></remarks>
        /// 
        /// <param name="mgrs">Ein <see cref="MGRS"/>-Objekt.</param>
        /// <returns>Ein <see cref="UTM"/>-Objekt.</returns>
        internal UTM MGRUTM(MGRS mgrs) 
        {
            int zone = mgrs.Zone;
            string eastgrid = mgrs.Grid.Substring(0, 1);
            string northgrid = mgrs.Grid.Substring(1, 1);

            // Führende Stelle East-Koordinate aus Planquadrat(east) und Koordinaten berechnen
            int i = mgrs.Zone % 3;
            int stellenwert = 0;
            if (i == 0) stellenwert = MGRS_EAST0.IndexOf(eastgrid) + 1;
            if (i == 1) stellenwert = MGRS_EAST1.IndexOf(eastgrid) + 1;
            if (i == 2) stellenwert = MGRS_EAST2.IndexOf(eastgrid) + 1;
            string sEast = stellenwert.ToString() + mgrs.EastString.PadRight(5, '0');

            // Führende Stelle North-Koordinate aus Planquadrat(north) 
            i = mgrs.Zone % 2;
            stellenwert = 0;
            if (i == 0)
            {
                stellenwert = MGRS_NORTH0.IndexOf(northgrid);
            }
            else
            {
                stellenwert = MGRS_NORTH1.IndexOf(northgrid);
            }

            // Führende Stelle North-Koordinate berechnen 
            char band = mgrs.Band.ToCharArray()[0];

            if (zone < MIN_ZONE || zone > MAX_ZONE || band < MIN_BAND || band > MAX_BAND)
            {
                throw new ErrorProvider.GeoException(new ErrorProvider.ErrorMessage("ERROR_UTM_ZONE"));
            }

            if (band >= 'N')
            {
                if ((band == 'Q') && (stellenwert < 10)) stellenwert += 20;
                if (band >= 'R') stellenwert += 20;
                if ((band == 'S') && (stellenwert < 30)) stellenwert += 20;
                if (band >= 'T') stellenwert += 20;
                if ((band == 'U') && (stellenwert < 50)) stellenwert += 20;
                if (band >= 'V') stellenwert += 20;
                if ((band == 'W') && (stellenwert < 70)) stellenwert += 20;
                if (band >= 'X') stellenwert += 20;
            }
            else
            {
                if ((band == 'C') && (stellenwert < 10)) stellenwert += 20;
                if (band >= 'D') stellenwert += 20;
                if ((band == 'F') && (stellenwert < 30)) stellenwert += 20;
                if (band >= 'G') stellenwert += 20;
                if ((band == 'H') && (stellenwert < 50)) stellenwert += 20;
                if (band >= 'J') stellenwert += 20;
                if ((band == 'K') && (stellenwert < 70)) stellenwert += 20;
                if (band >= 'L') stellenwert += 20;
            }

            // North-Koordinate 
            string sNorth = "";
            if ((stellenwert.ToString()).Length == 1) sNorth = "0";
            sNorth += stellenwert.ToString() + mgrs.NorthString.PadRight(5, '0');

            return new UTM(zone, band.ToString(), double.Parse(sEast), double.Parse(sNorth));
        }
Exemple #25
0
        /// <summary><para>Die Funktion wandelt militärische MGRS-Koordinaten (Military Grid Reference System, UTMREF) in UTM-Koordinaten um.
        /// <para>Die Funktion ist nur für interne Berechnungen bestimmt.</para></para></summary>
        /// <remarks><para>
        /// Hintergründe zum Problem der Koordinatentransformationen sowie entsprechende  mathematische
        /// Formeln können den einschlägigen Fachbüchern oder dem Internet entnommen werden.<p />
        /// Quellen:
        /// Bundesamt für Kartographie und Geodäsie<br />
        /// <a href="http://www.bkg.bund.de" target="_blank">http://www.bkg.bund.de</a><br />
        /// <a href="http://crs.bkg.bund.de" target="_blank">http://crs.bkg.bund.de</a><br />
        /// </para></remarks>
        ///
        /// <param name="mgrs">Ein <see cref="MGRS"/>-Objekt.</param>
        /// <returns>Ein <see cref="UTM"/>-Objekt.</returns>
        internal UTM MGRUTM(MGRS mgrs)
        {
            int    zone      = mgrs.Zone;
            string eastgrid  = mgrs.Grid.Substring(0, 1);
            string northgrid = mgrs.Grid.Substring(1, 1);

            // Führende Stelle East-Koordinate aus Planquadrat(east) und Koordinaten berechnen
            int i           = mgrs.Zone % 3;
            int stellenwert = 0;

            if (i == 0)
            {
                stellenwert = MGRS_EAST0.IndexOf(eastgrid) + 1;
            }
            if (i == 1)
            {
                stellenwert = MGRS_EAST1.IndexOf(eastgrid) + 1;
            }
            if (i == 2)
            {
                stellenwert = MGRS_EAST2.IndexOf(eastgrid) + 1;
            }
            string sEast = stellenwert.ToString() + mgrs.EastString.PadRight(5, '0');

            // Führende Stelle North-Koordinate aus Planquadrat(north)
            i           = mgrs.Zone % 2;
            stellenwert = 0;
            if (i == 0)
            {
                stellenwert = MGRS_NORTH0.IndexOf(northgrid);
            }
            else
            {
                stellenwert = MGRS_NORTH1.IndexOf(northgrid);
            }

            // Führende Stelle North-Koordinate berechnen
            char band = mgrs.Band.ToCharArray()[0];

            if (zone < MIN_ZONE || zone > MAX_ZONE || band < MIN_BAND || band > MAX_BAND)
            {
                throw new ErrorProvider.GeoException(new ErrorProvider.ErrorMessage("ERROR_UTM_ZONE"));
            }

            if (band >= 'N')
            {
                if ((band == 'Q') && (stellenwert < 10))
                {
                    stellenwert += 20;
                }
                if (band >= 'R')
                {
                    stellenwert += 20;
                }
                if ((band == 'S') && (stellenwert < 30))
                {
                    stellenwert += 20;
                }
                if (band >= 'T')
                {
                    stellenwert += 20;
                }
                if ((band == 'U') && (stellenwert < 50))
                {
                    stellenwert += 20;
                }
                if (band >= 'V')
                {
                    stellenwert += 20;
                }
                if ((band == 'W') && (stellenwert < 70))
                {
                    stellenwert += 20;
                }
                if (band >= 'X')
                {
                    stellenwert += 20;
                }
            }
            else
            {
                if ((band == 'C') && (stellenwert < 10))
                {
                    stellenwert += 20;
                }
                if (band >= 'D')
                {
                    stellenwert += 20;
                }
                if ((band == 'F') && (stellenwert < 30))
                {
                    stellenwert += 20;
                }
                if (band >= 'G')
                {
                    stellenwert += 20;
                }
                if ((band == 'H') && (stellenwert < 50))
                {
                    stellenwert += 20;
                }
                if (band >= 'J')
                {
                    stellenwert += 20;
                }
                if ((band == 'K') && (stellenwert < 70))
                {
                    stellenwert += 20;
                }
                if (band >= 'L')
                {
                    stellenwert += 20;
                }
            }

            // North-Koordinate
            string sNorth = "";

            if ((stellenwert.ToString()).Length == 1)
            {
                sNorth = "0";
            }
            sNorth += stellenwert.ToString() + mgrs.NorthString.PadRight(5, '0');

            return(new UTM(zone, band.ToString(), double.Parse(sEast), double.Parse(sNorth)));
        }
Exemple #26
0
  private void DrawCoordinate(Graphics graphics, IPoint p, string[] coordinateModes, Pen pen, System.Drawing.Font font, 
      SolidBrush textBrush, SolidBrush shadowBrush, StringFormat format)
  {
    DrawCross(graphics, p, pen, 10);

    double x = p.Coordinate.X;
    double y = p.Coordinate.Y;

    if (AppSettings.MapUnits == "feet")
    {
      x *= Constants.MetersPerFoot;
      y *= Constants.MetersPerFoot;
    }

    double lon;
    double lat;
    CoordinateSystem.ToGeodetic(x, y, out lon, out lat);

    double xOffset = 2;

    foreach (string mode in coordinateModes)
    {
      string yText;
      string xText;

      switch (mode)
      {
        case "dms":
          yText = (lat < 0 ? "S " : "N ") + ToDms(lat);
          xText = (lon < 0 ? "W " : "E ") + ToDms(lon);
          break;

        case "dd":
          yText = (lat < 0 ? "S " : "N ") + Math.Abs(lat).ToString("0.000000") + "°";
          xText = (lon < 0 ? "W " : "E ") + Math.Abs(lon).ToString("0.000000") + "°";
          break;

        case "usng":
          yText = "";
          MGRS mgrs = new MGRS();
          mgrs.ToGrid(lon, lat, out xText);
          break;

        default:
          string unit = AppSettings.MapUnits == "feet" ? " ft" : " m";
          yText = "N " + p.Coordinate.Y.ToString("#,##0") + unit;
          xText = "E " + p.Coordinate.X.ToString("#,##0") + unit;
          break;
      }


      DrawText(graphics, p, String.Format("{0}\n{1}", yText, xText), font, textBrush, shadowBrush, xOffset, -3, format);

      SizeF size = graphics.MeasureString((xText.Length > yText.Length ? xText : yText) + "..", font);
      xOffset += size.Width / _resolution;
    }
  }