예제 #1
0
        public ActionResult NewPoste(PosteView requestData)
        {
            Cidade cidade = UnitOfWork.CidadeRepository.Get(c => c.IdCidade == requestData.IdCidade).FirstOrDefault();

            if (cidade != null)
            {
                ConverterLatLonToUtm converter = new ConverterLatLonToUtm(cidade.Datum, cidade.NorteOuSul, cidade.Zona);
                UTM utm = converter.Convert(requestData.Latitude, requestData.Longitude);

                OrdemDeServico ordemDeServico = UnitOfWork.OrdemDeServicoRepository.Get(or => or.NumeroOS == requestData.IdOrdemServicoTexto).FirstOrDefault();

                Poste p = new Poste {
                    X = utm.X, Y = utm.Y, Cidade = cidade, DataCadastro = DateTime.Now, IdOrdemDeServico = ordemDeServico.IdOrdemDeServico, CodigoGeo = -1
                };

                UnitOfWork.PosteRepository.Insert(p);
                UnitOfWork.Save();

                Poste pst = UnitOfWork.PosteRepository.Get(pt => pt.X == p.X && pt.Y == p.Y, includeProperties: "Cidade").FirstOrDefault();

                PosteView posteview = new MetodosPosteView().PostetoPosteView(pst);

                return(Json(new ResponseView()
                {
                    Status = Status.Found, Result = posteview
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new ResponseView()
                {
                    Status = Status.NotFound, Result = Resources.Messages.Cidade_Not_Found
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #2
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);
            }
        }
예제 #3
0
        private void DoSimpleReceiving(object sender, DoWorkEventArgs e)
        {
            if (!(e.Argument is CancellationToken))
            {
                throw new ArgumentException("e.Argument is CancellationToken");
            }

            var cancelToken = (CancellationToken)e.Argument;

            //receiving loop as long as the subscrition is active or a chancelation is requested
            while (_subscription.isActive())
            {
                var msg = _subscription.receiveMessage();
                if (msg != null)
                {
                    //Receiving Pedestrian GPS msg using Player service
                    var Stream   = msg.getStreamID();
                    var datatype = (msg.getDataTypeID());
                    if (datatype == 16002349372918614042) //Datatype with GNSS Datatype
                    {
                        var gnss = (DioneData.Protobuf.GNSS.GlobalPositionData)ProtobufMessageConverter.MessageToProtobuf <DioneData.Protobuf.GNSS.GlobalPositionData>(msg);

                        //  var gnss = new DioneData.Protobuf.GNSS.GlobalPositionData();
                        var lat_gps    = gnss.Wgs84Latitude;
                        var lo_gps     = gnss.Wgs84Longitude;
                        var height_gps = gnss.Wgs84Height;

                        var wg = new WGS84();
                        wg.Latitude  = lat_gps;
                        wg.Longitude = lo_gps;
                        wg.Height    = height_gps;

                        //Covert WGS-84 to UTM coordinates
                        var utm = UTM.FromWGS84(wg, 33);

                        var reader = new HDMapReader(utm, gpsCoordinate_previous);

                        //For storing previous coordinate HISTORIZATION
                        PointQ History_gps = new PointQ();
                        History_gps.X          = utm.X;
                        History_gps.Y          = utm.Y;
                        gpsCoordinate_previous = History_gps;

                        //gpsCoordinate_previous.Y = utm.Y;
                        //Console.WriteLine("time stamp: " + time.ToString() + "\t" + "vehicle velocity: " + vel);

                        //  Console.WriteLine("WGS-Stream: " + Stream.ToString() + "\t" + "Pedestrian Latitude: " + lat);
                        //  Console.WriteLine("WGS-Stream: " + Stream.ToString() + "\t" + "Pedestrian Longitude: " + lo);
                        //  Console.WriteLine("WGS-Stream: " + Stream.ToString() + "\t" + "Pedestrian Altitude: " + al);

                        Console.WriteLine("UTM Coordinates of GPS: " + utm);
                    }
                }
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }
            }
        }
예제 #4
0
        public ActionResult DeleteConfirmed(int id)
        {
            UTM uTM = db.UTMs.Find(id);

            db.UTMs.Remove(uTM);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #5
0
 public ActionResult Edit([Bind(Include = "UTMID,UserID,TransportMethodID")] UTM uTM)
 {
     if (ModelState.IsValid)
     {
         db.Entry(uTM).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.TransportMethodID = new SelectList(db.TransportMethods, "TransportMethodID", "TransportMode", uTM.TransportMethodID);
     ViewBag.UserID            = new SelectList(db.AspNetUsers, "Id", "Email", uTM.UserID);
     return(View(uTM));
 }
예제 #6
0
        private void btnConvertToMgrs_Click(object sender, EventArgs e)
        {
            // Geographic geo = new Geographic(8.12345, 50.56789);
            Geographic geo   = new Geographic(9.692965, 8.447336);
            UTM        utm   = (UTM)geo;
            double     east  = utm.East;
            double     north = utm.North;
            int        zone  = utm.Zone;
            string     band  = utm.Band;

            lblLonMgrs.Text = "longitude = " + Convert.ToString(east);
            lblLatMgrs.Text = "lattitude = " + Convert.ToString(north) + " ZONE: " + Convert.ToString(zone) + "BAND : " + band;
        }
예제 #7
0
        public ActionResult SalvarArrastarPoste(PosteJs objeto_poste)
        {
            Poste posteBd = UnitOfWork.PosteRepository.Get(pp => pp.IdPoste == objeto_poste.IdPoste && pp.DataExclusao == null, includeProperties: "OrdemDeServico,Cidade").FirstOrDefault();
            var   vaos    = UnitOfWork.VaosDemandaPosteRepository.Get(v => v.IdPoste == objeto_poste.IdPoste).ToList();

            if (posteBd != null)
            {
                ConverterLatLonToUtm converter = new ConverterLatLonToUtm(posteBd.Cidade.Datum, posteBd.Cidade.NorteOuSul, posteBd.Cidade.Zona);
                UTM utm = converter.Convert(objeto_poste.Latitude, objeto_poste.Longitude);

                posteBd.X = utm.X;
                posteBd.Y = utm.Y;
                //posteBd.Esforco = objeto_poste.Esforco != null ? objeto_poste.Esforco.ToUpper() : "";
                //posteBd.TipoPoste = objeto_poste.TipoPoste;
                //posteBd.Altura = objeto_poste.Altura;
                //posteBd.Descricao = objeto_poste.Descricao != null ? objeto_poste.Descricao.ToUpper() : "";
                //posteBd.DataCadastro = DateTime.Now;

                /// Atualizando o Poste
                UnitOfWork.PosteRepository.Update(posteBd);

                //Salvando as Alteraçoes
                UnitOfWork.Save();

                Poste poste = UnitOfWork.PosteRepository.Get(p => p.IdPoste == objeto_poste.IdPoste).FirstOrDefault();

                if (vaos != null)
                {
                    foreach (var item in vaos)
                    {
                        item.X1 = utm.X;
                        item.Y1 = utm.Y;
                    }
                }

                UnitOfWork.Save();

                return(Json(new
                {
                    Poste = PostePaginadoView.GeneratePosteUnico(poste),
                    VaosDemandas = VaosDemandasPaginadoView.GenerateByOs(vaos)
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new ResponseView()
                {
                    Status = Status.NotFound, Result = Resources.Messages.Poste_Not_Found
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #8
0
        // GET: UTMs/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UTM uTM = db.UTMs.Find(id);

            if (uTM == null)
            {
                return(HttpNotFound());
            }
            return(View(uTM));
        }
예제 #9
0
        /// <summary><para>Ein Konstruktor mit den Parametern für Zone, East und Nordwert, sowie Hemisphäre.</para></summary>
        /// <param name="zone">Zone</param>
        /// <param name="east">East</param>
        /// <param name="north">North</param>
        /// <param name="hem">Hemisphäre: Nord, Süd</param>
        protected Geocentric(int zone, double east, double north, Hemisphere hem)
        {
            string band = "N";                                                      // Transformationsroutine auf Nordhalbkugel setzen 
            if (hem == Hemisphere.South) band = "A";                                // Transformationsroutine auf Südhalbkugel setzen 
            Geographic geo = Transform.UTMWGS(new UTM(zone, band, east, north));
            geo.Longitude = Math.Round(geo.Longitude, 4);                           // Ohne Rundung könnte Bandberechnung fehlerbehaftet sein
            geo.Latitude = Math.Round(geo.Latitude, 4);                             // Ohne Rundung könnte Bandberechnung fehlerbehaftet sein
            UTM utm = Transform.WGSUTM(geo);                                       // Doppelte Transformation um Band zu berechnen

            this.East = east;
            this.North = north;
            this.Zone = zone;
            this.Band = utm.Band;

        }
예제 #10
0
        // GET: UTMs/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UTM uTM = db.UTMs.Find(id);

            if (uTM == null)
            {
                return(HttpNotFound());
            }
            ViewBag.TransportMethodID = new SelectList(db.TransportMethods, "TransportMethodID", "TransportMode", uTM.TransportMethodID);
            ViewBag.UserID            = new SelectList(db.AspNetUsers, "Id", "Email", uTM.UserID);
            return(View(uTM));
        }
예제 #11
0
        public ActionResult NewAnotacao(AnotacaoView requestData)
        {
            Cidade         cidade         = UnitOfWork.CidadeRepository.Get(c => c.IdCidade == requestData.IdCidade).FirstOrDefault();
            OrdemDeServico ordemDeServico = UnitOfWork.OrdemDeServicoRepository.Get(or => or.NumeroOS == requestData.NumeroOs).FirstOrDefault();

            if (cidade != null)
            {
                ConverterLatLonToUtm converter = new ConverterLatLonToUtm(cidade.Datum, cidade.NorteOuSul, cidade.Zona);
                UTM utm = converter.Convert(requestData.X, requestData.Y);

                Anotacao anotacao = new Anotacao
                {
                    IdCidade         = cidade.IdCidade,
                    IdOrdemDeServico = ordemDeServico.IdOrdemDeServico,
                    Descricao        = requestData.Descricao,
                    X = utm.X,
                    Y = utm.Y
                };
                UnitOfWork.AnotacaoRepository.Insert(anotacao);
                UnitOfWork.Save();

                Anotacao     anotacaoview = UnitOfWork.AnotacaoRepository.Get(nota => nota.IdAnotacao == anotacao.IdAnotacao).FirstOrDefault();
                AnotacaoView AnotacaoView = new AnotacaoPaginadoView().AnotacaToAnotacaoView(anotacaoview);

                /*  var notas = new
                 * {
                 *    IdCidade = anotacaoview.IdCidade,
                 *    IdOrdemDeServico = anotacaoview.IdOrdemDeServico,
                 *    Descricao = anotacaoview.Descricao,
                 *    X = anotacaoview.X,
                 *    Y = anotacaoview.Y
                 * };*/

                return(Json(new ResponseView()
                {
                    Status = Status.Found, Result = AnotacaoView
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new ResponseView()
                {
                    Status = Status.NotFound, Result = "Cidade nao Encontrada"
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #12
0
        public ActionResult NovoNoMaps([System.Web.Http.FromBody] DemandaStrandView demandaStrandView)
        {
            Cidade cidade = UnitOfWork.CidadeRepository.Get(c => c.IdCidade == demandaStrandView.IdCidade).FirstOrDefault();
            ConverterLatLonToUtm converter = null;

            if (cidade != null)
            {
                converter = new ConverterLatLonToUtm(cidade.Datum, cidade.NorteOuSul, cidade.Zona);


                OrdemDeServico ordemDeServico = UnitOfWork.OrdemDeServicoRepository.Get(or => or.NumeroOS == demandaStrandView.NumeroOs).FirstOrDefault();

                double x1 = Double.Parse(demandaStrandView.X1Texto, System.Globalization.CultureInfo.InvariantCulture);
                double y1 = Double.Parse(demandaStrandView.Y1Texto, System.Globalization.CultureInfo.InvariantCulture);
                double x2 = Double.Parse(demandaStrandView.X2Texto, System.Globalization.CultureInfo.InvariantCulture);
                double y2 = Double.Parse(demandaStrandView.Y2Texto, System.Globalization.CultureInfo.InvariantCulture);

                UTM utm1 = converter.Convert(x1, y1);
                UTM utm2 = converter.Convert(x2, y2);

                DemandaStrand demandaStrand = new DemandaStrand
                {
                    IdCidade         = demandaStrandView.IdCidade,
                    IdOrdemDeServico = ordemDeServico.IdOrdemDeServico,
                    X1           = utm1.X,
                    Y1           = utm1.Y,
                    X2           = utm2.X,
                    Y2           = utm2.Y,
                    DataInclusao = DateTime.Now
                };

                UnitOfWork.DemandaStrandRepository.Insert(demandaStrand);
                UnitOfWork.Save();

                DemandaStrand strand = UnitOfWork.DemandaStrandRepository.Get(d => d.ID == demandaStrand.ID).FirstOrDefault();

                return(Json(StrandPaginadoView.GenerateUnico(strand), JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { Status = Status.NotFound, Result = "Cidade nao encontrada!" }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #13
0
파일: MGRS.cs 프로젝트: andrewgbuck/GPV
    public override void ToGrid(double lon, double lat, out string gridValue)
    {
        char[] letters = new char[3];

        double zoneLat = lat < -80 ? -80 : lat > 72 ? 72 : lat;

        letters[0] = _zoneLetters[Convert.ToInt32(Math.Floor((zoneLat + 80) / 8))];

        double     n          = lon >= 180 ? lon - 180 : lon + 180;
        int        zone       = Convert.ToInt32(Math.Floor(n / 6)) + 1;
        Hemisphere hemisphere = lat >= 0 ? Hemisphere.North : Hemisphere.South;

        UTM utm = new UTM(zone, hemisphere);

        double x;
        double y;

        utm.ToProjected(lon, lat, out x, out y);

        double divisor = Math.Pow(10, 5 - _precision);

        x = Math.Round(x / divisor) * divisor;
        y = Math.Round(y / divisor) * divisor;

        int setNumber = (zone - 1) % 6;

        letters[1] = _columnLetters[(setNumber % 3) * 8 + Convert.ToInt32(Math.Floor(x / 100000)) - 1];

        int rowOffset = setNumber % 2 == 1 ? 5 : 0;

        y         %= 2000000;
        letters[2] = _rowLetters[(Convert.ToInt32(Math.Floor(y / 100000)) + rowOffset) % _rowLetters.Length];

        x = (x % 100000) / divisor;
        y = (y % 100000) / divisor;

        string f = new String('0', _precision);

        gridValue = String.Format("{0}{1} {2} {3}", zone, new String(letters), x.ToString(f), y.ToString(f));
    }
예제 #14
0
        public Ham.SpatialBase.IPoint GetWgs84Point()
        {
            var point = new IRI.Ham.SpatialBase.Point(X, Y);

            switch (this.SelectedItem?.MenuType)
            {
            case SpatialReferenceType.Geodetic:
                return(point);   //.Project( ,new IRI.Ham.CoordinateSystem.MapProjection.NoProjection());

            case SpatialReferenceType.UTM:
                return(point.Project(UTM.CreateForZone(UtmZone), new NoProjection()));

            case SpatialReferenceType.Mercator:
            case SpatialReferenceType.TransverseMercator:
            case SpatialReferenceType.CylindricalEqualArea:
            case SpatialReferenceType.LambertConformalConic:
            case SpatialReferenceType.WebMercator:
            case SpatialReferenceType.AlbersEqualAreaConic:
            default:
                throw new NotImplementedException();
            }
        }
예제 #15
0
파일: MGRS.cs 프로젝트: jsmeyers/GPV
    public override string ToGrid(Coordinate g)
    {
        char[] letters = new char[3];

        double zoneLat = g.Y < -80 ? -80 : g.Y > 72 ? 72 : g.Y;

        letters[0] = _zoneLetters[Convert.ToInt32(Math.Floor((zoneLat + 80) / 8))];

        double     n          = g.X >= 180 ? g.X - 180 : g.X + 180;
        int        zone       = Convert.ToInt32(Math.Floor(n / 6)) + 1;
        Hemisphere hemisphere = g.Y >= 0 ? Hemisphere.North : Hemisphere.South;

        UTM utm = new UTM(zone, hemisphere);

        Coordinate p = utm.ToProjected(g);
        double     x = p.X;
        double     y = p.Y;

        double divisor = Math.Pow(10, 5 - _precision);

        x = Math.Round(x / divisor) * divisor;
        y = Math.Round(y / divisor) * divisor;

        int setNumber = (zone - 1) % 6;

        letters[1] = _columnLetters[(setNumber % 3) * 8 + Convert.ToInt32(Math.Floor(x / 100000)) - 1];

        int rowOffset = setNumber % 2 == 1 ? 5 : 0;

        y         %= 2000000;
        letters[2] = _rowLetters[(Convert.ToInt32(Math.Floor(y / 100000)) + rowOffset) % _rowLetters.Length];

        x = (x % 100000) / divisor;
        y = (y % 100000) / divisor;

        string f = new String('0', _precision);

        return(String.Format("{0}{1} {2} {3}", zone, new String(letters), x.ToString(f), y.ToString(f)));
    }
예제 #16
0
        private static EsriPrjFile AsEsriPrjFile(UTM utm)
        {
            EsriPrjTreeNode root = new EsriPrjTreeNode();

            root.Name = EsriPrjFile._projcs;

            string ns = utm.FalseNorthing == 0 ? "N" : "S";

            var zone = IRI.Msh.CoordinateSystem.MapProjection.MapProjects.FindZone(utm.CentralMeridian);

            root.Values = new List <string>()
            {
                string.IsNullOrWhiteSpace(utm.Title) ? $"WGS_1984_UTM_Zone_{zone}{ns}" : utm.Title
            };

            var geogcs = new EsriPrjTreeNode(utm.Ellipsoid, utm.DatumName, utm.Ellipsoid.Srid);

            var projection = new EsriPrjTreeNode(EsriPrjFile._projection, EsriPrjFile._esriTransverseMercator);

            var falseEasting = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._falseEasting, utm.FalseEasting.AsExactString());

            var falseNorthing = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._falseNorthing, utm.FalseNorthing.AsExactString());

            var centralMeridian = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._centralMeridian, utm.CentralMeridian.AsExactString());

            var scaleFactor = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._scaleFactor, utm.ScaleFactor.AsExactString());

            var latitudeOfOrigin = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._latitudeOfOrigin, utm.StandardParallel2.AsExactString());

            var unit = EsriPrjTreeNode.MeterUnit;

            root.Children = new List <EsriPrjTreeNode>()
            {
                geogcs, projection, falseEasting, falseNorthing, centralMeridian, scaleFactor, latitudeOfOrigin, unit
            };

            return(new EsriPrjFile(root));
        }
예제 #17
0
파일: MGRS.cs 프로젝트: ClaireBrill/GPV
	public override void ToGrid(double lon, double lat, out string gridValue)
	{
		char[] letters = new char[3];

		double zoneLat = lat < -80 ? -80 : lat > 72 ? 72 : lat;
		letters[0] = _zoneLetters[Convert.ToInt32(Math.Floor((zoneLat + 80) / 8))];

		double n = lon >= 180 ? lon - 180 : lon + 180;
		int zone = Convert.ToInt32(Math.Floor(n / 6)) + 1;
		Hemisphere hemisphere = lat >= 0 ? Hemisphere.North : Hemisphere.South;

		UTM utm = new UTM(zone, hemisphere);

		double x;
		double y;
		utm.ToProjected(lon, lat, out x, out y);

		double divisor = Math.Pow(10, 5 - _precision);
		x = Math.Round(x / divisor) * divisor;
		y = Math.Round(y / divisor) * divisor;

		int setNumber = (zone - 1) % 6;
		letters[1] = _columnLetters[(setNumber % 3) * 8 + Convert.ToInt32(Math.Floor(x / 100000)) - 1];

		int rowOffset = setNumber % 2 == 1 ? 5 : 0;

		y %= 2000000;
		letters[2] = _rowLetters[(Convert.ToInt32(Math.Floor(y / 100000)) + rowOffset) % _rowLetters.Length];

		x = (x % 100000) / divisor;
		y = (y % 100000) / divisor;

		string f = new String('0', _precision);
		gridValue = String.Format("{0}{1} {2} {3}", zone, new String(letters), x.ToString(f), y.ToString(f));
	}
예제 #18
0
 public static bool TryParse(string text, out UTM result)
 {
     result = null;
     if (string.IsNullOrEmpty(text)) return false;
     var split = text.Trim().Split(' ');
     var match = Regex.Match(split[0], @"^(\d+)([A-Z])$");
     double easting, northing;
     int zone;
     if (!(split.Length == 3 && match.Groups[0].Success
                 && int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out zone)
                 && double.TryParse(split[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out easting)
                 && double.TryParse(split[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out northing)))
         return false;
     char emisphere = match.Groups[2].Value[0];
     try {
         result = new UTM(easting, northing, emisphere, zone);
         return true;
     } catch { }
     return false;
 }
예제 #19
0
        public HDMapReader(UTM utm, PointQ gpsCoordinate_previous)
        {
            //Reading HDMap.bin binary file from MapDatabase
            _mapDatabase = MapDatabase.LoadFromFile("HDMap.bin");

            //Extract Road Surfaces form MapDatabase
            System.Collections.ObjectModel.ReadOnlyCollection <RoadSurface> rsurf = new System.Collections.ObjectModel.ReadOnlyCollection <RoadSurface>(_mapDatabase.GetRoadSurfaces());

            //Initialize Pedestrian GPS coordinates of type PoinQ from Recorded Stream
            PointQ gpsCoordinates = new PointQ {
                X = utm.X, Y = utm.Y
            };

            Console.WriteLine();
            foreach (RoadSurface rs in rsurf)
            {
                //Initialize Polygon List
                List <PointQ> polygon = new List <PointQ>();

                //Initialize a list of type PointQ with all possible end points/coordinates
                List <PointQ> allEndPoints = new List <PointQ>();

                //Extract Accessors from Road Surfaces
                System.Collections.ObjectModel.ReadOnlyCollection <Accessor> accessors = new System.Collections.ObjectModel.ReadOnlyCollection <Accessor>(rs.GetAccessors());
                foreach (Accessor a in accessors)
                {
                    //Console.WriteLine("Id: " + a.Id.ToString());
                    // Console.WriteLine("LeftRoadSurface: " + a.LeftRoadSurface.ToString());
                    // Console.WriteLine("Line: " + a.Line.ToString());
                    // Console.WriteLine("Point A:" + a.Line.Begin.ToString());
                    // Console.WriteLine("Point B:" + a.Line.End.ToString());
                    // Console.WriteLine("RightRoadSurface: " + a.RightRoadSurface);
                    // Console.WriteLine("StartingConnections: " + a.StartingConnections.ToString());

                    //Creat Road surface points using Accessors as boundary points
                    PointQ strt = new PointQ();
                    strt.X = a.Line.Begin.X;
                    strt.Y = a.Line.Begin.Y;

                    PointQ finish = new PointQ();
                    finish.X = a.Line.End.X;
                    finish.Y = a.Line.End.Y;

                    polygon.Add(strt);
                    polygon.Add(finish);

                    //Extract Lanes Types
                    System.Collections.Generic.IList <Lane> lane = new List <Lane>(rs.GetLanes());
                    foreach (Lane l in lane)
                    {
                    }
                }
                //Extract Borders
                System.Collections.Generic.IList <Border>           border  = new List <Border>(rs.GetBorders());
                System.Collections.Generic.IList <IParametricCurve> outline = new List <IParametricCurve>(rs.GetOutline());
                //Extract Connections
                System.Collections.Generic.IList <TUC.Data.HDMap.Connection> connections = new List <TUC.Data.HDMap.Connection>(rs.GetConnections());

                foreach (Connection c in connections)
                {
                    //  Console.WriteLine("Connection 1 Begin Point: " + ((TUC.Data.HDMap.QuinticHermiteCurve)c.CenterCurve).Begin.ToString());
                    // Console.WriteLine("Connection 1 End Point: " + ((TUC.Data.HDMap.QuinticHermiteCurve)c.CenterCurve).End.ToString());

                    //Inialize Connection Points
                    PointQ begin = new PointQ();
                    begin.X = ((QuinticHermiteCurve)c.CenterCurve).Begin.X;
                    begin.Y = ((QuinticHermiteCurve)c.CenterCurve).Begin.Y;

                    PointQ end = new PointQ();
                    end.X = ((QuinticHermiteCurve)c.CenterCurve).End.X;
                    end.Y = ((QuinticHermiteCurve)c.CenterCurve).End.Y;

                    //List<PointQ> allBeginPoints = new List<PointQ>();

                    // List<PointQ> allEndPoints = new List<PointQ>();

                    allEndPoints.Add(begin);
                    allEndPoints.Add(end);

                    //  Console.WriteLine("All Points:" + allEndPoints.ToString());

                    //allEndPoints.Add(Connection.endpoint); // add all connection end points like this


                    //AlgorithProbabailty(gpsCoordinates, allPoints);
                    // allEndPoints.Add((TUC.Data.HDMap.QuinticHermiteCurve)c.CenterCurve).Begin;
                    // allEndPoints.Add((QuinticHermiteCurve)c.CenterCurve).Begin;
                    // allEndPoints.Add((TUC.Data.HDMap.QuinticHermiteCurve)c.CenterCurve).
                }
                //
                bool x = IsPointInPolygon(polygon, new PointQ {
                    X = utm.X, Y = utm.Y
                });
                if (x == true)
                {
                    Console.WriteLine("Pedestriian is Inside of Surface ID: " + rs.Id.ToString());
                    Console.ReadLine();
                    predictTrajectory(gpsCoordinates, allEndPoints, gpsCoordinate_previous);
                }
                else
                {
                    Console.WriteLine("Pedestrian is outside of surface ID: " + rs.Id.ToString());
                    Console.ReadLine();
                }

                // TrajectoryPredictor tp = new TrajectoryPredictor();

                //   tp.predictTrajectory(gpsCoordinates, allEndPoints);
                // tp.gpsCoordinate_previous = gpsCoordinates;
            }
        }
예제 #20
0
        public ActionResult SalvarPontoEntregaNovo(PontoEntregaView PontoEntregaReceived)
        {
            Cidade Cidade = UnitOfWork.CidadeRepository.Get(c => c.IdCidade == PontoEntregaReceived.IdCidade).FirstOrDefault();

            if (Cidade != null)
            {
                double latPonto = Double.Parse(PontoEntregaReceived.LatitudeTexto, System.Globalization.CultureInfo.InvariantCulture);
                double lonPonto = Double.Parse(PontoEntregaReceived.LongitudeTexto, System.Globalization.CultureInfo.InvariantCulture);

                //double latPoste = Double.Parse(PontoEntregaReceived.LatitudePosteTexto, System.Globalization.CultureInfo.InvariantCulture);
                //  double lonPoste = Double.Parse(PontoEntregaReceived.LongitudePosteTexto, System.Globalization.CultureInfo.InvariantCulture);

                OrdemDeServico ordemServico = UnitOfWork.OrdemDeServicoRepository.Get(or => or.NumeroOS == PontoEntregaReceived.IdOrdemServicoTexto).FirstOrDefault();

                ConverterLatLonToUtm converter = new ConverterLatLonToUtm(Cidade.Datum, Cidade.NorteOuSul, Cidade.Zona);
                UTM utmPonto = converter.Convert(latPonto, lonPonto);
                //    UTM utmPoste = converter.Convert(latPoste, lonPoste);

                PontoEntrega new_ponto_entrega = new PontoEntrega();

                new_ponto_entrega.IdCidade     = PontoEntregaReceived.IdCidade;
                new_ponto_entrega.IdPoste      = PontoEntregaReceived.IdPoste;
                new_ponto_entrega.CodigoGeoBD  = PontoEntregaReceived.CodigoGeoBD;
                new_ponto_entrega.Complemento1 = PontoEntregaReceived.Complemento1;
                // new_ponto_entrega.ClasseAtendimento = PontoEntregaReceived.ClasseAtendimento;
                // new_ponto_entrega.TipoConstrucao = PontoEntregaReceived.TipoConstrucao;
                new_ponto_entrega.Numero       = PontoEntregaReceived.Numero;
                new_ponto_entrega.ClasseSocial = PontoEntregaReceived.ClasseSocial;
                // new_ponto_entrega.Logradouro = PontoEntregaReceived.Logradouro;
                // new_ponto_entrega.Fase = PontoEntregaReceived.Fase;
                // new_ponto_entrega.EtLigacao = PontoEntregaReceived.EtLigacao;
                // new_ponto_entrega.Observacao = PontoEntregaReceived.Observacao;
                new_ponto_entrega.X = utmPonto.X;
                new_ponto_entrega.Y = utmPonto.Y;
                new_ponto_entrega.IdOrdemDeServico = ordemServico.IdOrdemDeServico;
                new_ponto_entrega.DataInclusao     = DateTime.Now;

                new_ponto_entrega.Classificacao             = PontoEntregaReceived.Classificacao;
                new_ponto_entrega.Ocorrencia                = PontoEntregaReceived.Ocorrencia;
                new_ponto_entrega.QtdDomicilio              = PontoEntregaReceived.QtdDomicilio;
                new_ponto_entrega.QtdSalas                  = PontoEntregaReceived.QtdDomicilioComercio;
                new_ponto_entrega.NumeroAndaresEdificio     = PontoEntregaReceived.NumeroAndaresEdificio;
                new_ponto_entrega.TotalApartamentosEdificio = PontoEntregaReceived.TotalApartamentosEdificio;
                new_ponto_entrega.NomeEdificio              = PontoEntregaReceived.NomeEdificio;
                new_ponto_entrega.QtdBlocos                 = PontoEntregaReceived.QtdBlocos;
                new_ponto_entrega.TipoComercio              = PontoEntregaReceived.ClassificacaoComercio;


                /// Atualizando o Ponto Entrega
                UnitOfWork.PontoEntregaRepository.Insert(new_ponto_entrega);

                /*  if (PontoEntregaReceived.Medidores != null)
                 * {
                 *    foreach (MedidorView medidor_view in PontoEntregaReceived.Medidores)
                 *    {
                 *        /// Inserindo os Medidores
                 *        UnitOfWork.MedidoresRepository.Insert(new Medidor
                 *        {
                 *            IdPontoEntrega = new_ponto_entrega.IdPontoEntrega,
                 *            NumeroMedidor = medidor_view.NumeroMedidor,
                 *            ComplementoResidencial = medidor_view.ComplementoResidencial
                 *        });
                 *    }
                 * }*/

                /*   foreach (FotoPontoEntregaView foto in PontoEntregaReceived.Fotos)
                 * {
                 *     /// Nao deve Vim foto_view.DataFoto vazio mas se vim nao quebra o codigo
                 *     DateTime DataDiretorio = foto.DataFoto != String.Empty ? Convert.ToDateTime(foto.DataFoto) : DateTime.Now;
                 *     String Data = DataDiretorio.ToString("ddMMyyyy");
                 *
                 *     FotoPontoEntrega novaFoto = new FotoPontoEntrega();
                 *     novaFoto.CodigoGeoBD = -1;
                 *     novaFoto.DataFoto = Convert.ToDateTime(foto.DataFoto);
                 *     novaFoto.IdPontoEntrega = new_ponto_entrega.IdPontoEntrega;
                 *     novaFoto.NumeroFoto = foto.NumeroFoto.Trim();
                 *     novaFoto.DataExclusao = null;
                 *     novaFoto.Path = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], Cidade.CidadeDiretorio, Data, User.Identity.Name.ToUpper(), foto.NumeroFoto.Trim().ToUpper());
                 *     novaFoto.PontoEntrega = new_ponto_entrega;
                 *
                 *     UnitOfWork.FotoPontoEntregaRepository.Insert(novaFoto);
                 * }*/
                UnitOfWork.Save();
                PontoEntrega pontoEntrega = UnitOfWork.PontoEntregaRepository.Get(p => p.IdPontoEntrega == new_ponto_entrega.IdPontoEntrega).FirstOrDefault();

                Poste Poste = UnitOfWork.PosteRepository.Get(p => p.IdPoste == PontoEntregaReceived.IdPoste).FirstOrDefault();
                if (Poste != null)
                {
                    VaosDemandaPoste vaosDemandaPoste = new VaosDemandaPoste
                    {
                        IdCidade         = PontoEntregaReceived.IdCidade,
                        IdOrdemDeServico = ordemServico.IdOrdemDeServico,
                        IdPoste          = PontoEntregaReceived.IdPoste,
                        IdPontoEntrega   = new_ponto_entrega.IdPontoEntrega,
                        X1 = Poste.X,
                        Y1 = Poste.Y,
                        X2 = utmPonto.X,
                        Y2 = utmPonto.Y,
                    };
                    UnitOfWork.VaosDemandaPosteRepository.Insert(vaosDemandaPoste);
                    UnitOfWork.Save();

                    VaosDemandaPoste VaosDemandaPoste = UnitOfWork.VaosDemandaPosteRepository.Get(v => v.IdVaosDemandaPoste == vaosDemandaPoste.IdVaosDemandaPoste).FirstOrDefault();

                    //                return Json(new MetodosPontoEntregaView().PontoEntregaToPontoEntregaView(PontoEntrega), JsonRequestBehavior.AllowGet);

                    return(Json(new
                    {
                        Demanda = new MetodosPontoEntregaView().PontoEntregaToPontoEntregaView(pontoEntrega),
                        VaoDemandaPoste = new VaosDemandasPaginadoView().VaoToVaoView(VaosDemandaPoste)
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new
                    {
                        Demanda = new MetodosPontoEntregaView().PontoEntregaToPontoEntregaView(pontoEntrega)
                    },
                                JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                return(Json(new ResponseView()
                {
                    Status = Status.NotFound, Result = "Cidade nao encontrada"
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #21
0
        public ActionResult SalvarPontoEntrega(PontoEntregaView PontoEntregaReceived)
        {
            if (PontoEntregaReceived != null)
            {
                //Poste poste = UnitOfWork.PosteRepository.Get(p => p.IdPoste == PontoEntregaReceived.IdPoste).FirstOrDefault();
                Cidade cidade = UnitOfWork.CidadeRepository.Get(c => c.IdCidade == PontoEntregaReceived.IdCidade).FirstOrDefault();

                ConverterLatLonToUtm converter = new ConverterLatLonToUtm(cidade.Datum, cidade.NorteOuSul, cidade.Zona);
                UTM utm = converter.Convert(PontoEntregaReceived.Latitude, PontoEntregaReceived.Longitude);

                if (PontoEntregaReceived.IdPontoEntrega != -1)
                {
                    #region Atualiza Ponto de Entrega

                    PontoEntrega ponto_entrega_bd = UnitOfWork.PontoEntregaRepository.Get(p => p.IdPontoEntrega == PontoEntregaReceived.IdPontoEntrega).FirstOrDefault();

                    // ponto_entrega_bd.IdPontoEntrega = PontoEntregaReceived.IdPontoEntrega;
                    //ponto_entrega_bd.IdPoste = PontoEntregaReceived.IdPoste;
                    ponto_entrega_bd.CodigoGeoBD = PontoEntregaReceived.CodigoGeoBD;
                    //   ponto_entrega_bd.IdOrdemDeServico = PontoEntregaReceived.IdOrdemServico;

                    ponto_entrega_bd.Classificacao = PontoEntregaReceived.Classificacao;
                    ponto_entrega_bd.Complemento1  = PontoEntregaReceived.Complemento1;
                    //ponto_entrega_bd.Complemento2 = PontoEntregaReceived.Complemento2;

                    //ponto_entrega_bd.Status = PontoEntregaReceived.Status;
                    // ponto_entrega_bd.ClasseAtendimento = PontoEntregaReceived.ClasseAtendimento;
                    //ponto_entrega_bd.TipoConstrucao = PontoEntregaReceived.TipoConstrucao;
                    ponto_entrega_bd.Numero       = PontoEntregaReceived.Numero;
                    ponto_entrega_bd.ClasseSocial = PontoEntregaReceived.ClasseSocial;
                    ponto_entrega_bd.IdLagradouro = PontoEntregaReceived.IdLogradouro;

                    ponto_entrega_bd.Classificacao             = PontoEntregaReceived.Classificacao;
                    ponto_entrega_bd.Ocorrencia                = PontoEntregaReceived.Ocorrencia;
                    ponto_entrega_bd.QtdDomicilio              = PontoEntregaReceived.QtdDomicilio;
                    ponto_entrega_bd.NumeroAndaresEdificio     = PontoEntregaReceived.NumeroAndaresEdificio;
                    ponto_entrega_bd.TotalApartamentosEdificio = PontoEntregaReceived.TotalApartamentosEdificio;
                    ponto_entrega_bd.NomeEdificio              = PontoEntregaReceived.NomeEdificio;
                    ponto_entrega_bd.QtdBlocos    = PontoEntregaReceived.QtdBlocos;
                    ponto_entrega_bd.TipoComercio = PontoEntregaReceived.ClassificacaoComercio;
                    ponto_entrega_bd.QtdSalas     = PontoEntregaReceived.QtdDomicilioComercio;
                    //ponto_entrega_bd.Fase = PontoEntregaReceived.Fase;
                    //ponto_entrega_bd.EtLigacao = PontoEntregaReceived.EtLigacao;
                    // ponto_entrega_bd.Observacao = PontoEntregaReceived.Observacao;
                    //ponto_entrega_bd.X = utm.X;
                    // ponto_entrega_bd.Y = utm.Y;

                    /// Atualizando o Ponto Entrega
                    UnitOfWork.PontoEntregaRepository.Update(ponto_entrega_bd);

                    List <Medidor> medidores_ponto_entrega = UnitOfWork.MedidoresRepository.Get(m => m.IdPontoEntrega == PontoEntregaReceived.IdPontoEntrega).ToList();

                    /// Apagando os Medidores do Ponto de Entrega
                    foreach (Medidor medidor_bd in medidores_ponto_entrega)
                    {
                        UnitOfWork.MedidoresRepository.Delete(medidor_bd);
                    }

                    /* if (PontoEntregaReceived.Medidores != null)
                     * {
                     *   foreach (MedidorView medidor_view in PontoEntregaReceived.Medidores)
                     *   {
                     *       /// Inserindo os Medidores
                     *       UnitOfWork.MedidoresRepository.Insert(new Medidor
                     *       {
                     *           IdPontoEntrega = medidor_view.IdPontoEntrega,
                     *           NumeroMedidor = medidor_view.NumeroMedidor,
                     *           ComplementoResidencial = medidor_view.ComplementoResidencial
                     *       });
                     *   }
                     * }*/

                    /// Apagando Fotos do ponto de Entrega
                    List <FotoPontoEntrega> fotos_BD = UnitOfWork.FotoPontoEntregaRepository.Get(p => p.IdPontoEntrega == PontoEntregaReceived.IdPontoEntrega).ToList();

                    foreach (FotoPontoEntrega foto_bd in fotos_BD)
                    {
                        UnitOfWork.FotoPontoEntregaRepository.Delete(foto_bd);
                    }

                    if (PontoEntregaReceived.Fotos != null)
                    {
                        foreach (FotoPontoEntregaView foto in PontoEntregaReceived.Fotos)
                        {
                            /// Nao deve Vim foto_view.DataFoto vazio mas se vim nao quebra o codigo
                            DateTime DataDiretorio = foto.DataFoto != String.Empty ? Convert.ToDateTime(foto.DataFoto) : DateTime.Now;
                            String   Data          = DataDiretorio.ToString("ddMMyyyy");

                            UnitOfWork.FotoPontoEntregaRepository.Insert(
                                new FotoPontoEntrega()
                            {
                                CodigoGeoBD    = -1,
                                DataFoto       = Convert.ToDateTime(foto.DataFoto),
                                IdPontoEntrega = PontoEntregaReceived.IdPontoEntrega,
                                NumeroFoto     = foto.NumeroFoto.Trim(),
                                DataExclusao   = null,
                                Path           = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], cidade.CidadeDiretorio, Data, User.Identity.Name.ToUpper(), foto.NumeroFoto.Trim().ToUpper())
                            });
                        }
                    }


                    //Salvando as Alteraçoes
                    UnitOfWork.Save();


                    #endregion
                }
                else
                {
                    #region Novo Ponto de Entrega

                    PontoEntrega new_ponto_entrega = new PontoEntrega();

                    new_ponto_entrega.IdPoste     = PontoEntregaReceived.IdPoste;
                    new_ponto_entrega.CodigoGeoBD = PontoEntregaReceived.CodigoGeoBD;
                    // new_ponto_entrega.Status = PontoEntregaReceived.Status;
                    // new_ponto_entrega.ClasseAtendimento = PontoEntregaReceived.ClasseAtendimento;
                    // new_ponto_entrega.TipoConstrucao = PontoEntregaReceived.TipoConstrucao;
                    new_ponto_entrega.Numero       = PontoEntregaReceived.Numero;
                    new_ponto_entrega.ClasseSocial = PontoEntregaReceived.ClasseSocial;
                    // new_ponto_entrega.Logradouro = PontoEntregaReceived.Logradouro;
                    // new_ponto_entrega.Fase = PontoEntregaReceived.Fase;
                    // new_ponto_entrega.EtLigacao = PontoEntregaReceived.EtLigacao;
                    // new_ponto_entrega.Observacao = PontoEntregaReceived.Observacao;
                    new_ponto_entrega.X = utm.X;
                    new_ponto_entrega.Y = utm.Y;

                    /// Atualizando o Ponto Entrega
                    UnitOfWork.PontoEntregaRepository.Insert(new_ponto_entrega);

                    /*  if (PontoEntregaReceived.Medidores != null)
                     * {
                     *    foreach (MedidorView medidor_view in PontoEntregaReceived.Medidores)
                     *    {
                     *        /// Inserindo os Medidores
                     *        UnitOfWork.MedidoresRepository.Insert(new Medidor
                     *        {
                     *            IdPontoEntrega = new_ponto_entrega.IdPontoEntrega,
                     *            NumeroMedidor = medidor_view.NumeroMedidor,
                     *            ComplementoResidencial = medidor_view.ComplementoResidencial
                     *        });
                     *    }
                     * }*/

                    foreach (FotoPontoEntregaView foto in PontoEntregaReceived.Fotos)
                    {
                        /// Nao deve Vim foto_view.DataFoto vazio mas se vim nao quebra o codigo
                        DateTime DataDiretorio = foto.DataFoto != String.Empty ? Convert.ToDateTime(foto.DataFoto) : DateTime.Now;
                        String   Data          = DataDiretorio.ToString("ddMMyyyy");

                        FotoPontoEntrega novaFoto = new FotoPontoEntrega();
                        novaFoto.CodigoGeoBD    = -1;
                        novaFoto.DataFoto       = Convert.ToDateTime(foto.DataFoto);
                        novaFoto.IdPontoEntrega = new_ponto_entrega.IdPontoEntrega;
                        novaFoto.NumeroFoto     = foto.NumeroFoto.Trim();
                        novaFoto.DataExclusao   = null;
                        novaFoto.Path           = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], cidade.CidadeDiretorio, Data, User.Identity.Name.ToUpper(), foto.NumeroFoto.Trim().ToUpper());
                        novaFoto.PontoEntrega   = new_ponto_entrega;

                        UnitOfWork.FotoPontoEntregaRepository.Insert(novaFoto);
                    }

                    //Salvando as Alteraçoes
                    UnitOfWork.Save();

                    #endregion
                }

                return(Json(new ResponseView()
                {
                    Status = Status.OK, Result = Resources.Messages.Save_OK
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new ResponseView()
                {
                    Status = Status.NOK, Result = Resources.Messages.Error_Save_Changes
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #22
0
        /// <summary><para>Die Funktion wandelt UTM Koordinaten in geographische Koordinaten (Länge/Breite) 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="utm">Ein <see cref="GeoUtility.GeoSystem.UTM"/>-Objekt.</param>
        /// <returns>Ein <see cref="GeoUtility.GeoSystem.Geographic"/>-Objekt im <see cref="GeoUtility.GeoSystem.Helper.GeoDatum.WGS84">WGS84-Datum</see>.</returns>
        internal Geographic UTMWGS(UTM utm)
        {
            int    zone  = utm.Zone;
            string band  = utm.Band;
            double east  = utm.East;
            double north = utm.North;

            // Koeffizienten zur Berechnung der geographischen Breite aus gegebener Meridianbogenlänge
            double koeff0 = WGS84_POL * (Math.PI / 180) * (1 - 3 * WGS84_EXZENT2 / 4 + 45 * WGS84_EXZENT4 / 64 - 175 * WGS84_EXZENT6 / 256 + 11025 * WGS84_EXZENT8 / 16384);
            double koeff2 = (180 / Math.PI) * (3 * WGS84_EXZENT2 / 8 - 3 * WGS84_EXZENT4 / 16 + 213 * WGS84_EXZENT6 / 2048 - 255 * WGS84_EXZENT8 / 4096);
            double koeff4 = (180 / Math.PI) * (21 * WGS84_EXZENT4 / 256 - 21 * WGS84_EXZENT6 / 256 + 533 * WGS84_EXZENT8 / 8192);
            double koeff6 = (180 / Math.PI) * (151 * WGS84_EXZENT6 / 6144 - 453 * WGS84_EXZENT8 / 12288);

            // Nord-/Süd Halbkugel
            char b = band.ToCharArray()[0];

            if (b < 'N' && band != "")
            {
                north = north - 10E+06;
            }

            // Breite (Rad)
            double sig       = (north / UTM_FAKTOR) / koeff0;
            double sigRad    = sig * Math.PI / 180;
            double fbreite   = sig + koeff2 * Math.Sin(2 * sigRad) + koeff4 * Math.Sin(4 * sigRad) + koeff6 * Math.Sin(6 * sigRad);
            double breiteRad = fbreite * Math.PI / 180;

            double tangens1 = Math.Tan(breiteRad);
            double tangens2 = tangens1 * tangens1;
            double tangens4 = tangens2 * tangens2;
            double cosinus1 = Math.Cos(breiteRad);
            double cosinus2 = cosinus1 * cosinus1;

            double eta = WGS84_EXZENT2 * cosinus2;

            // Querkrümmung
            double qkhm1 = WGS84_POL / Math.Sqrt(1 + eta);
            double qkhm2 = Math.Pow(qkhm1, 2);
            double qkhm3 = Math.Pow(qkhm1, 3);
            double qkhm4 = Math.Pow(qkhm1, 4);
            double qkhm5 = Math.Pow(qkhm1, 5);
            double qkhm6 = Math.Pow(qkhm1, 6);

            // Differenz zum Bezugsmeridian
            double merid    = (zone - 30) * 6 - 3;
            double dlaenge1 = (east - UTM_FALSE_EASTING) / UTM_FAKTOR;
            double dlaenge2 = Math.Pow(dlaenge1, 2);
            double dlaenge3 = Math.Pow(dlaenge1, 3);
            double dlaenge4 = Math.Pow(dlaenge1, 4);
            double dlaenge5 = Math.Pow(dlaenge1, 5);
            double dlaenge6 = Math.Pow(dlaenge1, 6);

            // Faktor für Berechnung Breite
            double bfakt2 = -tangens1 * (1 + eta) / (2 * qkhm2);
            double bfakt4 = tangens1 * (5 + 3 * tangens2 + 6 * eta * (1 - tangens2)) / (24 * qkhm4);
            double bfakt6 = -tangens1 * (61 + 90 * tangens2 + 45 * tangens4) / (720 * qkhm6);

            // Faktor für Berechnung Länge
            double lfakt1 = 1 / (qkhm1 * cosinus1);
            double lfakt3 = -(1 + 2 * tangens2 + eta) / (6 * qkhm3 * cosinus1);
            double lfakt5 = (5 + 28 * tangens2 + 24 * tangens4) / (120 * qkhm5 * cosinus1);

            // Geographische Breite Länge WGS84
            double breite = fbreite + (180 / Math.PI) * (bfakt2 * dlaenge2 + bfakt4 * dlaenge4 + bfakt6 * dlaenge6);
            double laenge = merid + (180 / Math.PI) * (lfakt1 * dlaenge1 + lfakt3 * dlaenge3 + lfakt5 * dlaenge5);

            return(new Geographic(laenge, breite));
        }
예제 #23
0
        public HttpResponseMessage Add(PosteEditAPI Poste)
        {
            /// Validando o Poste
            ICollection <ValidationResult> results;

            if (Poste.TryValidate(out results))
            {
                OrdemDeServico OSBD = UnitOfWork.OrdemDeServicoRepository.Get(os => os.IdOrdemDeServico == Poste.IdOrdemDeServico, includeProperties: "Cidade").FirstOrDefault();
                if (OSBD != null)
                {
                    ConverterLatLonToUtm converter = new ConverterLatLonToUtm(OSBD.Cidade.Datum, OSBD.Cidade.NorteOuSul, OSBD.Cidade.Zona);
                    UTM utmPoste = converter.Convert(Poste.Lat, Poste.Lon);

                    // Salvando a posição do Mobile no momento da Edição do poste
                    UTM posicaoAtualizacao = converter.Convert(Poste.LatAtualizacao, Poste.LonAtualizacao);

                    Poste posteAux = new Poste()
                    {
                        X              = utmPoste.X,
                        Y              = utmPoste.Y,
                        XAtualizacao   = posicaoAtualizacao.X,
                        YAtualizacao   = posicaoAtualizacao.Y,
                        OrdemDeServico = OSBD,
                        DataCadastro   = DateTime.Now,
                        Cidade         = OSBD.Cidade,
                        Altura         = Poste.Altura,
                        TipoPoste      = Poste.TipoPoste,
                        Esforco        = Poste.Esforco,
                        Descricao      = Poste.Descricao
                    };

                    UnitOfWork.PosteRepository.Insert(posteAux);

                    /// usuario
                    Usuario User = UnitOfWork.UsuarioRepository.Get(u => u.IdUsuario == IdUsuario).FirstOrDefault();

                    if (Poste.Fotos != null && Poste.Fotos.Count > 0)
                    {
                        foreach (FotoAPI foto in Poste.Fotos)
                        {
                            if (foto != null)
                            {
                                DateTime DataDiretorio = Convert.ToDateTime(foto.DataFoto); //ConvertDate.UnixTimestampToDateTime(foto.DataFoto);
                                String   Data          = DataDiretorio.ToString("dd-MM-yyyy hh:mm:ss");

                                UnitOfWork.FotoPosteRepository.Insert(new FotoPoste
                                {
                                    CodigoGeoBD = -1,
                                    IdPoste     = posteAux.IdPoste,
                                    NumeroFoto  = foto.NumeroFoto.Trim(),
                                    DataFoto    = DataDiretorio,
                                    Path        = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], OSBD.Cidade.CidadeDiretorio, Data, User.UserName.ToUpper(), foto.NumeroFoto.Trim())
                                });
                            }
                        }
                    }

                    UnitOfWork.Save();

                    List <FotoAPI> FotosApi = new List <FotoAPI>();

                    foreach (FotoPoste foto in posteAux.Fotos.Where(f => f.DataExclusao == null))
                    {
                        FotoAPI ft = new FotoAPI();
                        ft.NumeroFoto = foto.NumeroFoto;
                        ft.DataFoto   = foto.DataFoto.ToString("dd-MM-yyyy hh:mm:ss"); //ConvertDate.DateTimeToUnixTimestamp(foto.DataFoto);
                        FotosApi.Add(ft);
                    }

                    ConverterUtmToLatLon converterToLatLong = new ConverterUtmToLatLon(posteAux.Cidade.Datum, posteAux.Cidade.NorteOuSul, posteAux.Cidade.Zona);
                    return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                    {
                        Status = Status.OK,
                        Message = Resources.Messages.Save_OK,
                        Results = new
                        {
                            IdPoste = posteAux.IdPoste,
                            Posicao = converterToLatLong.Convert(posteAux.X, posteAux.Y),
                            DataCadastro = posteAux.DataCadastro,
                            DataExclusao = posteAux.DataExclusao,
                            Finalizado = posteAux.Finalizado,
                            CodigoGeo = posteAux.CodigoGeo,
                            IdLogradouro = posteAux.IdLogradouro,
                            IdCidade = posteAux.Cidade.IdCidade,
                            IdOrdemDeServico = posteAux.IdOrdemDeServico,
                            Fotos = FotosApi,
                            Altura = posteAux.Altura,
                            TipoPoste = posteAux.TipoPoste,
                            Esforco = posteAux.Esforco,
                            Descricao = posteAux.Descricao
                        }
                    }));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                    {
                        Status = Status.NOK, Message = Resources.Messages.OS_Not_Found
                    }));
                }
            }
            else
            {
                string MessageValidate = string.Empty;
                foreach (var validationResult in results)
                {
                    MessageValidate += validationResult.ErrorMessage;
                }
                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                {
                    Status = Status.NOK, Message = MessageValidate
                }));
            }
        }
예제 #24
0
        public static DD UTM2DD(UTM utm)
        {
            var Convert = new ConversionUTM2DD();

            return(Convert.Convert(utm));
        }
예제 #25
0
파일: MGRS.cs 프로젝트: andrewgbuck/GPV
    public override void ToGeodetic(string gridValue, out double lon, out double lat)
    {
        gridValue = gridValue.Replace(" ", String.Empty).ToUpper();

        if (gridValue.Length < 6)
        {
            throw new ArgumentException("Grid value is too short");
        }

        if (!Char.IsNumber(gridValue[0]))
        {
            throw new ArgumentException("Grid value does not start with a zone number");
        }

        int i = 0;

        if (Char.IsNumber(gridValue[i + 1]))
        {
            ++i;
        }

        int zone = Convert.ToInt32(gridValue.Substring(0, i + 1));

        if (zone < 1 || 60 < zone)
        {
            throw new ArgumentException("Invalid zone number, must be between 1 and 60");
        }

        int zoneIndex = _zoneLetters.IndexOf(gridValue[++i]);

        if (zoneIndex < 0)
        {
            throw new ArgumentException("Invalid zone letter");
        }

        int setNumber   = (zone - 1) % 6;
        int columnIndex = _columnLetters.IndexOf(gridValue[++i]) - (setNumber % 3) * 8;

        if (columnIndex < 0 || 8 < columnIndex)
        {
            throw new ArgumentException("Invalid column letter");
        }

        int rowIndex = _rowLetters.IndexOf(gridValue[++i]);

        if (rowIndex < 0)
        {
            throw new ArgumentException("Invalid row letter");
        }

        char[] letters = gridValue.Substring(i - 2, 3).ToCharArray();

        for (int j = ++i; j < gridValue.Length; ++j)
        {
            if (!Char.IsNumber(gridValue[j]))
            {
                throw new ArgumentException("Invalid coordinates, contains non-numeric character");
            }
        }

        int coordLength = gridValue.Length - i;

        if (coordLength % 2 == 1)
        {
            throw new ArgumentException("Invalid coordinates, X and Y are of unequal length");
        }

        if (coordLength > 10)
        {
            throw new ArgumentException("Invalid coordinates, too long");
        }

        coordLength /= 2;
        double factor = Math.Pow(10, 5 - coordLength);

        double x = Convert.ToDouble(gridValue.Substring(i, coordLength));
        double y = Convert.ToDouble(gridValue.Substring(i + coordLength, coordLength));

        x += (columnIndex + 1) * 100000;

        int yOffset = setNumber % 2 == 1 ? 1500000 : 0;

        y = (rowIndex * 100000 + yOffset + y) % 2000000;

        double minZoneNorthing = zoneIndex < 10 ? (zoneIndex + 1) * 900000 : (zoneIndex % 10) * 900000;

        while (y < minZoneNorthing)
        {
            y += 2000000;
        }

        Hemisphere hemisphere = letters[0] > 'M' ? Hemisphere.North : Hemisphere.South;
        UTM        utm        = new UTM(zone, hemisphere);

        utm.ToGeodetic(x, y, out lon, out lat);
    }
예제 #26
0
        public ActionResult CriarOsPeloSite(string[] latlons, string[] PostesSelecionados, string[] StrandsSelecionados, int IdCidade, string NomeOrdem, string IdUsuario, SituacaoOrdemServico Situacao, string Observacao)
        {
            ConverterLatLonToUtm converter = null;
            var cidade = UnitOfWork.CidadeRepository.Get(id => id.IdCidade == IdCidade).FirstOrDefault();

            if (cidade != null)
            {
                converter = new ConverterLatLonToUtm(cidade.Datum, cidade.NorteOuSul, cidade.Zona);
            }


            OrdemDeServico OrdemDeServico = new OrdemDeServico()
            {
                IdCidade   = IdCidade,
                IdUsuario  = IdUsuario,
                Observacao = Observacao,
                NumeroOS   = NomeOrdem,
                Situacao   = Situacao,
                DataInicio = DateTime.Now
            };

            UnitOfWork.OrdemDeServicoRepository.Insert(OrdemDeServico);
            UnitOfWork.Save();

            if (PostesSelecionados != null)
            {
                for (int i = 0; i < PostesSelecionados.Length; i++)
                {
                    long idP = Convert.ToInt64(PostesSelecionados[i]);

                    //Realoca Poste para nova OS
                    var posteselect = UnitOfWork.PosteRepository.Get(id => id.IdPoste == idP).FirstOrDefault();
                    if (posteselect != null)
                    {
                        posteselect.IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico;
                    }

                    //Realoca Poste para nova OS
                    var demanda = UnitOfWork.PontoEntregaRepository.Get(id => id.IdPoste == idP).ToList();
                    foreach (var item in demanda)
                    {
                        item.IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico;
                    }

                    //Realoca VaosDemandas para nova OS
                    var vao = UnitOfWork.VaosDemandaPosteRepository.Get(id => id.IdPoste == idP).ToList();
                    foreach (var item in vao)
                    {
                        item.IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico;
                    }

                    //    (vao != null)
                    //{
                    //    vao.IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico;
                    //}
                }
                UnitOfWork.Save();
            }

            if (StrandsSelecionados != null)
            {
                for (int i = 0; i < StrandsSelecionados.Length; i++)
                {
                    long idS          = Convert.ToInt64(StrandsSelecionados[i]);
                    var  strandSelect = UnitOfWork.DemandaStrandRepository.Get(id => id.ID == idS).FirstOrDefault();
                    if (strandSelect != null)
                    {
                        strandSelect.IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico;
                    }
                }
                UnitOfWork.Save();
            }


            int           ordem    = -1;
            List <string> latlongs = new List <string>();
            bool          pode     = false;

            double latInicio = 0, lonInicio = 0;
            double latPrimo = 0, lonPrimo = 0;

            List <double> lates = new List <double>();

            for (int i = 0; i < latlons.Length; i++)
            {
                var x1y1 = latlons[i].Replace("(", "").Replace(")", "").Replace(" ", "").Split(',');
                for (int x = 0; x < x1y1.Length; x++)
                {
                    double lastlons = Double.Parse(x1y1[x], System.Globalization.CultureInfo.InvariantCulture);
                    // Console.WriteLine(lastlons.ToString(new System.Globalization.CultureInfo("en-US", true)));
                    lates.Add(lastlons);
                }
            }
            int    con = lates.Count();
            int    contadorFiel = con;
            int    contador = 0;
            double latitude1 = 0, longitude1 = 0, latitude2 = 0, longitude2 = 0;

            for (int d = 0; d <= con; d++)
            {
                if (lonInicio == 0)
                {
                    if (contador == 3)
                    {
                        longitude2 = lates[d];
                        contador++;
                        pode     = true;
                        contador = 5;
                    }

                    if (contador == 2)
                    {
                        latitude2 = lates[d];
                        contador++;
                    }

                    if (contador == 1)
                    {
                        longitude1 = lates[d];
                        contador++;
                    }

                    if (contador == 0)
                    {
                        latitude1 = lates[d];
                        contador++;
                    }
                }
                else
                {
                    if (contadorFiel > d)
                    {
                        bool sovai = false;
                        if (contador == 1)
                        {
                            longitude1 = lates[d];
                            contador++;
                            pode  = false;
                            sovai = true;
                        }

                        if (contador == 0)
                        {
                            latitude1 = lates[d];
                            contador++;
                        }
                        if (sovai)
                        {
                            UTM lonIni = converter.Convert(latInicio, lonInicio);
                            UTM latvem = converter.Convert(latitude1, longitude1);
                            ordem++;
                            PoligonoOS PoligonoOS = new PoligonoOS()
                            {
                                IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico,
                                Ordem            = ordem,
                                X1 = latInicio,
                                Y1 = lonInicio,
                                X2 = latvem.X,
                                Y2 = latvem.Y,
                            };
                            UnitOfWork.PoligonoOSRepository.Insert(PoligonoOS);
                            UnitOfWork.Save();

                            latInicio = latvem.X;
                            lonInicio = latvem.Y;
                            contador  = 0;
                        }
                    }
                    else
                    {
                        ordem++;
                        PoligonoOS PoligonoOS = new PoligonoOS()
                        {
                            IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico,
                            Ordem            = ordem,
                            X1 = latInicio,
                            Y1 = lonInicio,
                            X2 = latPrimo,
                            Y2 = lonPrimo
                        };
                        UnitOfWork.PoligonoOSRepository.Insert(PoligonoOS);
                        UnitOfWork.Save();
                    }
                }

                if (pode)
                {
                    UTM xy1 = converter.Convert(latitude1, longitude1);
                    UTM xy2 = converter.Convert(latitude2, longitude2);

                    if (latInicio == 0)
                    {
                        ordem++;
                        PoligonoOS PoligonoOS = new PoligonoOS()
                        {
                            IdOrdemDeServico = OrdemDeServico.IdOrdemDeServico,
                            Ordem            = ordem,
                            X1 = xy1.X,
                            Y1 = xy1.Y,
                            X2 = xy2.X,
                            Y2 = xy2.Y,
                        };
                        UnitOfWork.PoligonoOSRepository.Insert(PoligonoOS);
                        UnitOfWork.Save();
                    }
                    latInicio = xy2.X;
                    lonInicio = xy2.Y;
                    contador  = 0;
                    pode      = false;
                    if (lonPrimo == 0)
                    {
                        latPrimo = xy1.X;
                        lonPrimo = xy1.Y;
                    }
                }
            }

            OrdemDeServico OrdemBd = UnitOfWork.OrdemDeServicoRepository.Get(or => or.IdOrdemDeServico == OrdemDeServico.IdOrdemDeServico).FirstOrDefault();

            //OrdemServicoView OrdemServicoView = new OrdemServicoView().GetOSByNum(OrdemBd);

            //   return Json(new {Ordem = new OrdemServicoView().GetOSByNum(OrdemBd)}, JsonRequestBehavior.AllowGet);
            return(Json(new ResponseView()
            {
                Status = Status.OK, Result = Resources.Messages.Save_OK
            }, JsonRequestBehavior.AllowGet));
        }
예제 #27
0
 private static WGS84LatLongPoint UTMtoLL(double UTMNorthing, double UTMEasting, int UTMZoneNumber, Geocentric.Hemisphere pHemisphere)
 {
     UTM mgrs = new UTM(UTMZoneNumber, UTMEasting, UTMNorthing, pHemisphere);
     Geographic geo = (Geographic)mgrs;
     return WGS84LatLongPoint.Create(geo.Latitude, geo.Longitude);
 }
        /// <summary><para>Die Funktion wandelt zivile UTM Koordinaten in militärische 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="utm">Ein <see cref="GeoUtility.GeoSystem.UTM"/>-Objekt.</param>
        /// <returns>Ein <see cref="GeoUtility.GeoSystem.MGRS"/>-Objekt (UTMREF/MGRS).</returns>
        internal MGRS UTMMGR(UTM utm)
        {

            int zone = utm.Zone;
            string band = utm.Band;
            char cz2 = band.ToCharArray()[0];
            char[] sep = { ',', '.' };

            // Die höchsten Stellen der East und North Koordinate werden für die Berechnung des Planquadrates benötigt.
            string e = utm.EastString.Split(sep)[0];
            int east_plan = int.Parse(e.Substring(0, 1));   // 1. Stelle des Ostwertes
            string n = utm.NorthString.Split(sep)[0];
            int north_plan = int.Parse(n.Substring(0, 2));  // 1. und 2. Stelle des Nordwertes
            
            // East Koordinate
            string east = ((int)Math.Round(utm.East)).ToString();
            if (east.Length > 2) east = east.Remove(0, 1);

            // North Koordinate
            string north = ((int)Math.Round(utm.North)).ToString();
            if (north.Length > 2) north = north.Remove(0, 2);

            // Anzahl Stellen bei East und North müssen gleich sein
            if (east.Length < north.Length)
            {
                east = east.PadLeft(north.Length, '0');
            }
            else if (north.Length < east.Length)
            {
                north = north.PadLeft(east.Length, '0');
            }

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

            // Berechnung des Indexes für die Ost-Planquadrat Komponente
            int eastgrid = 0;
            int i = zone % 3;
            if (i == 1) eastgrid = east_plan - 1;
            if (i == 2) eastgrid = east_plan + 7;
            if (i == 0) eastgrid = east_plan + 15;

            // Berechnung des Indexes für die Nord-Planquadrat Komponente
            int northgrid = 0;
            i = zone % 2;
            if (i != 1) northgrid = 5; 
            i = north_plan;
            while (i - 20 >= 0) 
            { 
                i = i - 20; 
            }
            northgrid += i;
            if (northgrid > 19) northgrid = northgrid - 20;

            // Planquadrat aus den vorher berechneten Indizes zusammensetzen
            string plan = MGRS_EAST.Substring(eastgrid, 1) + MGRS_NORTH1.Substring(northgrid, 1);

            return new MGRS(utm.Zone, utm.Band, plan, double.Parse(east), double.Parse(north));
        }
예제 #29
0
        public HttpResponseMessage Edit(PosteEditAPI Poste)
        {
            /// Validando o Poste
            ICollection <ValidationResult> results;

            if (Poste.TryValidate(out results))
            {
                Poste posteBD = UnitOfWork.PosteRepository.Get(p => p.IdPoste == Poste.IdPoste && p.DataExclusao == null, includeProperties: "Cidade,Fotos,OrdemDeServico").FirstOrDefault();
                if (posteBD != null)
                {
                    ConverterLatLonToUtm converter = new ConverterLatLonToUtm(posteBD.Cidade.Datum, posteBD.Cidade.NorteOuSul, posteBD.Cidade.Zona);
                    UTM utmPoste = converter.Convert(Poste.Lat, Poste.Lon);

                    //Atribuindo os novos valores da Edicao
                    posteBD.X          = utmPoste.X;
                    posteBD.Y          = utmPoste.Y;
                    posteBD.Finalizado = Poste.Finalizado;
                    posteBD.Altura     = Poste.Altura;
                    posteBD.TipoPoste  = Poste.TipoPoste;
                    posteBD.Esforco    = Poste.Esforco != null ? Poste.Esforco : 0;
                    posteBD.Descricao  = Poste.Descricao != null?Poste.Descricao.ToUpper() : "";

                    posteBD.DataCadastro = ConvertDate.UnixTimestampToDateTime(Poste.DataAtualizacao);

                    // Salvando a posição do Mobile no momento da Edição do poste
                    UTM posicaoAtualizacao = converter.Convert(Poste.LatAtualizacao, Poste.LonAtualizacao);
                    posteBD.XAtualizacao = posicaoAtualizacao.X;
                    posteBD.YAtualizacao = posicaoAtualizacao.Y;

                    UnitOfWork.PosteRepository.Update(posteBD);

                    /// Setando DataDeExclusao em todas as fotos
                    foreach (FotoPoste f in posteBD.Fotos)
                    {
                        f.DataExclusao = DateTime.Now;
                        UnitOfWork.FotoPosteRepository.Update(f);
                    }

                    /// usuario
                    Usuario User = UnitOfWork.UsuarioRepository.Get(u => u.IdUsuario == IdUsuario).FirstOrDefault();

                    // Verificando as alterações das fotos
                    if (Poste.Fotos != null && Poste.Fotos.Count > 0)
                    {
                        foreach (FotoAPI foto in Poste.Fotos)
                        {
                            if (foto != null)
                            {
                                DateTime DataDiretorio = Convert.ToDateTime(foto.DataFoto);  //ConvertDate.UnixTimestampToDateTime(foto.DataFoto);
                                String   Data          = DataDiretorio.ToString("dd-MM-yyyy hh:mm:ss");

                                FotoPoste f = UnitOfWork.FotoPosteRepository.Get(fto => fto.IdPoste == posteBD.IdPoste && fto.NumeroFoto.Trim() == foto.NumeroFoto.Trim()).FirstOrDefault();
                                if (f != null)
                                {
                                    f.DataExclusao = null;
                                    f.DataFoto     = DataDiretorio;
                                    f.Path         = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], posteBD.Cidade.CidadeDiretorio, Data, User.UserName.ToUpper(), foto.NumeroFoto.Trim());
                                    UnitOfWork.FotoPosteRepository.Update(f);
                                }
                                else
                                {
                                    FotoPoste fAux = new FotoPoste
                                    {
                                        CodigoGeoBD = -1,
                                        IdPoste     = posteBD.IdPoste,
                                        NumeroFoto  = foto.NumeroFoto.Trim(),
                                        DataFoto    = DataDiretorio,
                                        Path        = string.Format(ConfigurationManager.AppSettings["NewPathFotos"], posteBD.Cidade.CidadeDiretorio, Data, User.UserName.ToUpper(), foto.NumeroFoto.Trim())
                                    };

                                    UnitOfWork.FotoPosteRepository.Insert(fAux);
                                }
                            }
                        }
                    }

                    UnitOfWork.Save(); //Commit

                    List <FotoAPI> FotosApi = new List <FotoAPI>();

                    foreach (FotoPoste foto in posteBD.Fotos.Where(f => f.DataExclusao == null))
                    {
                        FotoAPI ft = new FotoAPI();
                        ft.NumeroFoto = foto.NumeroFoto;
                        ft.DataFoto   = foto.DataFoto.ToString("dd-MM-yyyy hh:mm:ss"); //ConvertDate.DateTimeToUnixTimestamp(foto.DataFoto);
                        FotosApi.Add(ft);
                    }

                    ConverterUtmToLatLon converterToLatLong = new ConverterUtmToLatLon(posteBD.Cidade.Datum, posteBD.Cidade.NorteOuSul, posteBD.Cidade.Zona);
                    return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                    {
                        Status = Status.OK,
                        Message = Resources.Messages.Save_OK,
                        Results = new
                        {
                            IdPoste = posteBD.IdPoste,
                            Posicao = converterToLatLong.Convert(posteBD.X, posteBD.Y),
                            DataCadastro = posteBD.DataCadastro,
                            DataExclusao = posteBD.DataExclusao,
                            Finalizado = posteBD.Finalizado,
                            CodigoGeo = posteBD.CodigoGeo,
                            IdLogradouro = posteBD.IdLogradouro,
                            IdCidade = posteBD.Cidade.IdCidade,
                            IdOrdemDeServico = posteBD.IdOrdemDeServico,
                            Fotos = FotosApi,
                            Altura = posteBD.Altura,
                            TipoPoste = posteBD.TipoPoste,
                            Esforco = posteBD.Esforco,
                            Descricao = posteBD.Descricao
                        }
                    }));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                    {
                        Status = Status.NOK, Message = Resources.Messages.Poste_Not_Found
                    }));
                }
            }
            else
            {
                string MessageValidate = string.Empty;
                foreach (var validationResult in results)
                {
                    MessageValidate += validationResult.ErrorMessage + "-";
                }
                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseApi()
                {
                    Status = Status.NOK, Message = MessageValidate.Remove(MessageValidate.Length - 1)
                }));
            }
        }
예제 #30
0
        /// <summary><para>Die Funktion wandelt UTM Koordinaten in geographische Koordinaten (Länge/Breite) 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="utm">Ein <see cref="GeoUtility.GeoSystem.UTM"/>-Objekt.</param>
        /// <returns>Ein <see cref="GeoUtility.GeoSystem.Geographic"/>-Objekt im <see cref="GeoUtility.GeoSystem.Helper.GeoDatum.WGS84">WGS84-Datum</see>.</returns>
        internal Geographic UTMWGS(UTM utm)
        {

            int zone = utm.Zone;
            string band = utm.Band;
            double east = utm.East;
            double north = utm.North;

            // Koeffizienten zur Berechnung der geographischen Breite aus gegebener Meridianbogenlänge
            double koeff0 = WGS84_POL * (Math.PI / 180) * (1 - 3 * WGS84_EXZENT2 / 4 + 45 * WGS84_EXZENT4 / 64 - 175 * WGS84_EXZENT6 / 256 + 11025 * WGS84_EXZENT8 / 16384);
            double koeff2 = (180 / Math.PI) * (3 * WGS84_EXZENT2 / 8 - 3 * WGS84_EXZENT4 / 16 + 213 * WGS84_EXZENT6 / 2048 - 255 * WGS84_EXZENT8 / 4096);
            double koeff4 = (180 / Math.PI) * (21 * WGS84_EXZENT4 / 256 - 21 * WGS84_EXZENT6 / 256 + 533 * WGS84_EXZENT8 / 8192);
            double koeff6 = (180 / Math.PI) * (151 * WGS84_EXZENT6 / 6144 - 453 * WGS84_EXZENT8 / 12288);

            // Nord-/Süd Halbkugel
            char b = band.ToCharArray()[0];
            if (b < 'N' && band != "")
            {
                north = north - 10E+06;
            }

            // Breite (Rad)
            double sig = (north / UTM_FAKTOR) / koeff0;
            double sigRad = sig * Math.PI / 180;
            double fbreite = sig + koeff2 * Math.Sin(2 * sigRad) + koeff4 * Math.Sin(4 * sigRad) + koeff6 * Math.Sin(6 * sigRad);
            double breiteRad = fbreite * Math.PI / 180;

            double tangens1 = Math.Tan(breiteRad);
            double tangens2 = tangens1 * tangens1;
            double tangens4 = tangens2 * tangens2;
            double cosinus1 = Math.Cos(breiteRad);
            double cosinus2 = cosinus1 * cosinus1;

            double eta = WGS84_EXZENT2 * cosinus2;

            // Querkrümmung
            double qkhm1 = WGS84_POL / Math.Sqrt(1 + eta);
            double qkhm2 = Math.Pow(qkhm1, 2);
            double qkhm3 = Math.Pow(qkhm1, 3);
            double qkhm4 = Math.Pow(qkhm1, 4);
            double qkhm5 = Math.Pow(qkhm1, 5);
            double qkhm6 = Math.Pow(qkhm1, 6);

            // Differenz zum Bezugsmeridian
            double merid = (zone - 30) * 6 - 3;
            double dlaenge1 = (east - UTM_FALSE_EASTING) / UTM_FAKTOR;
            double dlaenge2 = Math.Pow(dlaenge1, 2);
            double dlaenge3 = Math.Pow(dlaenge1, 3);
            double dlaenge4 = Math.Pow(dlaenge1, 4);
            double dlaenge5 = Math.Pow(dlaenge1, 5);
            double dlaenge6 = Math.Pow(dlaenge1, 6);

            // Faktor für Berechnung Breite
            double bfakt2 = -tangens1 * (1 + eta) / (2 * qkhm2);
            double bfakt4 = tangens1 * (5 + 3 * tangens2 + 6 * eta * (1 - tangens2)) / (24 * qkhm4);
            double bfakt6 = -tangens1 * (61 + 90 * tangens2 + 45 * tangens4) / (720 * qkhm6);

            // Faktor für Berechnung Länge
            double lfakt1 = 1 / (qkhm1 * cosinus1);
            double lfakt3 = -(1 + 2 * tangens2 + eta) / (6 * qkhm3 * cosinus1);
            double lfakt5 = (5 + 28 * tangens2 + 24 * tangens4) / (120 * qkhm5 * cosinus1);

            // Geographische Breite Länge WGS84
            double breite = fbreite + (180 / Math.PI) * (bfakt2 * dlaenge2 + bfakt4 * dlaenge4 + bfakt6 * dlaenge6);
            double laenge = merid + (180 / Math.PI) * (lfakt1 * dlaenge1 + lfakt3 * dlaenge3 + lfakt5 * dlaenge5);

            return new Geographic(laenge, breite);
        }
예제 #31
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 { }
            }
        }
예제 #32
0
 public static DD UTM2DD(UTM utm)
 {
     var Convert = new ConversionUTM2DD();
     return Convert.Convert(utm);
 }
예제 #33
0
        /// <summary><para>Die Funktion wandelt zivile UTM Koordinaten in militärische 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="utm">Ein <see cref="GeoUtility.GeoSystem.UTM"/>-Objekt.</param>
        /// <returns>Ein <see cref="GeoUtility.GeoSystem.MGRS"/>-Objekt (UTMREF/MGRS).</returns>
        internal MGRS UTMMGR(UTM utm)
        {
            int    zone = utm.Zone;
            string band = utm.Band;
            char   cz2  = band.ToCharArray()[0];

            char[] sep = { ',', '.' };

            // Die höchsten Stellen der East und North Koordinate werden für die Berechnung des Planquadrates benötigt.
            string e          = utm.EastString.Split(sep)[0];
            int    east_plan  = int.Parse(e.Substring(0, 1)); // 1. Stelle des Ostwertes
            string n          = utm.NorthString.Split(sep)[0];
            int    north_plan = int.Parse(n.Substring(0, 2)); // 1. und 2. Stelle des Nordwertes

            // East Koordinate
            string east = ((int)Math.Round(utm.East)).ToString();

            if (east.Length > 2)
            {
                east = east.Remove(0, 1);
            }

            // North Koordinate
            string north = ((int)Math.Round(utm.North)).ToString();

            if (north.Length > 2)
            {
                north = north.Remove(0, 2);
            }

            // Anzahl Stellen bei East und North müssen gleich sein
            if (east.Length < north.Length)
            {
                east = east.PadLeft(north.Length, '0');
            }
            else if (north.Length < east.Length)
            {
                north = north.PadLeft(east.Length, '0');
            }

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

            // Berechnung des Indexes für die Ost-Planquadrat Komponente
            int eastgrid = 0;
            int i        = zone % 3;

            if (i == 1)
            {
                eastgrid = east_plan - 1;
            }
            if (i == 2)
            {
                eastgrid = east_plan + 7;
            }
            if (i == 0)
            {
                eastgrid = east_plan + 15;
            }

            // Berechnung des Indexes für die Nord-Planquadrat Komponente
            int northgrid = 0;

            i = zone % 2;
            if (i != 1)
            {
                northgrid = 5;
            }
            i = north_plan;
            while (i - 20 >= 0)
            {
                i = i - 20;
            }
            northgrid += i;
            if (northgrid > 19)
            {
                northgrid = northgrid - 20;
            }

            // Planquadrat aus den vorher berechneten Indizes zusammensetzen
            string plan = MGRS_EAST.Substring(eastgrid, 1) + MGRS_NORTH1.Substring(northgrid, 1);

            return(new MGRS(utm.Zone, utm.Band, plan, double.Parse(east), double.Parse(north)));
        }
예제 #34
0
 public UTMHandler(ISession client, ChatCommandBase cmd) : base(client, cmd)
 {
     _cmd = (UTM)cmd;
 }
예제 #35
0
        private void OnTripStatus(object parm)
        {
            Debug.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss.fff"), "OnTripStatus"));

            RoutePatternConfig configRP = null;
            ServiceAlertConfig configSA = null;
            VehicleConfig      configV  = null;

            Interlocked.Exchange <RoutePatternConfig>(ref configRP, m_configRP);
            Interlocked.Exchange <ServiceAlertConfig>(ref configSA, m_configSA);
            Interlocked.Exchange <VehicleConfig>(ref configV, m_configV);

            bool       bContinue = true, bDispose = false;
            Trip       trip = null;
            TripStatus ts = (TripStatus)parm;
            Timeout    timeoutFix = new Timeout(TimeSpan.FromMinutes(2)), timeoutOnRoute = new Timeout(TimeSpan.FromSeconds(500));

            do
            {
                if (ts != null)
                {
                    if (ts.NoTrip)
                    {
                        trip = null;
                    }
                    else if (!ts.OffRoute)
                    {
                        timeoutOnRoute.Reset();
                        if (trip == null || ts.RouteTag != trip.RouteTag || ts.RP < trip.RP || ts.TripNo != trip.TripNo || ts.ServiceStart != trip.ServiceStart)
                        {
                            trip = Trip.Create(this, ts.RouteTag, ts.RP, ts.TripNo, ts.ServiceStart, m_configRP, m_configSA, m_configV, m_fFerry);
                        }
                        else
                        {
                            trip.ProgressRP(ts.RP);
                        }

                        EnableSignalPriority(ts.SignalPriority);
                    }
                    else if (trip != null)
                    {
                        trip.OffRoute = true;
                        EnableSignalPriority(false);
                    }
                }

                if (trip != null)
                {
                    GPSFix fix = m_Fix;

                    bool bEndTrip = false;
                    if (timeoutOnRoute.HasExpired)
                    {
                        bEndTrip = true;
                    }
                    else if (fix == null || !UTM.IsValidLL4Zone(configV.UTMZoneNo, configV.UTMZoneLetter, fix.Lat, fix.Long))
                    {
                        bEndTrip = timeoutFix.HasExpired;
                    }
                    else
                    {
                        timeoutFix.Reset();
                        //if( m_fFerry || !trip.OffRoute )
                        //	bEndTrip = !trip.UpdatePosition( UTM.LL2UTM( configV.UTMZoneNo, fix.Lat, fix.Long ), fix.Speed, fix.SpeedWeighted );
                    }

                    if (bEndTrip)
                    {
                        trip = null;
                    }
                    else
                    {
                        Thread.Sleep(999);
                    }
                }

                lock ( m_qTS )
                {
                    if (m_qTS.Count == 0)
                    {
                        ts = null;
                    }
                    else
                    {
                        ts = m_qTS.Dequeue();
                        if (ts == null)
                        {
                            bDispose = true;
                        }
                    }

                    if (bDispose || (trip == null && ts == null))
                    {
                        bContinue = m_bTSThreadPoolActive = false;
                    }
                }
            }while(bContinue);

            if (!bDispose)
            {
                QueueRequest(new RequestEventArgs(RequestType.DisplayNextStop, null));
                QueueRequest(new RequestEventArgs(RequestType.DisplayNextStopExtra, null));
                if (configV.HeadSignDefault != null)
                {
                    QueueRequest(new RequestEventArgs(RequestType.HeadSign, configV.HeadSignDefault));
                }
                EnableSignalPriority(false);
            }
        }
예제 #36
-1
파일: MGRS.cs 프로젝트: ClaireBrill/GPV
	public override void ToGeodetic(string gridValue, out double lon, out double lat)
	{
		gridValue = gridValue.Replace(" ", String.Empty).ToUpper();

		if (gridValue.Length < 6)
		{
			throw new ArgumentException("Grid value is too short");
		}

		if (!Char.IsNumber(gridValue[0]))
		{
			throw new ArgumentException("Grid value does not start with a zone number");
		}

		int i = 0;

		if (Char.IsNumber(gridValue[i + 1]))
		{
			++i;
		}

		int zone = Convert.ToInt32(gridValue.Substring(0, i + 1));

		if (zone < 1 || 60 < zone)
		{
			throw new ArgumentException("Invalid zone number, must be between 1 and 60");
		}

		int zoneIndex = _zoneLetters.IndexOf(gridValue[++i]);

		if (zoneIndex < 0)
		{
			throw new ArgumentException("Invalid zone letter");
		}

		int setNumber = (zone - 1) % 6;
		int columnIndex = _columnLetters.IndexOf(gridValue[++i]) - (setNumber % 3) * 8;

		if (columnIndex < 0 || 8 < columnIndex)
		{
			throw new ArgumentException("Invalid column letter");
		}

		int rowIndex = _rowLetters.IndexOf(gridValue[++i]);

		if (rowIndex < 0)
		{
			throw new ArgumentException("Invalid row letter");
		}

		char[] letters = gridValue.Substring(i - 2, 3).ToCharArray();

		for (int j = ++i; j < gridValue.Length; ++j)
		{
			if (!Char.IsNumber(gridValue[j]))
			{
				throw new ArgumentException("Invalid coordinates, contains non-numeric character");
			}
		}

		int coordLength = gridValue.Length - i;

		if (coordLength % 2 == 1)
		{
			throw new ArgumentException("Invalid coordinates, X and Y are of unequal length");
		}

		if (coordLength > 10)
		{
			throw new ArgumentException("Invalid coordinates, too long");
		}

		coordLength /= 2;
		double factor = Math.Pow(10, 5 - coordLength);

		double x = Convert.ToDouble(gridValue.Substring(i, coordLength));
		double y = Convert.ToDouble(gridValue.Substring(i + coordLength, coordLength));

		x += (columnIndex + 1) * 100000;

		int yOffset = setNumber % 2 == 1 ? 1500000 : 0;
		y = (rowIndex * 100000 + yOffset + y) % 2000000;

		double minZoneNorthing = zoneIndex < 10 ? (zoneIndex + 1) * 900000 : (zoneIndex % 10) * 900000;

		while (y < minZoneNorthing)
		{
			y += 2000000;
		}

		Hemisphere hemisphere = letters[0] > 'M' ? Hemisphere.North : Hemisphere.South;
		UTM utm = new UTM(zone, hemisphere);
		utm.ToGeodetic(x, y, out lon, out lat);
	}