Example #1
0
        public double GetDistance(Location target)
        {
            CLLocation currentLoc = new CLLocation(this.CurrentLocation.Latitude, this.CurrentLocation.Longitude);
            CLLocation targetLoc  = new CLLocation(target.Latitude, target.Longitude);

            return(currentLoc.DistanceFrom(targetLoc));
        }
Example #2
0
        static public void UpdateLocation(GPSLocate ms, CLLocation newLocation)
        {
            ms.LblAltitude.Text  = newLocation.Altitude.ToString() + " meters";
            ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString() + "º";
            ms.LblLatitude.Text  = newLocation.Coordinate.Latitude.ToString() + "º";
            ms.LblCourse.Text    = newLocation.Course.ToString() + "º";
            ms.LblSpeed.Text     = newLocation.Speed.ToString() + " meters/s";

            // get the distance from here to paris
            ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km";


            var x1       = Convert.ToDouble("40.023408");
            var y1       = Convert.ToDouble("40.643127");
            var x2       = Convert.ToDouble("30.753657");
            var y2       = Convert.ToDouble("30.038635");
            var longdute = newLocation.Coordinate.Longitude;
            var latidute = newLocation.Coordinate.Latitude;


            ms.checkIt.Clicked += (sender, e) => {
                if (longdute > x2 && longdute < x1 && latidute > y2 && latidute < y1)
                {
                    new UIAlertView("Ankara Dışındasın", "Konum : " + longdute + " " + latidute, null, "OK", null).Show();
                }
                else
                {
                    new UIAlertView("Ankara İçerisindesin", "Konum : " + longdute + " " + latidute, null, "OK", null).Show();
                }
            };
        }
        private double?checkLocation()
        {
            var overlays           = map.Overlays;
            var user               = map.UserLocation;
            var userLatitude       = user.Location.Coordinate.Latitude;
            var userLongitude      = user.Location.Coordinate.Longitude;
            var affordableDistance = 0.00;

            foreach (var overlay in overlays)
            {
                var latitude  = overlay.Coordinate.Latitude;
                var longitude = overlay.Coordinate.Longitude;
                var overlapCenterCoordinate  = new CLLocation(latitude, longitude);
                var userLocationCoordinate   = new CLLocation(userLatitude, userLongitude);
                var distanceFromCenterToUser = overlapCenterCoordinate.DistanceFrom(userLocationCoordinate);

                if (distanceFromCenterToUser <= 1000.00)
                {
                    affordableDistance = distanceFromCenterToUser;
                }
            }

            if (affordableDistance != 0.00)
            {
                return(affordableDistance);
            }
            else
            {
                return(null);
            }
        }
Example #4
0
        // Calculates the distance between two points
        public double GetDistanceTravelled(double lat, double lon)
        {
            // Get the distance travelled from current location to previous location
            var distance = newLocation.DistanceFrom(new CLLocation(lat, lon)) / 1000;

            return(distance);
        }
Example #5
0
        private double GetDistanceFromLatLonInKm(double lat1, double lon1, double lat2, double lon2)
        {
            CLLocation pointALocation = new CLLocation(lat1, lon1);
            CLLocation pointBLocation = new CLLocation(lat2, lon2);

            return(pointALocation.DistanceFrom(pointBLocation) / 1000);
        }
Example #6
0
        UIView markerInfoWindow(UIView view, Marker marker)
        {
            if (marker.ZIndex == 0)
            {
                return(null);
            }

            MapMarkerView v = MapMarkerView.Create();

            var resID = marker.ZIndex.ToString();

            for (int i = 0; i < _pickups.Count; i++)
            {
                if (_pickups [i]["ResID"] == resID)
                {
                    var pickup   = _pickups [i];
                    var pos1     = new CLLocation(double.Parse(pickup ["Latitude"]), double.Parse(pickup ["Longitude"]));
                    var pos2     = new CLLocation(LocationHelper.GetLocationResult().Latitude, LocationHelper.GetLocationResult().Longitude);
                    var distance = string.Format("{0}m", (Math.Round(pos1.DistanceFrom(pos2))).ToString());

                    DateTime pDate   = DateTime.Parse(pickup ["Date"]);
                    string[] arrDate = pDate.GetDateTimeFormats();
                    string   strType = pickup ["ArvDep"] == "1" ? "Drop-Off" : "Pick-Up";
                    string   title   = string.Format("{0} - {1} {2}", pickup ["ResType"], arrDate[108], strType);
                    v.SetView(title, distance);
                }
            }
            return(v);
        }
