private void CalculateRouteStep(Route route)
        {
            if (route.ArrivedToDestination)
            {
                return;
            }

            double maxStepDistance = Settings.UserSpeed * _updateInterval.TotalHours;

            Geoposition origin      = route.CurrentPosition;
            Geoposition destination = route.NextPosition;

            double pendingDistanceToDestination = GeoCodeCalc.CalcDistance(origin.Latitude, origin.Longitude, destination.Latitude, destination.Longitude);

            if (pendingDistanceToDestination < maxStepDistance)
            {
                // when distance to next point is lower than expected step, simply jump to next point
                route.MoveToNextPosition();
            }
            else
            {
                double distanceProportion = 2 * maxStepDistance / pendingDistanceToDestination;
                double latDiff            = destination.Latitude - origin.Latitude;
                double lonDiff            = destination.Longitude - origin.Longitude;

                var nextGeoposition = new Geoposition
                {
                    Latitude  = origin.Latitude + (latDiff * distanceProportion),
                    Longitude = origin.Longitude + (lonDiff * distanceProportion)
                };

                route.MoveToPosition(nextGeoposition);
            }
        }
Beispiel #2
0
        public int SearchByNeartsRoom(int userid)
        {
            var user      = _db.Member.Where(x => x.UserId == userid).FirstOrDefault();
            var ChatRooms = _db.ChatRoom.ToList();

            int result = 0;

            foreach (var item in ChatRooms)
            {
                int Distanes = (int)Math.Round(GeoCodeCalc.CalcDistance(new LocationM()
                {
                    X = user.X, Y = user.Y
                }, item.Location, GeoCodeCalcMeasurement.Kilometers));

                if (Distanes <= 10 && Distanes >= 0)
                {
                    result = item.id;
                    break;
                }
            }



            return(result);
        }
Beispiel #3
0
        public async Task <IActionResult> Get(double lat, double lng, double radius = 10, double popularity = 0, string categories = "")
        {
            try
            {
                var attractions = await _attractionRepository.GetAttractions(lat, lng, radius, Convert.ToInt32(popularity));

                var result = new List <Attraction>();
                foreach (var attraction in attractions)
                {
                    if (GeoCodeCalc.CalcDistance(lat, lng, attraction.lat, attraction.lng) > radius)
                    {
                        continue;
                    }
                    if (attraction.reviews < popularity)
                    {
                        continue;
                    }
                    if (!GeoSearch.HasCategory(attraction, categories))
                    {
                        continue;
                    }
                    result.Add(attraction);
                }

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.ToString()));
            }
        }
Beispiel #4
0
        string TestLocation(LocationM LocationMe)
        {
            LocationM Tehtanloc = new LocationM()
            {
                X = 35.699745178222656, Y = 51.337795257568359
            };

            return(GeoCodeCalc.CalcDistance(Tehtanloc, LocationMe).ToString().ToLocationDistance());
        }
Beispiel #5
0
        private static double CalculateDistanceAlongStops(IList <TransitStopScheduledCall> stops)
        {
            var distance = 0.0;

            for (int i = 0; i < stops.Count - 1; i++)
            {
                distance += GeoCodeCalc.CalcDistance(stops[i].Stop.Lat, stops[i].Stop.Lng, stops[i + 1].Stop.Lat,
                                                     stops[i + 1].Stop.Lng);
            }
            return(distance);
        }
Beispiel #6
0
        private void CenterMap(IReadOnlyCollection <GeoCoords> coords)
        {
            var lowestLat  = coords.Select(l => l.Latitude).Min();
            var highestLat = coords.Select(l => l.Latitude).Max();
            var lowestLng  = coords.Select(l => l.Longitude).Min();
            var highestLng = coords.Select(l => l.Longitude).Max();
            var finalLat   = (lowestLat + highestLat) / 2;
            var finalLng   = (lowestLng + highestLng) / 2;
            var distance   = GeoCodeCalc.CalcDistance(lowestLat, lowestLng, highestLat, highestLng, GeoCodeCalcMeasurement.Kilometers);

            MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(finalLat, finalLng), Distance.FromKilometers(distance * 2 / 3)));
        }
