Example #1
0
        public async Task <ObjectResult> GetMatches()
        {
            string          userId      = sessionService.GetCurrentUserId();
            ApplicationUser currentUser = await userRepository.GetUserAccount(userId);

            IEnumerable <string> matchIds = matchRepository.GetMatches(userId);
            List <ReturnedUser>  matches  = new List <ReturnedUser>();

            foreach (string id in matchIds)
            {
                ApplicationUser match = await userRepository.GetUserAccount(id);

                ReturnedUser matchResponse = new ReturnedUser
                {
                    Id         = match.Id,
                    Username   = match.UserName,
                    Name       = match.Name != null && match.Name.Length != 0 ? match.Name : match.UserName,
                    Picture    = match.Picture,
                    Bio        = match.Bio,
                    LookingFor = match.LookingFor,
                    Genres     = match.Genres.Select(ug => ug.Genre.Name).ToArray(),
                    Venues     = match.Venues.Select(uv => uv.Venue.Name).ToArray(),
                    Distance   = GeoCalculator.GetDistance(currentUser.Lat, currentUser.Lon, match.Lat, match.Lon),
                    Role       = await userRepository.GetAcountRole(match.Id)
                };

                matches.Add(matchResponse);
            }

            return(Ok(matches));
        }
        public async Task <Response> MeasureDistance
            (Location location1, Location location2)
        {
            Response measureResponse;

            //check input coordinats is Double
            if (IsDouble(location1.Lat, location1.Long) &&
                IsDouble(location2.Lat, location2.Long))
            {
                double distance = GeoCalculator.
                                  GetDistance(
                    double.Parse(location1.Lat),
                    double.Parse(location1.Long),
                    double.Parse(location2.Lat),
                    double.Parse(location2.Long), 1);
                measureResponse = new MeasureResponse()
                {
                    Location1 = location1,
                    Location2 = location2,
                    Distance  = distance,
                    Code      = StatusCodes.Status200OK,
                    Message   = "Ok"
                };

                return(measureResponse);
            }

            return(new Response()
            {
                Code = StatusCodes.Status500InternalServerError,
                Message = "Input Location Coordinates is Incorrect"
            });
        }
        public async Task <MeasureResponse> MeasureDistance
            (Location location1, Location location2)
        {
            MeasureResponse measureResponse;

            if (IsDouble(location1.Latitude, location1.Longitude) &&
                IsDouble(location2.Latitude, location2.Longitude))
            {
                double distance = GeoCalculator.
                                  GetDistance(
                    double.Parse(location1.Latitude),
                    double.Parse(location1.Longitude),
                    double.Parse(location2.Latitude),
                    double.Parse(location2.Longitude), 1);
                measureResponse = new MeasureResponse()
                {
                    Location1 = location1,
                    Location2 = location2,
                    Distance  = distance,
                    Code      = StatusCodes.Status200OK,
                    Message   = "Ok"
                };

                return(measureResponse);
            }
            else
            {
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            var path = Environment.CurrentDirectory + "\\Taco_Bell-US-AL-Alabama.csv";

            Logger.Info("Log initialized");
            Logger.Info("Grabbing from path: " + path);

            var lines = File.ReadAllLines(path);

            if (lines.Length == 0)
            {
                Logger.Error("No locations to check. Must have at least one location.");
            }
            else if (lines.Length == 1)
            {
                Logger.Warn("Only one location provided. Must have two to perform a check");
            }
            var parser = new TacoParser();

            Logger.Info(("Initialized our Parser"));

            var locations = lines.Select(line => parser.Parse(line))
                            .OrderBy(loc => loc.Location.Longitude)
                            .ThenBy(loc => loc.Location.Latitude)
                            .ToArray();

            ITrackable a        = null;
            ITrackable b        = null;
            double     distance = 0;

            foreach (var locA in locations)
            {
                var origin = new Coordinate
                {
                    Latitude  = locA.Location.Latitude,
                    Longitude = locA.Location.Longitude
                };

                foreach (var locB in locations)
                {
                    var dest = new Coordinate
                    {
                        Latitude  = locB.Location.Latitude,
                        Longitude = locB.Location.Longitude
                    };

                    var nDist = GeoCalculator.GetDistance(origin, dest);

                    if (nDist > distance)
                    {
                        distance = nDist;
                        a        = locA;
                        b        = locB;
                    }
                }
            }

            Console.WriteLine($"The first Taco Bell location is {a.Name} and the furthest distance away {b.Name}, with a distance of {distance}");
            Console.ReadLine();
        }
        private IEnumerable <ResultModel> GetResults(Coordinate originCoordinate, double radius, DistanceUnit distanceUnit)
        {
            // Get the boundaries (min and max) latitude and longitude values. This forms a "square" around the origin coordinate
            // with each leg of the square exactly "X" miles from the origin, where X is the selected radius.
            var boundaries = new CoordinateBoundaries(originCoordinate.Latitude, originCoordinate.Longitude, radius, distanceUnit);

            // Select from all of the locations
            return(Locations
                   // Where the location's latitude is between the min and max latitude boundaries
                   .Where(x => x.Latitude >= boundaries.MinLatitude && x.Latitude <= boundaries.MaxLatitude)
                   // And where the location's longitude is between the min and max longitude boundaries
                   .Where(x => x.Longitude >= boundaries.MinLongitude && x.Longitude <= boundaries.MaxLongitude)
                   // Populate an instance of the Result class with the desired data, including distance/direction calculation
                   .Select(result => new ResultModel
            {
                Name = result.Name,
                Distance = GeoCalculator.GetDistance(originCoordinate.Latitude, originCoordinate.Longitude, result.Latitude, result.Longitude, distanceUnit: distanceUnit),
                Direction = GeoCalculator.GetDirection(originCoordinate.Latitude, originCoordinate.Longitude, result.Latitude, result.Longitude)
            })
                   // Filter by distance. This is necessary because a radius is a circle, yet we've defined a square around the origin coordinate.
                   // This filter removes any extraneous results that would appear in the square's "corners" (imagine placing a circle inside a square of the
                   // same size for visualization).
                   .Where(x => x.Distance <= radius)
                   // Sort by distance
                   .OrderBy(x => x.Distance));
        }
Example #6
0
        public static GeolocationPlace[] GetUserCurrentLocations(IGeolocationTarget[] users, string userId, string deviceName)
        {
            var user = users.FirstOrDefault(x => x.Id.Equals(userId));

            if (user == null)
            {
                return new GeolocationPlace[] { GeolocationPlace.Empty }
            }
            ;
            var userLocations = GetNonGpsLocations(user, deviceName);

            if (!userLocations.Any())
            {
                return new GeolocationPlace[] { GeolocationPlace.Other }
            }
            ;
            var userLastLocation = userLocations.Last();
            var places           = PlacesManager.Current.Places.OrderBy(x => x.MetersRadious).ToArray();
            var targetPlaces     = places.Where(x =>
                                                GeoCalculator.GetDistance(
                                                    x.Location.Latitude, x.Location.Longtitude,
                                                    userLastLocation.Geolocation.Latitude, userLastLocation.Geolocation.Longtitude,
                                                    1,
                                                    DistanceUnit.Meters) <= x.MetersRadious)
                                   .OrderBy(x => x.MetersRadious)
                                   .ToArray();

            return(targetPlaces.Any() ? targetPlaces : new GeolocationPlace[] { GeolocationPlace.Other });
        }
Example #7
0
        public double CalcularDistancia()
        {
            int casasDecimais = 1;

            return(GeoCalculator.GetDistance(Origem.Latitude, Origem.Longitude,
                                             Destino.Latitude, Destino.Longitude, casasDecimais, DistanceUnit.Miles));
        }
Example #8
0
        public async Task <ObjectResult> GetSuggestions()
        {
            string          userId = sessionService.GetCurrentUserId();
            ApplicationUser user   = await userRepository.GetUserAccount(userId);

            CoordinateBoundaries boundaries = new CoordinateBoundaries(user.Lat, user.Lon, user.MatchRadius, DistanceUnit.Kilometers);

            IEnumerable <ApplicationUser> matchesInRadius = await suggestionsRepository.GetUsersInMatchRadius(boundaries.MinLatitude, boundaries.MaxLatitude, boundaries.MinLongitude, boundaries.MaxLongitude);

            IEnumerable <string> previouslyRespondedSuggestionsIds = suggestionsRepository.GetPreviousSuggestions(userId);

            IEnumerable <ReturnedUser> suggestedUsers = matchesInRadius.Select(x => new ReturnedUser
            {
                Id         = x.Id,
                Username   = x.UserName,
                Name       = x.Name != null && x.Name.Length != 0 ? x.Name : x.UserName,
                Picture    = x.Picture,
                Bio        = x.Bio,
                LookingFor = x.LookingFor,
                Genres     = x.Genres.Select(ug => ug.Genre.Name).ToArray(),
                Venues     = x.Venues.Select(uv => uv.Venue.Name).ToArray(),
                Distance   = GeoCalculator.GetDistance(user.Lat, user.Lon, x.Lat, x.Lon)
            }).ToList()
                                                        .Where(x => x.Id != user.Id)
                                                        .Where(x => !previouslyRespondedSuggestionsIds.Contains(x.Id))
                                                        .Where(x => x.Distance <= user.MatchRadius)
                                                        .OrderBy(x => x.Distance);

            foreach (ReturnedUser u in suggestedUsers)
            {
                u.Role = await userRepository.GetAcountRole(u.Id);
            }

            return(Ok(suggestedUsers));
        }
 public IEnumerable <Post> GetPostsInRange([FromBody] Location model)
 {
     if (ModelState.IsValid)
     {
         var userId = HttpContext.User.GetUserId();
         var user   = _context.User.FirstOrDefault(x => x.Id == userId);
         //CoordinateBoundaries boundaries = new CoordinateBoundaries(model.Latitude, model.Longitude, user.SearchRange/1.6);
         //var posts = _context.Post.AsQueryable();
         //var result = posts.Where(
         //        x => x.Latitude >= boundaries.MinLatitude && x.Latitude <= boundaries.MaxLatitude)
         //    .Where(x => x.Longitude >= boundaries.MinLongitude && x.Longitude <= boundaries.MaxLongitude);
         //range - dystans w kilometrach
         //GeoCalculation.GetDistance(...) - zwraca dystans w milach => 1 mila = 1.6 km
         var posts = (from p in _context.Post.Include(p => p.PostTags)
                      let range = user.SearchRange / 1000
                                  where
                                  range >=
                                  GeoCalculator.GetDistance(model.Latitude, model.Longitude, p.Latitude, p.Longitude, 5) / 1.6
                                  orderby p.AddDate descending
                                  select p
                      ).ToList();
         for (int i = 0; i < posts.Count; i++)
         {
             posts[i].user = _context.User.FirstOrDefault(x => x.Id == posts[i]._UserId);
         }
         //range - dystans w kilometrach
         //GeoCalculation.GetDistance(...) - zwraca dystans w milach => 1 mila = 1.6 km
         //var result = _context.Post.Include(x => x.user).Where(x => x.user.SearchRange / 100 >= GeoCalculator.GetDistance(model.Latitude, model.Longitude, x.Latitude, x.Longitude, 5) / 1.6);
         return(posts);
     }
     return(null);
 }
        public IActionResult Index(string searchString, double lat, double lng, float radius)
        {
            IEnumerable <Event> events = new List <Event>();

            try
            {
                events = _eventRepository.GetEvents().Result;
            }
            catch (TimeoutException)
            {
                return(RedirectToAction("Error"));
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                events = events.Where(e => e.Name.ToLower().Contains(searchString.ToLower()) || e.Description.ToLower().Contains(searchString.ToLower()));
            }

            foreach (var item in events)
            {
                item.Image       = _imageRepository.GetImage(item.Id);
                item.EventStatus = _eventRepository.CheckStatus(item);
            }

            if (!Double.IsNaN(lat) && !Double.IsNaN(lng) && lat != 0 && lng != 0)
            {
                events = events.Where(e => GeoCalculator.GetDistance(e.Lat, e.Long, lat, lng, 1, DistanceUnit.Kilometers) <= radius);
            }

            return(View(events.ToList()));
        }
Example #11
0
        public async Task <DroneDTO> DroneAtendePedido(Pedido pedido)
        {
            double latitudeSaidaDrone  = -23.5880684;
            double longitudeSaidaDrone = -46.6564195;

            double distance = GeoCalculator.GetDistance(latitudeSaidaDrone, longitudeSaidaDrone, pedido.Latitude, pedido.Longitude, 1, DistanceUnit.Kilometers) * 2;

            _droneService.GerenciarDrones();

            var drones = await _droneService.GetDisponiveis();

            var buscaDrone = drones.Where(d => d.PerformanceRestante >= distance && d.CapacidadeRestante >= pedido.Peso).FirstOrDefault();

            if (buscaDrone == null)
            {
                return(null);
            }

            buscaDrone.PerformanceRestante -= (float)distance;
            buscaDrone.CapacidadeRestante  -= pedido.Peso;
            buscaDrone.Situacao             = (int)EStatusDrone.AGUARDANDO;

            if ((buscaDrone.CapacidadeRestante <= (buscaDrone.Capacidade * 0.5)) || (buscaDrone.PerformanceRestante <= (buscaDrone.Perfomance * 0.5)))
            {
                buscaDrone.Situacao = (int)EStatusDrone.OCUPADO;
            }

            _droneService.Update(buscaDrone);

            return(new DroneDTO(buscaDrone, distance));
        }
Example #12
0
        public async Task <List <PoiDto> > ListClosestPoisAsync(SearchPoiDto search)
        {
            if (search == null)
            {
                throw new ArgumentNullException(nameof(search));
            }

            IQueryable <Poi> query = DbContext.Pois;

            //TODO: null-t nem engedni
            IPoint location = null;

            //order by distance
            if (search.Longitude.HasValue && search.Latitude.HasValue)
            {
                location = LocationManager.GeometryFactory.CreatePoint(new GeoAPI.Geometries.Coordinate(search.Longitude.Value, search.Latitude.Value));
                //TODO: valszeg ez nem marad szimplan query
                query = query.OrderBy(p => p.Location.Distance(location));
            }

            var result = await query.Select(x => new { Poi = x, Distance = location != null ? x.Location.Distance(location) : 0 }).ToListAsync();

            var pois = Mapper.Map <List <PoiDto> >(result.Select(r => r.Poi).ToList());

            pois.ForEach(t => t.Distance = GeoCalculator.GetDistance(location.Y, location.X, t.Latitude, t.Longitude, 1, DistanceUnit.Kilometers));

            return(pois);
        }
Example #13
0
    public double DistanceTo(IataPoint destinationPoint)
    {
        var origin      = new Coordinate(this.Location.Latitude, this.Location.Longitude);
        var destination = new Coordinate(destinationPoint.Location.Latitude, destinationPoint.Location.Longitude);

        return(GeoCalculator.GetDistance(origin, destination));
    }
Example #14
0
        public ActionResult <IEnumerable <PacijentReadDTO> > GetAllPacijenti()
        {
            var pacijenti = _repository.GetAllPacijenti();

            foreach (var pacijent in pacijenti)
            {
                var stanje           = _stanjeRepo.GetLastStanjeByID(pacijent.Id);
                var udaljenost       = 0d;
                var trenutnaLokacija = _lokacijaRepo.GetLastLokacijeByID(pacijent.Id);
                if (trenutnaLokacija?.Id != null && trenutnaLokacija?.Id != 0)
                {
                    var TL = new Coordinate(Convert.ToDouble(trenutnaLokacija.Lat), Convert.ToDouble(trenutnaLokacija.Long));
                    var SI = new Coordinate(Convert.ToDouble(pacijent.Lat), Convert.ToDouble(pacijent.Long));
                    udaljenost = GeoCalculator.GetDistance(TL, SI, 5) / 0.62137;
                }

                if (stanje?.Temperatura > 37)
                {
                    pacijent.Stanje = "Visoka temp.";
                }
                else if (udaljenost > 1)
                {
                    pacijent.Stanje = "Udaljen više od 1km";
                }
                else
                {
                    pacijent.Stanje = "Ok";
                }
            }
            return(Ok(_mapper.Map <IEnumerable <PacijentReadDTO> >(pacijenti)));
        }
Example #15
0
        /// <summary>
        /// Uses https://www.nuget.org/packages/Geolocation/
        /// </summary>
        public void Test()
        {
            var landsEndLocation    = new Coordinate(50.0775475, -5.6352355);
            var johnOGroatsLocation = new Coordinate(58.6366688, -3.0827024);

            double distance = GeoCalculator.GetDistance(landsEndLocation, johnOGroatsLocation, 1, DistanceUnit.Kilometers);
        }
Example #16
0
        public static IAirportDistanceMap FromAirports(List <AlgorithmAirport> airports)
        {
            if (airports == null || !airports.Any())
            {
                throw new ArgumentException(nameof(airports));
            }

            var len    = airports.Count();
            var result = new AirportDistanceMap()
            {
                _map = new Dictionary <AlgorithmAirport, Dictionary <AlgorithmAirport, double> >(len),
            };

            foreach (var fromAirport in airports)
            {
                result._map[fromAirport] = new Dictionary <AlgorithmAirport, double>(len);

                foreach (var destinationAirport in airports)
                {
                    result._map[fromAirport][destinationAirport] = GeoCalculator.GetDistance(fromAirport.Coordinate, destinationAirport.Coordinate, distanceUnit: DistanceUnit.Kilometers);
                }
            }

            return(result);
        }
Example #17
0
        /// <summary>
        /// Method to get the distance in miles between to sets of coordinates
        /// </summary>
        /// <param name="lat1"> Double of the first locations latitude </param>
        /// <param name="long1"> Double of the first locations longitude </param>
        /// <param name="lat2"> Double of the second locations latitude </param>
        /// <param name="long2"> Double of the second locations longitude </param>
        /// <returns> Double representing the distance between the 2 given locations in miles </returns>
        public static double GetDistanceBetweenTwoLocations(double lat1, double long1, double lat2, double long2)
        {
            Coordinate location1 = new Coordinate(lat1, long1);
            Coordinate location2 = new Coordinate(lat2, long2);
            double     distance  = GeoCalculator.GetDistance(location1, location2, 1);

            return(distance);
        }
Example #18
0
        public async Task <double> Calculate(string from, string to)
        {
            var fromAirport = await airportClient.GetAirportData(from);

            var toAirport = await airportClient.GetAirportData(to);

            return(GeoCalculator.GetDistance(fromAirport.location.lat, fromAirport.location.lon,
                                             toAirport.location.lat, toAirport.location.lon, 1));
        }
Example #19
0
        private double GetDistanceBetweenPersons(Person person1, Person person2)
        {
            var person1Location = new Coordinate(person1.Address.Geo.Lat, person1.Address.Geo.Lng);
            var person2Location = new Coordinate(person2.Address.Geo.Lat, person2.Address.Geo.Lng);

            var distance = GeoCalculator.GetDistance(person1Location, person2Location);

            return(distance);
        }
        public bool IsInRange(ApplicationUser volunteer, ApplicationUser beneficiary)
        {
            Coordinate volunteerCoordinates   = new Coordinate(volunteer.Latitude, volunteer.Longitude);
            Coordinate beneficiaryCoordinates = new Coordinate(beneficiary.Latitude, beneficiary.Longitude);

            double distance = GeoCalculator.GetDistance(volunteerCoordinates, beneficiaryCoordinates, 15, DistanceUnit.Kilometers);

            return(distance <= (double)volunteer.RangeInKm);
        }
 public Task <MeasureResponse> MeasureDistance
     (Location location1, Location location2)
 {
     if (IsDouble(location1.Latitude, location1.Longitude) &&
         IsDouble(location2.Latitude, location2.Longitude))
     {
         double distance = GeoCalculator.GetDistance(34.0675918, -118.3977091, 34.076234, -118.395314, 1);
     }
 }
        public void GetDistanceThrowsArgumentExceptionWithInvalidDestinationCoordinates()
        {
            Coordinate origin      = Constants.Coordinates.ValidCoordinate;
            Coordinate destination = Constants.Coordinates.LatitudeBelowMinimum;

            var ex = Assert.Throws <ArgumentException>(() => GeoCalculator.GetDistance(origin.Latitude, origin.Longitude, destination.Latitude, destination.Longitude, 1));

            Assert.AreEqual("Invalid destination coordinates supplied.", ex.Message);
        }
        public void GetDistanceReturnsCorrectResult()
        {
            Coordinate origin      = Constants.Coordinates.ValidCoordinate;
            Coordinate destination = Constants.Coordinates.ValidDestinationCoordinate;

            double       distance       = GeoCalculator.GetDistance(origin.Latitude, origin.Longitude, destination.Latitude, destination.Longitude, 1);
            const double expectedResult = 75.4;

            Assert.AreEqual(distance, expectedResult);
        }
        public void GetDistanceWithCoordinateObjectReturnsCorrectResult()
        {
            Coordinate origin      = Constants.Coordinates.ValidCoordinate;
            Coordinate destination = Constants.Coordinates.ValidDestinationCoordinate;

            double       distance       = GeoCalculator.GetDistance(origin, destination);
            const double expectedResult = 75.5;

            Assert.AreEqual(expectedResult, distance);
        }
        public void GetDistanceReturnsCorrectResultInMeters()
        {
            Coordinate origin      = Constants.Coordinates.ValidCoordinate;
            Coordinate destination = Constants.Coordinates.ValidDestinationCoordinate;

            double       distance       = GeoCalculator.GetDistance(origin.Latitude, origin.Longitude, destination.Latitude, destination.Longitude, distanceUnit: DistanceUnit.Meters);
            const double expectedResult = 121493.3;

            Assert.AreEqual(expectedResult, distance);
        }
 public Trecho(string nome, Local localA, Local localB)
 {
     this.Nome      = nome;
     this.LocalA    = localA;
     this.LocalB    = localB;
     this.Distancia = GeoCalculator.GetDistance(
         LocalA.LatitudeLocal, LocalA.LongitudeLocal,
         LocalB.LatitudeLocal, LocalB.LongitudeLocal,
         1);
 }
 public void Atualizar(Trecho trechoAlterado)
 {
     this.Nome      = trechoAlterado.Nome;
     this.Distancia = GeoCalculator.GetDistance(
         LocalA.LatitudeLocal, LocalA.LongitudeLocal,
         LocalB.LatitudeLocal, LocalB.LongitudeLocal,
         1);
     this.LocalA = trechoAlterado.LocalA;
     this.LocalB = trechoAlterado.LocalB;
 }
        public async Task <double> DistanceBetween(IataAirportCode origin, IataAirportCode dest)
        {
            var originLocation = await _airportLocationProvider.LocationOf(origin);

            var destLocation = await _airportLocationProvider.LocationOf(dest);

            var distance = GeoCalculator.GetDistance(originLocation, destLocation, distanceUnit: DistanceUnit.Kilometers);

            return(distance);
        }
Example #29
0
        private void DistanceFromISSToYouButton_Click(object sender, EventArgs e)
        {
            var userLat = 0.0;
            var userLon = 0.0;
            var ISSLati = 0.0;
            var ISSLong = 0.0;

            DistanceFromISSToYouText.Text = "" + (GeoCalculator.GetDistance(myLat(userLat), myLon(userLon), ISSLat(ISSLati), ISSLon(ISSLong)) + " miles.");
            //save here
        }
Example #30
0
 public double GetKmDistance(Point originPoint, Point destPoint)
 {
     return(GeoCalculator.GetDistance(
                originPoint.Latitude,
                originPoint.Longitude,
                destPoint.Latitude,
                destPoint.Longitude,
                1,
                DistanceUnit.Kilometers));
 }