Example #7
0
        bool ClickedDropItem(MapView mapView, Marker marker)
        {
            mSelectedDrop = mDrops[marker.ZIndex];
            if (mSelectedDrop.Password == string.Empty || mSelectedDrop.Password == null)
            {
                var        currentLocation = LocationHelper.GetLocationResult();
                CLLocation dLocation       = new CLLocation(mSelectedDrop.Location_Lat, mSelectedDrop.Location_Lnt);
                CLLocation cLocation       = new CLLocation(currentLocation.Latitude, currentLocation.Longitude);
                var        distance        = dLocation.DistanceFrom(cLocation);

                if (distance > Constants.PURCHASE_DISTANCE)
                {
                    PurchasePopUp pPopup = PurchasePopUp.Create(Constants.PURCHASE_TYPE.VIEW);
                    pPopup.PopUp(true, OpenPurchase);
                }
                else
                {
                    ViewDropDetail();
                }
            }
            else
            {
                ShowTextFieldBox(Constants.STR_VERIFY_PASSWORD_TITLE, "Cancel", new[] { "OK" }, VerifyPassword);
            }

            return(true);
        }
        public float CalculateDistance(Position position1, Position position2)
        {
            CLLocation location1 = new CLLocation(position1.Latitude, position1.Longitude);
            CLLocation location2 = new CLLocation(position1.Latitude, position1.Longitude);

            return((float)location1.DistanceFrom(location2));
        }
Example #9
0
        //This will keep going in the background and the foreground
        private void UpdateLocation(object sender, LocationUpdatedEventArgs e)
        {
            if (oldLocation != null)
            {
                var distance = oldLocation.DistanceFrom(e.Location);
                if (distance >= 100)
                {
                    oldLocation = e.Location;
                    this.OnLocationChangedAsync(oldLocation);
                }
            }
            else
            {
                CLLocation location = e.Location;
                oldLocation = location;
                this.OnLocationChangedAsync(location);
            }

            //var monitores = locMgr.MonitoredRegions.ToArray<CLRegion>();

            //foreach(CLRegion rg in monitores)
            //{
            //    locMgr.StopMonitoring(rg);
            //}

            //var region = new CLRegion(location.Coordinate, 100, "region");
            //region.NotifyOnExit = true;
            //region.NotifyOnEntry = false;

            //locMgr.StartMonitoring(region);
        }
Example #10
0
        //Showed calculate how long you have run and how long you have left.
        public void MeterLeftToRun(MKMapView map, CLLocation pointA,
                                   UIKit.UILabel LeftOnRunlabel, double LengthOfTheRun)
        {
            CLLocation pointB = new CLLocation(map.UserLocation.Location.Coordinate.Latitude,
                                               map.UserLocation.Location.Coordinate.Longitude);

            var distanceToB = pointB.DistanceFrom(pointA);


            //The connection an the information to the server.



            //string text = "You have left" + distanceToB;
            //UserClient.Connect("10.0.1.5", text);
            string testRegistrationOFAUser = "******";

            UserClient.Connect("10.0.1.5", testRegistrationOFAUser);



            Console.WriteLine("THIS IS THE Destination between A and B" + distanceToB.ToString());
            Console.WriteLine("INTERNET IS ON" + UserClient.CheckConnectivity());


            if (LengthOfTheRun <= distanceToB)
            {
                Console.WriteLine("END OF RUN");
                audioManager.PlaySound("Finished.mp3");
            }
            double length = Math.Round(distanceToB, 2);

            Console.WriteLine(LengthOfTheRun - distanceToB);
            LeftOnRunlabel.Text = "YOU HAVE RUN: " + length.ToString();
        }