Beispiel #7
0
 void Geolocator_PositionChanged(object sender, PositionEventArgs e)
 {
     if (oldPosition != null)
     {
         distance            += GeoCodeCalc.CalcDistance(oldPosition.Latitude, oldPosition.Longitude, e.Position.Latitude, e.Position.Longitude);
         currentItem.Distance = distance;
         DistanceEntry.Text   = currentItem.Distance.ToString();
     }
     else
     {
         oldPosition = e.Position;
     }
 }
Beispiel #8
0
    public string getGeofenceStatus(double lat1, double lon1, double lat2, double lon2, double radious)
    {
        double difference = GeoCodeCalc.CalcDistance(lat1, lon1, lat2, lon2);

        difference = difference * 1000;
        if (radious >= difference)
        {
            return("In Side");
        }
        else     //if (radious < difference)
        {
            return("Out Side");
        }
    }
Beispiel #9
0
 private async void EditPointButton_Clicked(object sender, EventArgs eventArgs, bool isStart)
 {
     if (MyPosition.Accuracy < Accuracy)
     {
         // Создаем наше модальное окно
         var alertPage = new AlertPopupPage(false,
                                            $"Использовать текущее местоположение как новые координаты {(isStart ? "начала ИССО" : "конца ИССО")}?",
                                            confirmText: "Да");
         // Описываем метод при нажатии на Ок
         alertPage.Confirm += (s, e) =>
         {
             // Записываем новые координаты
             if (isStart)
             {
                 StartGeo.Latitude  = MyPosition.Latitude;
                 StartGeo.Longitude = MyPosition.Longitude;
             }
             else
             {
                 EndGeo.Latitude  = MyPosition.Latitude;
                 EndGeo.Longitude = MyPosition.Longitude;
             }
             SetupPins(StartGeo, EndGeo);
             if (StartGeo != null && EndGeo != null)
             {
                 CenterMap(new List <GeoCoords> {
                     StartGeo, EndGeo
                 });
             }
             else if (MyPosition != null)
             {
                 CenterMap(new List <GeoCoords> {
                     new GeoCoords(MyPosition.Latitude, MyPosition.Longitude)
                 });
             }
             if (StartGeo != null && EndGeo != null)
             {
                 CurrentISSOLength.Text =
                     $"{(GeoCodeCalc.CalcDistance(StartGeo.Latitude, StartGeo.Longitude, EndGeo.Latitude, EndGeo.Longitude) * 1000):F1} м.";
             }
             EditIssoLocations();
             Edited = true;
         };
         await Navigation.PushPopupAsync(new CommonPopupPage(alertPage, "Изменение координат"));
     }
     else
     {
         DependencyService.Get <IMessage>().LongAlert("Нельзя установить новые координаты, т.к. погрешность > 10 м.");
     }
 }
        private static IEnumerable <SchoolSearchResult> CalcDistance(
            IEnumerable <SchoolSearchResult> results,
            string lat,
            string lng)
        {
            foreach (var result in results)
            {
                var location = result.Location;
                if (location != null)
                {
                    result.DistanceInMeters = GeoCodeCalc.CalcDistance(location.Latitude.ToString(), location.Longitude.ToString(), lat, lng);
                }
            }

            return(results);
        }
Beispiel #11
0
        public int UpdateLocation(LocationM Location, int UserId)
        {
            string  s1        = Location.X.ToString();
            string  s2        = Location.Y.ToString();
            Decimal Latitude  = Convert.ToDecimal(s1);
            Decimal Longitude = Convert.ToDecimal(s2);

            var userIdUbdatelocation = _db.Member.Where(x => x.UserId == UserId).FirstOrDefault();

            //userIdUbdatelocation.Location = new LocationM() { X = Location.X.LocationDecimals(), Y = Location.Y.LocationDecimals() };
            userIdUbdatelocation.X       = Location.X;
            userIdUbdatelocation.Y       = Location.Y;
            userIdUbdatelocation.Adrress = GeoCodeCalc.GetAddressFromLatLon(Latitude, Longitude);
            _db.SaveChanges();
            SetCurrentInstructionsUser(UserId, Selectoption.Mnu);
            return(0);
        }
        private static IEnumerable <IDictionary <string, object> > CalcDistance(
            IEnumerable <IDictionary <string, object> > results, string lat, string lng)
        {
            var calcDistance = results as IDictionary <string, object>[] ?? results.ToArray();

            foreach (var result in calcDistance)
            {
                if (result.ContainsKey("Location"))
                {
                    dynamic location = result["Location"];
                    if (location != null)
                    {
                        var coordinates = location.coordinates;
                        result.Add("distanceInMeters",
                                   GeoCodeCalc.CalcDistance(coordinates[1].ToString(), coordinates[0].ToString(), lat, lng));
                    }
                }
            }

            return(calcDistance);
        }
