Exemplo n.º 1
0
    public GeoPoint(float lat, float lon, float alt, GeoCalculator.DistanceUnits altUnit = GeoCalculator.DistanceUnits.Kilofeet)
    {
        _lat = lat;
        _lon = lon;

        switch (altUnit)
        {
        case GeoCalculator.DistanceUnits.Feet:
            this._alt = (float)GeoCalculator.ConvertDistanceUnit(alt, GeoCalculator.DistanceUnits.Feet, GeoCalculator.DistanceUnits.Degrees);
            break;

        case GeoCalculator.DistanceUnits.Kilofeet:
            this._alt = (float)GeoCalculator.ConvertDistanceUnit(alt, GeoCalculator.DistanceUnits.Kilofeet, GeoCalculator.DistanceUnits.Degrees);
            break;

        case GeoCalculator.DistanceUnits.NauticalMiles:
            this._alt = (float)GeoCalculator.ConvertDistanceUnit(alt, GeoCalculator.DistanceUnits.NauticalMiles, GeoCalculator.DistanceUnits.Degrees);
            break;

        case GeoCalculator.DistanceUnits.Degrees:
            this._alt = alt;
            break;

        case GeoCalculator.DistanceUnits.Meters:
            this._alt = (float)GeoCalculator.ConvertDistanceUnit(alt, GeoCalculator.DistanceUnits.Meters, GeoCalculator.DistanceUnits.Degrees);
            break;

        default:
            throw new FormatException("Geopoint could not be constructed with the given Distance Units input");
        }
    }
        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"
            });
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        public double CalcularDistancia()
        {
            int casasDecimais = 1;

            return(GeoCalculator.GetDistance(Origem.Latitude, Origem.Longitude,
                                             Destino.Latitude, Destino.Longitude, casasDecimais, DistanceUnit.Miles));
        }
        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
            {
            }
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
0
        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));
        }
Exemplo n.º 8
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));
    }
Exemplo n.º 9
0
    public void GetScalebarDistanceParams(out float d1, out float d2, out float d, out int number, out string unit)
    {
        d1 = (float)GeoCalculator.PixelsToMetes(minSize, canvas.scaleFactor, map.zoom);
        d2 = (float)GeoCalculator.PixelsToMetes(maxSize, canvas.scaleFactor, map.zoom);

        d = GetNumberAndUnit(d2, out number, out unit);
    }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
    private void UpdateMapBounds()
    {
        // Convert view bounds (in Unity units) to tile ids
        int northId = anchor.Y - Mathf.CeilToInt((viewBounds.yMax - anchorOffsetInUnits.y) * unitsToTiles + verticalBuffer);
        int southId = anchor.Y - Mathf.FloorToInt((viewBounds.yMin - anchorOffsetInUnits.y) * unitsToTiles - verticalBuffer);
        int westId  = anchor.X + Mathf.FloorToInt((viewBounds.xMin - anchorOffsetInUnits.x) * unitsToTiles - horizontalBuffer);
        int eastId  = anchor.X + Mathf.CeilToInt((viewBounds.xMax - anchorOffsetInUnits.x) * unitsToTiles + horizontalBuffer);

        mapTileBounds.Set(northId, southId, westId, eastId);

        // Update coordinate bounds (in degrees)
        var offsetMeters = GeoCalculator.RelativePixelsToMeters(viewBounds.xMax * unitsToPixels, viewBounds.yMax * unitsToPixels, zoomLevel);
        var LonLat       = GeoCalculator.MetersToLonLat(currentMeters + offsetMeters);

        mapCoordBounds.east  = LonLat.Longitude;
        mapCoordBounds.north = LonLat.Latitude;
        offsetMeters         = GeoCalculator.RelativePixelsToMeters(viewBounds.xMin * unitsToPixels, viewBounds.yMin * unitsToPixels, zoomLevel);
        LonLat = GeoCalculator.MetersToLonLat(currentMeters + offsetMeters);
        mapCoordBounds.west  = LonLat.Longitude;
        mapCoordBounds.south = LonLat.Latitude;

        if (OnBoundsChange != null)
        {
            OnBoundsChange();
        }
    }
Exemplo n.º 12
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)));
        }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
0
    private void UpdateProjectionValues()
    {
        if (grid.countY == 0)
        {
            return;
        }

        int count = grid.countY + 1;

        if (projection == null || projection.width != count)
        {
            CreateProjectionBuffer(count);
        }

        double min         = GeoCalculator.LatitudeToNormalizedMercator(grid.south);
        double max         = GeoCalculator.LatitudeToNormalizedMercator(grid.north);
        double invLatRange = (1.0 / (grid.north - grid.south));

        float[] lats            = new float[count];
        double  projLatInterval = (max - min) / (count - 1);

        for (int i = 0; i < count; i++)
        {
            double projLat = min + i * projLatInterval;
            double lat     = (2 * Math.Atan(Math.Exp(projLat * Math.PI)) - HalfPI) * Rad2Deg;
            lats[i] = Mathf.Clamp01((float)(1 - (lat - grid.south) * invLatRange));
        }
        byte[] latBytes = new byte[lats.Length * 4];
        Buffer.BlockCopy(lats, 0, latBytes, 0, latBytes.Length);
        projection.LoadRawTextureData(latBytes);
        projection.Apply();
    }
Exemplo n.º 15
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));
        }