Example #11
0
        public double Distance(double lat, double lng, XLocation b)
        {
            var firstPoint  = new CLLocation(lat, lng);
            var secondPoint = new CLLocation(b.Latitude, b.Longitude);

            return(firstPoint.DistanceFrom(secondPoint));
        }
        void LocationUpdated(object sender, EventArgs e)
        {
            foreach (UIView view in virtualDropContent.Subviews)
            {
                view.RemoveFromSuperview();
            }

            CLLocationsUpdatedEventArgs locArgs = e as CLLocationsUpdatedEventArgs;
            var currentLocation = locArgs.Locations[locArgs.Locations.Length - 1];

            for (int i = 0; i < mDrops.Count; i++)
            {
                var drop = mDrops[i];

                if (!drop.IsVisibilityByUser())
                {
                    continue;
                }

                CLLocation pointB      = new CLLocation(drop.Location_Lat, drop.Location_Lnt);
                var        distanceToB = pointB.DistanceFrom(currentLocation);

                if (distanceToB < Constants.PURCHASE_DISTANCE)
                {
                    VisibleDrop(drop, currentLocation);
                }
            }
        }
Example #13
0
        public static void UpdateLocation(GPSLocate ms, CLLocation newLocation)
        {
            ms.LblAltitude.Text = newLocation.Altitude.ToString () + " meters";
             ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString () + "º";
             ms.LblLatitude.Text = newLocation.Coordinate.Latitude.ToString () + "º";
             ms.LblCourse.Text = newLocation.Course.ToString () + "º";
             ms.LblSpeed.Text = newLocation.Speed.ToString () + " meters/s";

             // get the distance from here to paris
             ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km";

             var x1 =Convert.ToDouble( "40.023408");
             var y1 =Convert.ToDouble( "40.643127");
             var x2 =Convert.ToDouble( "30.753657");
             var y2 = Convert.ToDouble("30.038635");
             var longdute =newLocation.Coordinate.Longitude;
             var latidute = newLocation.Coordinate.Latitude;

             ms.checkIt.Clicked+= (sender, e) => {

            if (longdute > x2 && longdute < x1 && latidute > y2 && latidute < y1)
               new UIAlertView("Ankara Dışındasın", "Konum : " + longdute + " " + latidute, null, "OK", null).Show();
            else
               new UIAlertView("Ankara İçerisindesin", "Konum : " + longdute + " " + latidute, null, "OK", null).Show();

             };
        }
Example #14
0
        public void SetView(ParseItem drop, CLLocation uLocation, HomeViewController rootVC)
        {
            mDrop       = drop;
            this.rootVC = rootVC;

            CLLocation dLocation = new CLLocation(drop.Location_Lat, drop.Location_Lnt);
            var        distance  = dLocation.DistanceFrom(uLocation);

            var imgScale  = 1 - distance / Constants.PURCHASE_DISTANCE;
            var vdropSize = Constants.VDROP_MAX_SIZE * imgScale;

            var angle         = DegreeBearing(uLocation, dLocation);
            var distanceScale = (distance / Constants.PURCHASE_DISTANCE) * (rootVC.View.Frame.Size.Width / 2);

            var posX = rootVC.View.Frame.Size.Width / 2 + Math.Sin(angle) * distanceScale - vdropSize / 2;
            var posY = rootVC.View.Frame.Size.Height / 2 - Math.Cos(angle) * distanceScale - vdropSize / 2;

            var frame = new CGRect(posX, posY, vdropSize, vdropSize);

            this.Frame = frame;

            lblDistance.Text = distance.ToString("F2") + " m";

            imgIcon.SetImage(
                url: new NSUrl(drop.IconURL.ToString()),
                placeholder: UIImage.FromBundle("icon_drop1.png")
                );

            LayoutIfNeeded();
        }
        /// <summary>
        /// Translates distance in meters between two locations.
        /// Returns the result as the distance in latitude and distance in longitude.
        /// </summary>
        /// <returns>The translation.</returns>
        /// <param name="self">Self.</param>
        /// <param name="toLocation">To location.</param>
        public static LocationTranslation Translation(this CLLocation self, CLLocation toLocation)
        {
            var inbetweenLocation = new CLLocation(latitude: self.Coordinate.Latitude, longitude: toLocation.Coordinate.Longitude);

            var distanceLatitude    = toLocation.DistanceFrom(inbetweenLocation);
            var latitudeTranslation = default(double);

            if (toLocation.Coordinate.Latitude > inbetweenLocation.Coordinate.Latitude)
            {
                latitudeTranslation = distanceLatitude;
            }
            else
            {
                latitudeTranslation = 0 - distanceLatitude;
            }

            var distanceLongitude    = self.DistanceFrom(inbetweenLocation);
            var longitudeTranslation = default(double);

            if (self.Coordinate.Longitude > inbetweenLocation.Coordinate.Longitude)
            {
                longitudeTranslation = 0 - distanceLongitude;
            }
            else
            {
                longitudeTranslation = distanceLongitude;
            }

            var altitudeTranslation = toLocation.Altitude - self.Altitude;

            return(new LocationTranslation(latitudeTranslation, longitudeTranslation, altitudeTranslation));
        }