Beispiel #13
0
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs <GeoCoordinate> e)
        {
            Debug.WriteLine("watcher_PositionChanged");
            MyLocation.X = e.Position.Location.Longitude;
            MyLocation.Y = e.Position.Location.Latitude;
            //speed_text.Text = e.Position.Location.Speed.ToString();
            Debug.WriteLine("({0},{1})", e.Position.Location.Latitude, e.Position.Location.Longitude);

            mMap.Center = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);

            //---set the location for the Current_Location pushpin---
            Current_Location.Location = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);


            //drawCircle(new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude), 10);
            //drawCircle(new GeoCoordinate(e.Position.Location.Latitude-10, e.Position.Location.Longitude-10), 10);

            //---add the Current_Location pushpin to the map---
            if (mMap.Children.Contains(Current_Location) != true)
            {
                mMap.Children.Add(Current_Location);
            }
            else
            {
                mMap.Children.Remove(Current_Location);
                mMap.Children.Add(Current_Location);
            }

            //Update Traffic Incident: http://msdn.microsoft.com/en-us/library/hh441726.aspx
            // String address = "http://dev.virtualearth.net/REST/v1/Traffic/Incidents/";
            //address += (e.Position.Location.Latitude - 0.5) + ",";
            //address += (e.Position.Location.Longitude - 0.5) + ",";
            //address += (e.Position.Location.Latitude + 0.5) + ",";
            //address += (e.Position.Location.Longitude + 0.5);
            //address += "/true?t=1,2,3,4,5,6,7,8,9,10,11&s=1,2,3,4&key=";

            Debug.WriteLine("The distance is " + GeoCodeCalc.CalcDistance(MyLocation.Y, MyLocation.X, MyPreviousLocation.Y, MyPreviousLocation.X));
            double distance = GeoCodeCalc.CalcDistance(MyLocation.Y, MyLocation.X, MyPreviousLocation.Y, MyPreviousLocation.X);

            if (distance >= 2)
            {
                TRAFFIC_ADDRESS = updateTrafficIncidentUrl(e.Position.Location); // method creates traffic url

                // if traffic url is not empty
                if (TRAFFIC_ADDRESS.Count() > 1)
                {
                    if (!wc.IsBusy)
                    {
                        wc.DownloadStringAsync(new Uri(TRAFFIC_ADDRESS));
                    }
                }
                MyPreviousLocation = MyLocation;
                if (Pushpins != null && selectedIncident != null)
                {
                    ObservableCollection <PushpinModel> tempPuspins = Pushpins;
                    PivotItem currentPivotItem = (PivotItem)MainPivot.SelectedItem;
                    string    currentHeader    = (string)currentPivotItem.Header;
                    if (currentHeader == "all")
                    {
                        tempPuspins = Pushpins;
                    }
                    else if (currentHeader == "highways")
                    {
                        tempPuspins = FreewayPushpins;
                    }
                    else if (currentHeader == "roads")
                    {
                        tempPuspins = RoadPushpins;
                    }
                    foreach (PushpinModel pm in tempPuspins)
                    {
                        pm.severityColor   = pm.trafficIncident.severityColor;
                        pm.foregroundColor = "Black";
                        if (pm.trafficIncident.Equals(selectedIncident))
                        {
                            pm.severityColor         = "Black";
                            pm.foregroundColor       = "White";
                            PushpinLayer.ItemsSource = null;
                            PushpinLayer.ItemsSource = Pushpins;
                            break;
                        }
                    }
                }
            }
        }
    private void Load_History()
    {
        try
        {
            DataTable sampletable = new DataTable();

            int count = 0;
            Lbl_MsgInfo.Text = "";
            if (Session["main_user"] == null)
            {
                cmd = new MySqlCommand("SELECT main_user FROM loginstable WHERE (loginid = @loginid)");
                cmd.Parameters.Add("@loginid", UserName);
                DataTable mainusertbl = vdm.SelectQuery(cmd).Tables[0];
                if (mainusertbl.Rows.Count > 0)
                {
                    mainuser             = mainusertbl.Rows[0]["main_user"].ToString();
                    Session["main_user"] = mainuser;
                }
                else
                {
                    mainuser = UserName;
                }
            }
            else
            {
                mainuser = Session["main_user"].ToString();
            }
            reportData = new Dictionary <string, DataTable>();

            if (startdate.Text != "" && enddate.Text != "" && startdate.Text != "NA" && enddate.Text != "NA")
            {
                DateTime fromdate   = DateTime.Now;
                DateTime todate     = DateTime.Now;
                DateTime AMfromdate = DateTime.Now;
                DateTime AMtodate   = DateTime.Now;
                DateTime PMfromdate = DateTime.Now;
                DateTime PMtodate   = DateTime.Now;
                // d/M/yyyy HH:mm
                string[] datestrig = startdate.Text.Split(' ');

                if (datestrig.Length > 1)
                {
                    if (datestrig[0].Split('-').Length > 0)
                    {
                        string[] dates = datestrig[0].Split('-');
                        string[] times = datestrig[1].Split(':');
                        fromdate   = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                        AMfromdate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                        PMfromdate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                    }
                }
                else
                {
                    Lbl_MsgInfo.Text = "From Date Time Format Wrong";
                    return;
                }

                datestrig = enddate.Text.Split(' ');
                if (datestrig.Length > 1)
                {
                    if (datestrig[0].Split('-').Length > 0)
                    {
                        string[] dates = datestrig[0].Split('-');
                        string[] times = datestrig[1].Split(':');
                        todate   = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                        AMtodate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                        PMtodate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                    }
                }
                else
                {
                    Lbl_MsgInfo.Text = "To Date Time Format Wrong";
                    return;
                }

                List <string> logstbls = new List <string>();
                logstbls.Add("GpsTrackVehicleLogs");
                logstbls.Add("GpsTrackVehicleLogs1");
                logstbls.Add("GpsTrackVehicleLogs2");
                logstbls.Add("GpsTrackVehicleLogs3");
                logstbls.Add("GpsTrackVehicleLogs4");

                #region GeneralReports
                DataTable  rpttable = new DataTable();
                DataColumn col      = new DataColumn("VehicleID");
                rpttable.Columns.Add(col);
                //"Report From: " + fromdate.ToString() + "  To: " + todate.ToString() + " and  TotalDistance Travelled:" + (int)TotalDistance + "\n" +
                //    "Motion Hours:" + (int)RunningTime / 3600 + "H " + (int)RunningTime % (60) + "Min  Stationary Hours:" + (int)StopTime / 3600 + "H " + (int)StopTime % 60 + "Min  Max Speed:" + (int)Maxspeed + "KMPH  AvgSpeed: " + String.Format("{0:0.00}", avgspeed) + "KMPH  Idle Time: " + (int)IdleTime / 3600 + "H " + (int)IdleTime % 60 + " Min";
                col = new DataColumn("TotalDistanceTravelled(Kms)");
                rpttable.Columns.Add(col);
                col = new DataColumn("WorkingHours");
                rpttable.Columns.Add(col);
                col = new DataColumn("MotionHours");
                rpttable.Columns.Add(col);
                col = new DataColumn("StationaryHours");
                rpttable.Columns.Add(col);
                col = new DataColumn("IdleTime");
                rpttable.Columns.Add(col);
                col = new DataColumn("MaxSpeed");
                rpttable.Columns.Add(col);
                col = new DataColumn("AvgSpeed");
                rpttable.Columns.Add(col);
                col = new DataColumn("A/C ON Time");
                rpttable.Columns.Add(col);
                col = new DataColumn("No Of Stops");
                rpttable.Columns.Add(col);
                col = new DataColumn("Remarks");
                rpttable.Columns.Add(col);
                string vehiclestr = ddl_VehicleNo.SelectedItem.Text;
                if (vehiclestr.Length > 0)
                {
                    Maxspeed = 0;
                    #region codefor selected vehicles
                    double    SpeedLimit   = 0.0;
                    double    MaxIdleLimit = 0.0;
                    double    MaxStopLimit = 0.0;
                    DataTable logs         = new DataTable();
                    DataTable tottable     = new DataTable();
                    foreach (string tbname in logstbls)
                    {
                        cmd = new MySqlCommand("SELECT " + tbname + ".VehicleID, " + tbname + ".Speed, " + tbname + ".DateTime, " + tbname + ".Diesel, " + tbname + ".Latitiude, " + tbname + ".Longitude, " + tbname + ".TimeInterval, " + tbname + ".inp4, " + tbname + ".Status, " + tbname + ".Odometer, " + tbname + ".Direction, " + tbname + ".Direction AS Expr1, vehiclemaster.VendorNo, vehiclemaster.VendorName, vehiclemaster.VehicleTypeName, vehiclemaster.MaintenancePlantName FROM " + tbname + " LEFT OUTER JOIN vehiclemaster ON " + tbname + ".VehicleID = vehiclemaster.VehicleID AND " + tbname + ".UserID = vehiclemaster.UserName WHERE (" + tbname + ".DateTime >= @starttime) AND (" + tbname + ".DateTime <= @endtime) AND (" + tbname + ".VehicleID = '" + vehiclestr + "') and (" + tbname + ".UserID='" + mainuser + "') ORDER BY " + tbname + ".DateTime");
                        //cmd = new MySqlCommand("select * from " + tbname + " where DateTime>= @starttime and DateTime<=@endtime and VehicleID='" + vehiclestr + "' and UserID='" + UserName + "' order by DateTime");
                        cmd.Parameters.Add(new MySqlParameter("@starttime", fromdate));
                        cmd.Parameters.Add(new MySqlParameter("@endtime", todate));
                        logs = vdm.SelectQuery(cmd).Tables[0];
                        if (tottable.Rows.Count == 0)
                        {
                            tottable = logs.Clone();
                        }
                        foreach (DataRow dr in logs.Rows)
                        {
                            tottable.ImportRow(dr);
                        }
                    }
                    DataView dv = tottable.DefaultView;
                    dv.Sort = "DateTime ASC";
                    table   = dv.ToTable();
                    reportData.Add(vehiclestr, table);


                    double lat            = 0.0;
                    double longi          = 0.0;
                    double prvlat         = 0.0;
                    double prevLongi      = 0.0;
                    double TotalDistance  = 0.0;
                    double IdleTime       = 0.0;
                    double TotalTimeSpent = 0.0;
                    double StopTime       = 0.0;
                    double totalStops     = 0.0;
                    double RunningTime    = 0.0;
                    double TotalACTime    = 0.0;

                    bool onceMet        = false;
                    bool IdleStarted    = false;
                    bool runningStarted = false;
                    bool StopStarted    = false;
                    bool SpentStarttime = false;
                    bool IsDisplayed    = false;
                    bool ACStatred      = false;

                    DateTime PrvIdletime     = DateTime.Now;
                    DateTime presIdletime    = DateTime.Now;
                    DateTime PrvRunningtime  = DateTime.Now;
                    DateTime PresRunningtime = DateTime.Now;
                    DateTime PrvStoptime     = DateTime.Now;
                    DateTime PresStoptime    = DateTime.Now;
                    DateTime PresSpenttime   = DateTime.Now;
                    DateTime PrvSpenttime    = DateTime.Now;
                    DateTime PresACOnTime    = DateTime.Now;
                    DateTime PrvACOnTime     = DateTime.Now;

                    DateTime PrevGenTime        = DateTime.Now;
                    string   vehicleEnteredDate = "";
                    string   vehicleLeftDate    = "";
                    string   Remarks            = "No";
                    string   PrvBranch          = "";
                    string   PresBranchName     = "";


                    DataRow firstrow = null;
                    DataRow lastrow  = null;
                    if (table.Rows.Count > 1)
                    {
                        firstrow = table.Rows[0];
                        lastrow  = table.Rows[table.Rows.Count - 1];



                        foreach (DataRow dr1 in table.Rows)
                        {
                            int AC = 0;
                            int.TryParse(dr1["inp4"].ToString(), out AC);

                            if (lat == 0.0 && longi == 0.0)
                            {
                                lat           = (double)dr1["Latitiude"];
                                longi         = (double)dr1["Longitude"];
                                prvlat        = lat;
                                prevLongi     = longi;
                                TotalDistance = 0.0;
                                PrevGenTime   = (DateTime)dr1["DateTime"];

                                if (AC == 1)
                                {
                                    PrvACOnTime  = (DateTime)dr1["DateTime"];
                                    PresACOnTime = (DateTime)dr1["DateTime"];
                                    ACStatred    = true;
                                }
                                else
                                {
                                    ACStatred = false;
                                }
                            }
                            else
                            {
                                #region Calculations
                                lat            = (double)dr1["Latitiude"];
                                longi          = (double)dr1["Longitude"];
                                TotalDistance += GeoCodeCalc.CalcDistance(lat, longi, prvlat, prevLongi);
                                prvlat         = lat;
                                prevLongi      = longi;

                                double deisel = (double)dr1["Diesel"];
                                double speed  = (double)dr1["Speed"];
                                if (deisel > 50 && speed == 0)
                                {
                                    runningStarted = false;
                                    StopStarted    = false;
                                    if (IdleStarted)
                                    {
                                        presIdletime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(presIdletime.Ticks); //presIdletime.Hour, presIdletime.Minute, presIdletime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvIdletime.Ticks);  //PrvIdletime.Hour, PrvIdletime.Minute, PrvIdletime.Second);
                                        IdleTime   += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        PrvIdletime = presIdletime;
                                        PrevGenTime = presIdletime;
                                        if (IdleTime > MaxIdleLimit)
                                        {
                                            Remarks = "YES";
                                        }
                                    }
                                    else
                                    {
                                        IdleStarted = true;
                                        PrvIdletime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(PrevGenTime.Ticks); //presIdletime.Hour, presIdletime.Minute, presIdletime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvIdletime.Ticks); //PrvIdletime.Hour, PrvIdletime.Minute, PrvIdletime.Second);
                                        IdleTime   += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        PrevGenTime = PrvIdletime;
                                    }
                                }
                                //else if (deisel > 50 && speed > 0)
                                else if (speed > 0)
                                {
                                    IdleStarted = false;
                                    StopStarted = false;
                                    if (runningStarted)
                                    {
                                        PresRunningtime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(PresRunningtime.Ticks); //PresRunningtime.Hour, PresRunningtime.Minute, PresRunningtime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvRunningtime.Ticks);  //PrvRunningtime.Hour, PrvRunningtime.Minute, PrvRunningtime.Second);
                                        RunningTime += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        if (speed > Maxspeed)
                                        {
                                            Maxspeed = speed;
                                        }

                                        totalSpeed    += speed;
                                        PrvRunningtime = PresRunningtime;
                                        PrevGenTime    = PresRunningtime;
                                    }
                                    else
                                    {
                                        runningStarted = true;
                                        PrvRunningtime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(PrevGenTime.Ticks);    //presIdletime.Hour, presIdletime.Minute, presIdletime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvRunningtime.Ticks); //PrvIdletime.Hour, PrvIdletime.Minute, PrvIdletime.Second);
                                        RunningTime += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        totalSpeed  += speed;
                                        if (speed > Maxspeed)
                                        {
                                            Maxspeed = speed;
                                        }
                                        PrevGenTime = PrvRunningtime;
                                    }
                                }
                                else if (deisel < 50 && speed == 0)
                                {
                                    IdleStarted    = false;
                                    runningStarted = false;
                                    if (StopStarted)
                                    {
                                        PresStoptime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(PresStoptime.Ticks); //PresStoptime.Hour, PresStoptime.Minute, PresStoptime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvStoptime.Ticks);  //PrvStoptime.Hour, PrvStoptime.Minute, PrvStoptime.Second);
                                        StopTime   += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        PrvStoptime = PresStoptime;
                                        //if (speed > MaxStopLimit)
                                        //    Remarks = "YES-stopped";
                                        PrevGenTime = PresStoptime;
                                    }
                                    else
                                    {
                                        StopStarted = true;
                                        PrvStoptime = (DateTime)dr1["DateTime"];
                                        TimeSpan t  = new TimeSpan(PrevGenTime.Ticks); //presIdletime.Hour, presIdletime.Minute, presIdletime.Second);
                                        TimeSpan t1 = new TimeSpan(PrvStoptime.Ticks); //PrvIdletime.Hour, PrvIdletime.Minute, PrvIdletime.Second);
                                        StopTime   += Math.Abs(t.Subtract(t1).TotalSeconds);
                                        PrevGenTime = PrvStoptime;
                                        totalStops += 1;
                                    }
                                }
                                #endregion


                                if (AC == 1)
                                {
                                    if (ACStatred == false)
                                    {
                                        PrvACOnTime = (DateTime)dr1["DateTime"];
                                    }
                                    PresACOnTime = (DateTime)dr1["DateTime"];

                                    ACStatred = true;
                                }
                                else
                                {
                                    ACStatred = false;
                                }

                                if (ACStatred)
                                {
                                    PresACOnTime = (DateTime)dr1["DateTime"];
                                    TimeSpan t  = new TimeSpan(PresACOnTime.Ticks);//presIdletime.Hour, presIdletime.Minute, presIdletime.Second);
                                    TimeSpan t1 = new TimeSpan(PrvACOnTime.Ticks);
                                    TotalACTime += Math.Abs(t.Subtract(t1).TotalSeconds);
                                    PrvACOnTime  = PresACOnTime;
                                }
                            }
                        }


                        if (firstrow != null && lastrow != null)
                        {
                            double firstval = 0;
                            double.TryParse(firstrow["Odometer"].ToString(), out firstval);
                            double lastval = 0;
                            double.TryParse(lastrow["Odometer"].ToString(), out lastval);
                            if (lastval > 0 && firstval > 0)
                            {
                                TotalDistance = lastval - firstval;
                            }
                        }

                        double avgspeeddiv = (RunningTime / 3600);
                        double avgspeed    = 0;
                        if (avgspeeddiv > 0)
                        {
                            avgspeed = TotalDistance / avgspeeddiv;
                        }
                        DataRow tablerow = rpttable.NewRow();
                        tablerow["VehicleID"] = vehiclestr;
                        tablerow["TotalDistanceTravelled(Kms)"] = (Math.Abs(Math.Round(TotalDistance, 3))).ToString();
                        tablerow["WorkingHours"]    = (int)(RunningTime + IdleTime) / 3600 + "H " + (int)((RunningTime + IdleTime) % (60)) + "Min";
                        tablerow["MotionHours"]     = (int)RunningTime / 3600 + "H " + (int)RunningTime % (60) + "Min";
                        tablerow["StationaryHours"] = (int)StopTime / 3600 + "H " + (int)StopTime % 60 + "Min";
                        //tablerow["Stopped Time"]=
                        tablerow["MaxSpeed"]    = (int)Maxspeed + "KMPH";
                        tablerow["AvgSpeed"]    = String.Format("{0:0.00}", avgspeed) + "KMPH";
                        tablerow["IdleTime"]    = (int)IdleTime / 3600 + "H " + (int)IdleTime % 60 + " Min";
                        tablerow["No Of Stops"] = totalStops.ToString();
                        tablerow["A/C ON Time"] = (int)TotalACTime / 3600 + "H " + (int)TotalACTime % 60 + " Min";//.ToString();
                        rpttable.Rows.Add(tablerow);

                        lbl_vehicleNos.Text      = vehiclestr;
                        lbl_TotalDistance.Text   = (Math.Abs(Math.Round(TotalDistance, 3))).ToString();
                        lbl_WorkingHours.Text    = (int)(RunningTime + IdleTime) / 3600 + "H " + (int)((RunningTime + IdleTime) % (60)) + "Min";
                        lbl_StationaryHours.Text = (int)StopTime / 3600 + "H " + (int)StopTime % 60 + "Min";
                        lbl_MaxSpeed.Text        = (int)Maxspeed + "KMPH";
                        lbl_AvgSpeed.Text        = String.Format("{0:0.00}", avgspeed) + "KMPH";
                        lbl_IdleTime.Text        = (int)IdleTime / 3600 + "H " + (int)IdleTime % 60 + " Min";
                        lbl_NoOfStops.Text       = totalStops.ToString();
                        lbl_ACONTime.Text        = (int)TotalACTime / 3600 + "H " + (int)TotalACTime % 60 + " Min";

                        #endregion
                    }
                }
                #endregion
            }
        }
        catch (Exception ex)
        {
        }
    }