Exemplo n.º 16
0
        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()));
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
    private void UpdateCenter(double lon, double lat)
    {
        // Wrap coordinate
        while (lon < GeoCalculator.MinLongitude)
        {
            lon += 2 * GeoCalculator.MaxLongitude;
        }
        while (lon > GeoCalculator.MaxLongitude)
        {
            lon += 2 * GeoCalculator.MinLongitude;
        }
        while (lat < GeoCalculator.MinLatitude)
        {
            lat += 2 * GeoCalculator.MaxLatitude;
        }
        while (lat > GeoCalculator.MaxLatitude)
        {
            lat += 2 * GeoCalculator.MinLatitude;
        }

        // Update lon/lat location
        longitude     = lon;
        latitude      = lat;
        currentMeters = GeoCalculator.LonLatToMeters(longitude, latitude);
    }
Exemplo n.º 19
0
    public override void UpdateContent()
    {
        bounds = map.MapCoordBounds;

        if (degrees)
        {
            UpdateProjectionValues();
        }
        else
        {
            // Convert Lon/Lat to meters
            var meters = GeoCalculator.LonLatToMeters(bounds.east, bounds.north);
            bounds.east  = meters.x;
            bounds.north = meters.y;
            meters       = GeoCalculator.LonLatToMeters(bounds.west, bounds.south);
            bounds.west  = meters.x;
            bounds.south = meters.y;
        }

        var invBoundsX = 1.0 / (bounds.east - bounds.west);
        var invBoundsY = 1.0 / (bounds.north - bounds.south);
        var interval   = new Vector4((float)(intervalX * invBoundsX), (float)(intervalY * invBoundsY), 0, 0);
        var offsetX    = (float)(((0.5f * (bounds.east + bounds.west)) % intervalX) * invBoundsX);
        var offsetY    = (float)(((0.5f * (bounds.north + bounds.south)) % intervalY) * invBoundsY);
        var offset     = new Vector4(offsetX, offsetY, 0, 0);

        if (degrees)
        {
            offset.y = -offset.y;
        }

        material.SetVector("Interval", interval);
        material.SetVector("Offset", offset);
    }
Exemplo n.º 20
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 });
        }
Exemplo n.º 21
0
 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);
 }
Exemplo n.º 22
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));
        }
Exemplo n.º 23
0
        public static Expression <Func <T, double> > CalculateDistanceFrom <T>(double originLatitude, double originLongitude, string latitudePropertyName, string longitudePropertyName, DistanceUnit distanceUnit)
        {
            var earthsRadiusConstantExpression = Expression.Constant(GeoCalculator.GetRadius(distanceUnit));
            var inputExpression           = Expression.Parameter(typeof(T), "x");
            var originLatitudeExpression  = Expression.Constant(originLatitude);
            var originLongitudeExpression = Expression.Constant(originLongitude);

            var destinationLatitudeExpression  = Expression.Convert(Expression.Property(inputExpression, latitudePropertyName), typeof(double));
            var destinationLongitudeExpression = Expression.Convert(Expression.Property(inputExpression, longitudePropertyName), typeof(double));

            if (originLatitude < -90 || originLatitude > 90 || originLongitude < -180 || originLongitude > 180)
            {
                return(Expression.Lambda <Func <T, double> >(Expression.Constant(-1.0), inputExpression));
            }

            return(Expression.Lambda <Func <T, double> >(
                       Expression.Multiply(
                           earthsRadiusConstantExpression,
                           Expression.Multiply(
                               Expression.Constant(2.0),
                               Expression.Call(_asin,
                                               // MIN isn't supported in SQL
                                               // Tested all (4B+) combinations of valid Lat/Long and calculation was never greater than 1
                                               //Expression.Call(_min,
                                               //    Expression.Constant(1.0),
                                               Expression.Call(_sqrt,
                                                               Expression.Add(
                                                                   Expression.Call(_pow,
                                                                                   Expression.Call(_sin,
                                                                                                   Expression.Divide(
                                                                                                       originLatitudeExpression.DiffRadiansExpression(destinationLatitudeExpression),
                                                                                                       Expression.Constant(2.0)
                                                                                                       )
                                                                                                   ),
                                                                                   Expression.Constant(2.0)
                                                                                   ),
                                                                   Expression.Multiply(
                                                                       Expression.Call(_cos, originLatitudeExpression.ToRadiansExpression()),
                                                                       Expression.Multiply(
                                                                           Expression.Call(_cos, destinationLatitudeExpression.ToRadiansExpression()),
                                                                           Expression.Call(_pow,
                                                                                           Expression.Call(_sin,
                                                                                                           Expression.Divide(
                                                                                                               originLongitudeExpression.DiffRadiansExpression(destinationLongitudeExpression),
                                                                                                               Expression.Constant(2.0)
                                                                                                               )
                                                                                                           ),
                                                                                           Expression.Constant(2.0)
                                                                                           )
                                                                           )
                                                                       )
                                                                   )
                                                               )
                                               //)
                                               )
                               )
                           ),
                       inputExpression));
        }
Exemplo n.º 24
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);
        }
    private static Coordinate CalcActiveSiteCenter()
    {
        var bounds = GetActiveSiteAreaBounds();
        var max    = GeoCalculator.LonLatToMeters(bounds.east, bounds.north);
        var min    = GeoCalculator.LonLatToMeters(bounds.west, bounds.south);
        var center = GeoCalculator.MetersToLonLat((min.x + max.x) * 0.5, (min.y + max.y) * 0.5);

        return(center);
    }
Exemplo n.º 26
0
        public void GetBearingThrowsArgumentExceptionWithInvalidOriginCoordinates()
        {
            Coordinate origin      = Constants.Coordinates.LatitudeBelowMinimum;
            Coordinate destination = Constants.Coordinates.ValidCoordinate;

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

            Assert.AreEqual("Invalid origin coordinates supplied.", ex.Message);
        }
 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);
     }
 }
Exemplo n.º 28
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));
        }
        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(ex.Message, "Invalid destination coordinates supplied.");
        }
Exemplo n.º 30
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);
        }