Example #16
0
        public double DistanceAtoB(TPoint pA, TPoint pB)
        {
            CLLocation pointA   = new CLLocation(pA.Latitude, pA.Longitude);
            CLLocation pointB   = new CLLocation(pB.Latitude, pB.Longitude);
            var        distance = pointA.DistanceFrom(pointB);

            return(distance);
        }
Example #17
0
        public void UpdatePlacesOfInterestCoordinates(Position position)
        {
            double myX = 0.0, myY = 0.0, myZ = 0.0;

            MathHelpers.LatLonToEcef(position.Latitude, position.Longitude, 0.0, ref myX, ref myY, ref myZ);

            placesOfInterestCoordinates = new List <float[]>();

            foreach (var poi in PointsOfInterest)
            {
                double poiX = 0.0, poiY = 0.0, poiZ = 0.0, e = 0.0, n = 0.0, u = 0.0;
                MathHelpers.LatLonToEcef(poi.POI.Latitude, poi.POI.Longitude, poi.POI.Altitude, ref poiX, ref poiY, ref poiZ);
                MathHelpers.EcefToEnu(poi.POI.Latitude, poi.POI.Longitude, myX, myY, myZ, poiX, poiY, poiZ, ref e, ref n, ref u);

                var p = new float[4];
                p[0] = (float)n;
                p[1] = -(float)e;
                p[2] = 0.0f;
                p[3] = 1.0f;

                placesOfInterestCoordinates.Add(p);

                if (poi.View == null)
                {
                    poi.View = new UILabel
                    {
                        AdjustsFontSizeToFitWidth = false,
                        Opaque          = false,
                        BackgroundColor = new UIColor(0.1f, 0.1f, 0.1f, 0.5f),
                        Center          = new PointF(200.0f, 200.0f),
                        TextAlignment   = UITextAlignment.Center,
                        TextColor       = UIColor.White,
                        Lines           = 0,
                        LineBreakMode   = UILineBreakMode.WordWrap,
                        Hidden          = true
                    };

                    AddSubview(poi.View);
                }

                CLLocation newLocation = new CLLocation(new CLLocationCoordinate2D(position.Latitude, position.Longitude),
                                                        position.Altitude, position.Accuracy, position.AltitudeAccuracy, NSDate.Now);
                var distance = newLocation.DistanceFrom(new CLLocation(poi.POI.Latitude, poi.POI.Longitude));
                if (distance > 1000)
                {
                    ((UILabel)poi.View).Text = string.Format("{0} - {1:F} km", poi.POI.Name, distance / 1000);
                }
                else
                {
                    ((UILabel)poi.View).Text = string.Format("{0} - {1:F} m", poi.POI.Name, distance);
                }
                var size = ((UILabel)poi.View).Text.StringSize(((UILabel)poi.View).Font);
                // var size = UIStringDrawing.StringSize(((UILabel)poi.View).Text, ((UILabel)poi.View).Font);
                ((UILabel)poi.View).Bounds = new CoreGraphics.CGRect(0.0f, 0.0f, size.Width, size.Height);
            }
        }