Beispiel #15
0
        public EditCoordsContentPage(int cIsso)
        {
            InitializeComponent();
            CIsso = cIsso;
            Title = "АИС ИССО-IX. Изменение геокоординат.";
            MyMap = new Map
            {
                VerticalOptions   = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };
            ForMap.Children.Add(MyMap);

            using (var connection = new SqliteConnection(ConnectionClass.NewDatabasePath))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText    = $"select * from V_ISSO where C_ISSO={cIsso}";
                    command.CommandTimeout = 30;
                    command.CommandType    = System.Data.CommandType.Text;
                    connection.Open();
                    using (var datareader = command.ExecuteReader())
                    {
                        if (datareader.HasRows)
                        {
                            while (datareader.Read())
                            {
                                StartGeo = new GeoCoords(Convert.ToDouble(datareader["P1_LATITUDE"]), Convert.ToDouble(datareader["P1_LONGITUDE"]));
                                EndGeo   = new GeoCoords(Convert.ToDouble(datareader["P2_LATITUDE"]), Convert.ToDouble(datareader["P2_LONGITUDE"]));
                            }
                        }
                        datareader.Close();
                    }
                }
                connection.Close();
            }

            CurrentISSOLength.Text =
                $"{(GeoCodeCalc.CalcDistance(StartGeo.Latitude, StartGeo.Longitude, EndGeo.Latitude, EndGeo.Longitude) * 1000):F1} м.";
            if (StartGeo != null && EndGeo != null)
            {
                CenterMap(new List <GeoCoords> {
                    StartGeo, EndGeo
                });
                SetupPins(StartGeo, EndGeo);
            }
            else if (MyPosition != null)
            {
                CenterMap(new List <GeoCoords> {
                    new GeoCoords(MyPosition.Latitude, MyPosition.Longitude)
                });
            }
            // Инициализация кнопки центрирования карты
            Btn_Follow.Image = new FileImageSource()
            {
                File = CommonStaffUtils.GetFilePath("define_location_dark.png")                                                    /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "free_location_dark.png")*/
            };
            Btn_Follow.Clicked += (s, e) =>
            {
                var listIssos = new List <GeoCoords>();
                if (StartGeo != null && EndGeo != null)
                {
                    listIssos.Add(StartGeo);
                    listIssos.Add(EndGeo);
                }
                else if (MyPosition != null)
                {
                    listIssos.Add(new GeoCoords(MyPosition.Latitude, MyPosition.Longitude));
                }
                CenterMap(listIssos);
            };

            // Инициализация кнопки выбора спутников
            Btn_Satellite.Image = TypesMapImgLight[0];

            EditIssoLocations();

            EditStartPointButton.Image = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("no_location_light.png")
            };
            EditEndPointButton.Image = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("no_location_light.png")
            };

            EditStartPointButton.Clicked += (s, e) => { EditPointButton_Clicked(s, e, true); };
            EditEndPointButton.Clicked   += (s, e) => { EditPointButton_Clicked(s, e, false); };
        }