Example #18
0
            public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
            {
                ms.LblAltitude.Text  = newLocation.Altitude.ToString() + "meters";
                ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString() + "º";
                ms.LblLatitude.Text  = newLocation.Coordinate.Latitude.ToString() + "º";
                ms.LblCourse.Text    = newLocation.Course.ToString() + "º";
                ms.LblSpeed.Text     = newLocation.Speed.ToString() + "meters/s";

                // get the distance from here to paris
                ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + "km";
            }
        static public void UpdateLocation(IMainScreen ms, CLLocation newLocation)
        {
            ms.LblAltitude.Text  = newLocation.Altitude.ToString() + " meters";
            ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString() + "º";
            ms.LblLatitude.Text  = newLocation.Coordinate.Latitude.ToString() + "º";
            ms.LblCourse.Text    = newLocation.Course.ToString() + "º";
            ms.LblSpeed.Text     = newLocation.Speed.ToString() + " meters/s";

            // get the distance from here to paris
            ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km";
        }
Example #20
0
        public OperationResult <double> GetDistanceBetween(Position firstPosition, Position secondPosition)
        {
            if (firstPosition == null || secondPosition == null)
            {
                return(OperationResult <double> .AsFailure("Invalid positions specified"));
            }

            var firstLocation  = new CLLocation(firstPosition.Latitude, firstPosition.Longitude);
            var secondLocation = new CLLocation(secondPosition.Latitude, secondPosition.Longitude);

            return(OperationResult <double> .AsSuccess(firstLocation.DistanceFrom(secondLocation)));
        }
Example #21
0
        public bool checkDistance(CLLocation sculpture, CLLocation current)
        {
            double meters = current.DistanceFrom(sculpture);

            if (meters <= 7)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        //Metodo de busqueda de la tienda mas cercana.
        public StoresService nearestStore(CLLocation location, List <StoresService> stores)
        {
            StoresService nearStore = stores.ElementAt(0);

            foreach (StoresService store in stores)
            {
                if ((location.DistanceFrom(new CLLocation(Double.Parse(store.latitud), Double.Parse(store.longitud)))) < (location.DistanceFrom(new CLLocation(Double.Parse(nearStore.latitud), Double.Parse(nearStore.longitud)))))
                {
                    nearStore = store;
                }
            }
            return(nearStore);
        }
Example #23
0
 //Caution: If radius is too large results will be HUGE!
 //radius in meters
 public IEnumerable<BusStop> getAllBusStops(CLLocation aboutLoc, double radius)
 {
     List<BusStop> stops = new List<BusStop>(30);
     using (LumenWorks.Framework.IO.Csv.CsvReader csv = new LumenWorks.Framework.IO.Csv.CsvReader(getReader("stops.txt"),true)) {
         while (csv.ReadNextRecord()){
             CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"]));
             if (loc.DistanceFrom(aboutLoc)<=radius)
                 stops.Add(new BusStop(csv["stop_name"],int.Parse(csv["stop_id"]), loc));
             loc.Dispose();
         }
         return stops;
     }
 }
        //Metodo de busqueda de la tienda mas cercana.
        public ProductSearchDetailService nearestStore(CLLocation location, List <ProductSearchDetailService> stores)
        {
            Console.WriteLine("" + location.Coordinate.Latitude);
            ProductSearchDetailService nearStore = stores.ElementAt(0);

            foreach (ProductSearchDetailService store in stores)
            {
                if ((location.DistanceFrom(new CLLocation(Double.Parse(store.tienda_latitud), Double.Parse(store.tienda_longitud)))) < (location.DistanceFrom(new CLLocation(Double.Parse(nearStore.tienda_latitud), Double.Parse(nearStore.tienda_longitud)))))
                {
                    nearStore = store;
                }
            }
            return(nearStore);
        }
Example #25
0
        // iOS 9 <=, fire when recieve notification foreground
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler)
        {
            Messaging.SharedInstance.AppDidReceiveMessage(userInfo);

            // Generate custom event
            NSString[] keys       = { new NSString("Event_type") };
            NSObject[] values     = { new NSString("Recieve_Notification") };
            var        parameters = NSDictionary <NSString, NSObject> .FromObjectsAndKeys(keys, values, keys.Length);

            // Send custom event
            //Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);

            if (application.ApplicationState == UIApplicationState.Active)
            {
                var aps_d   = userInfo["aps"] as NSDictionary;
                var alert_d = aps_d["alert"] as NSDictionary;
                try
                {
                    NSNumberFormatter formatter = new NSNumberFormatter
                    {
                        NumberStyle = NSNumberFormatterStyle.Decimal
                    };
                    var mLat = userInfo["lat"] as NSString;
                    var mLng = userInfo["lng"] as NSString;
                    //NSNumber lat = (formatter.NumberFromString(mLat));
                    //NSNumber lng = (formatter.NumberFromString(mLng));
                    double     lat      = Convert.ToDouble(mLat);
                    double     lng      = Convert.ToDouble(mLng);
                    CLLocation notifLoc = new CLLocation(lat, lng);
                    var        distance = notifLoc.DistanceFrom(curLocation);
                    Console.WriteLine($"Distance: {distance}");
                    //Console.WriteLine($"lat: {lat}, lng:{lng}");
                } catch (NullReferenceException e)
                {
                    //TODO: log this maybe?
                    Console.WriteLine(e);
                }

                try
                {
                    var body  = alert_d["body"] as NSString;
                    var title = alert_d["title"] as NSString;
                    DebugAlert(title, body);
                } catch (NullReferenceException)
                {
                    //TODO: here?
                }
            }
            completionHandler(UIBackgroundFetchResult.NewData);
        }
Example #26
0
        public void DidUpdateUserLocation(MKMapView mapView, MKUserLocation userLocation)
        {
            if (userLocation != null)
            {
                Console.WriteLine("location: " + userLocation.Coordinate.Latitude + " " + userLocation.Coordinate.Longitude);

                if (!ViewModel.IsNavigating || !ViewModel.HasStaredNavigation)
                {
                    return;
                }

                if (currentStepIndex < ViewModel.Routes.Count - 1)
                {
                    RouteItem  nextItem    = ViewModel.Routes [currentStepIndex + 1];
                    CLLocation nexLocation = new CLLocation(nextItem.Lat, nextItem.Long);

                    double distanceToNext = userLocation.Location.DistanceFrom(nexLocation);

                    Console.WriteLine("distance to next steps " + distanceToNext);

                    RouteItem  currentItem       = ViewModel.Routes [currentStepIndex];
                    CLLocation currentLocation   = new CLLocation(currentItem.Lat, currentItem.Long);
                    double     distanceToCurrent = userLocation.Location.DistanceFrom(currentLocation);

                    double distanceCurrentToNext = nexLocation.DistanceFrom(currentLocation);

                    if (distanceToNext < distanceCurrentToNext && distanceToCurrent > 5 && distanceToNext < 100)
                    {
                        Console.WriteLine("move to next steps");
                        collectionRoutes.SetContentOffset(new CGPoint(collectionRoutes.Frame.Width * (currentStepIndex + 1), 0), true);
                        DrawStepForIndex(currentStepIndex + 1, false);
                    }
                    else if (currentStepIndex > 0)
                    {
                        RouteItem  prevItem     = ViewModel.Routes [currentStepIndex - 1];
                        CLLocation prevLocation = new CLLocation(prevItem.Lat, prevItem.Long);

                        double distanceToPrev        = userLocation.Location.DistanceFrom(prevLocation);
                        double distancePrevToCurrent = prevLocation.DistanceFrom(currentLocation);

                        if (distanceToPrev < 5 && distanceToCurrent > distancePrevToCurrent)
                        {
                            // user go back to prev step
                            collectionRoutes.SetContentOffset(new CGPoint(collectionRoutes.Frame.Width * (currentStepIndex - 1), 0), true);
                            DrawStepForIndex(currentStepIndex - 1, false);
                        }
                    }
                }
            }
        }
Example #27
0
 public BusStop? getClosestStop(CLLocation aboutLoc)
 {
     int closestId = -1;
     double closestDist=double.MaxValue;
     using (CsvReader csv = new CsvReader(getReader("stops.txt"),true)) {
         while (csv.ReadNextRecord()){
             CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"]));
             if (loc.DistanceFrom(aboutLoc)<=closestDist)
                 closestId=int.Parse(csv["stop_id"]);
             loc.Dispose();
         }
     }
     return (closestId==-1)?null:getStopInfo(closestId);
 }
        private void LocationUpdated(object sender, CLLocationsUpdatedEventArgs e)
        {
            if (arrived)
            {
                return;
            }

            if (!(e?.Locations?.Length > 0))
            {
                Console.WriteLine("No locations");
                return;
            }

            CLLocation lastLoc = e.Locations[e.Locations.Length - 1];

            lastDistance = (float)lastLoc.DistanceFrom(new CLLocation(target.Lat, target.Long));
            string distanceString = "Arrived!";

            if (lastDistance >= 1000)
            {
                distanceString = string.Format("{0} km", (lastDistance / 1000).ToString("N2"));
            }
            else if (lastDistance >= 10)
            {
                distanceString = string.Format("{0} metres", lastDistance.ToString("N0"));
            }

            DistanceLabel.Text = distanceString;
            AccuracyLabel.Text = string.Format("Accuracy: within {0} metres", (lastLoc.HorizontalAccuracy * 2).ToString("N0"));

            if (!startedAnim)
            {
                startedAnim = true;
                Animate();
            }

            if (lastDistance < 10)
            {
                arrived = true;
                locationManager.StopUpdatingLocation();
                AppUtils.ShowSimpleDialog(
                    this,
                    "Finished!",
                    "You\'ve arrived at the destination!",
                    "Got it",
                    (act) => { ReturnWithData(true.ToString()); });
            }
        }
        async void ShowPath()
        {
            var inputController = new InputDataController();
            var data            = await inputController.GetListAsync(_jsonResult);

            var locations = new List <CLLocationCoordinate2D>();


            foreach (var item in data)
            {
                locations.Add(new CLLocationCoordinate2D()
                {
                    Latitude = item.Latitude, Longitude = item.Longitude
                });
            }
            MapView.RemoveAnnotations(MapView.Annotations);
            if (locations.Count > 0)
            {
                var polyline = MKPolyline.FromCoordinates(locations.ToArray());
                MapView.AddOverlay(polyline);

                var startLocation = new CLLocation(locations[0].Latitude,
                                                   locations[0].Longitude);
                var endLocation = new CLLocation(locations.Last().Latitude,
                                                 locations.Last().Longitude);
                var distance = startLocation.DistanceFrom(endLocation);


                var region = MKCoordinateRegion.FromDistance(locations[(locations.Count / 2)],
                                                             distance + 10000, distance + 10000);
                MapView.SetRegion(region, animated: false);

                var annoStart = new FlightAnnotation(title: "Starting point",
                                                     subtitle: "",
                                                     coordinate: locations[0]);
                MapView.AddAnnotation(annoStart);


                var annoEnd = new FlightAnnotation(title: "End point",
                                                   subtitle: "",
                                                   coordinate: locations.Last());
                annoEnd.TintColor = UIColor.Purple;

                MapView.AddAnnotation(annoEnd);
            }
        }
Example #30
0
        public OperationResult <double> GetDistanceFrom(Position referencePosition)
        {
            if (referencePosition == null)
            {
                return(OperationResult <double> .AsFailure("Invalid reference position specified"));
            }

            if (_position == null)
            {
                return(OperationResult <double> .AsFailure("Current position not available"));
            }

            var currentLocation   = new CLLocation(_position.Latitude, _position.Longitude);
            var referenceLocation = new CLLocation(referencePosition.Latitude, referencePosition.Longitude);

            return(OperationResult <double> .AsSuccess(referenceLocation.DistanceFrom(currentLocation)));
        }
Example #31
0
        //Caution: If radius is too large results will be HUGE!
        //radius in meters
        public IEnumerable <BusStop> getAllBusStops(CLLocation aboutLoc, double radius)
        {
            List <BusStop> stops = new List <BusStop>(30);

            using (LumenWorks.Framework.IO.Csv.CsvReader csv = new LumenWorks.Framework.IO.Csv.CsvReader(getReader("stops.txt"), true)) {
                while (csv.ReadNextRecord())
                {
                    CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"]));
                    if (loc.DistanceFrom(aboutLoc) <= radius)
                    {
                        stops.Add(new BusStop(csv["stop_name"], int.Parse(csv["stop_id"]), loc));
                    }
                    loc.Dispose();
                }
                return(stops);
            }
        }
Example #32
0
        //a more memory friendly way to get the closest stop than getting a list, sorting, and tossing
        public BusStop?getClosestStop(CLLocation aboutLoc)
        {
            var    allStops    = SafeQuery <GTFS_Stop>("select * from stops");
            int    closestId   = -1;
            double closestDist = double.MaxValue;

            foreach (GTFS_Stop stop in allStops)
            {
                CLLocation loc = new CLLocation(stop.stop_lat, stop.stop_lon);
                if (loc.DistanceFrom(aboutLoc) <= closestDist)
                {
                    closestId = stop.stop_id;
                }
                loc.Dispose();
            }
            return((closestId == -1)?null:getStopInfo(closestId));
        }
Example #33
0
        public BusStop?getClosestStop(CLLocation aboutLoc)
        {
            int    closestId   = -1;
            double closestDist = double.MaxValue;

            using (CsvReader csv = new CsvReader(getReader("stops.txt"), true)) {
                while (csv.ReadNextRecord())
                {
                    CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"]));
                    if (loc.DistanceFrom(aboutLoc) <= closestDist)
                    {
                        closestId = int.Parse(csv["stop_id"]);
                    }
                    loc.Dispose();
                }
            }
            return((closestId == -1)?null:getStopInfo(closestId));
        }
        public double Distance(double lat, double lng, XLocation b)
        {
            var firstPoint = new CLLocation(lat, lng);
            var secondPoint = new CLLocation(b.Latitude, b.Longitude);

            return firstPoint.DistanceFrom(secondPoint);
        }
		//Metodo de busqueda de la tienda mas cercana.
		public StoresService nearestStore(CLLocation location, List<StoresService> stores){
			StoresService nearStore = stores.ElementAt (0);
			foreach (StoresService store in stores) {
				if( (location.DistanceFrom(new CLLocation(Double.Parse(store.latitud),Double.Parse(store.longitud)))) < (location.DistanceFrom(new CLLocation(Double.Parse(nearStore.latitud), Double.Parse(nearStore.longitud)))) ) {
					nearStore = store;
				}
			}
			return nearStore;
		}
		//Metodo de busqueda de la tienda mas cercana.
		public ProductSearchDetailService nearestStore(CLLocation location, List<ProductSearchDetailService> stores){
			Console.WriteLine (""+location.Coordinate.Latitude);
			ProductSearchDetailService nearStore = stores.ElementAt (0);
			foreach (ProductSearchDetailService store in stores) {
				if( (location.DistanceFrom(new CLLocation(Double.Parse(store.tienda_latitud),Double.Parse(store.tienda_longitud)))) < (location.DistanceFrom(new CLLocation(Double.Parse(nearStore.tienda_latitud), Double.Parse(nearStore.tienda_longitud)))) ) {
					nearStore = store;
				}
			}
			return nearStore;
		}
		static public void UpdateLocation (IMainScreen ms, CLLocation newLocation)
		{
			ms.LblAltitude.Text = newLocation.Altitude.ToString () + " meters";
			ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString () + "º";
			ms.LblLatitude.Text = newLocation.Coordinate.Latitude.ToString () + "º";
			ms.LblCourse.Text = newLocation.Course.ToString () + "º";
			ms.LblSpeed.Text = newLocation.Speed.ToString () + " meters/s";
			
			// get the distance from here to paris
			ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km";
		}