Exemplo n.º 1
0
        public async Task <OperationResult <IEnumerable <@event> > > Search(LocationCoordinates location, string[] tags)
        {
            if (location != null && location.isEmpty())
            {
                new OperationResult <IEnumerable <@event> >()
                {
                    Success = false, Message = Messages.MISSING_LOCATION
                }
            }
            ;

            var box = CoordinatesBoundingBox.GetBoundingBox(new CoordinatesBoundingBox.MapPoint {
                Longitude = location.longitude, Latitude = location.latitude
            }, location.radius);

            IEnumerable <@event> events = await eventRepo.GetByParamsAsync(new CoordinatesRange { MaxLatitude = box.MaxPoint.Latitude, MaxLongitude = box.MaxPoint.Longitude, MinLatitude = box.MinPoint.Latitude, MinLongitude = box.MinPoint.Longitude }, tags);

            if (events != null)
            {
                return(new OperationResult <IEnumerable <@event> >()
                {
                    Success = true, Message = Messages.EVENTS_SUCCESS, Result = events
                });
            }
            return(new OperationResult <IEnumerable <@event> >()
            {
                Success = false, Message = Messages.EVENT_NOT_EXIST
            });
        }
        public static WeatherData GetCurrentWeatherData(LocationCoordinates location, out WeatherAPIError weatherAPIError)
        {
            string url;

            StringBuilder sb = new StringBuilder();

            sb.Clear();
            sb.Append("http://api.openweathermap.org/data/2.5/weather?");
            sb.Append("&lat=" + location.Latitude + "&lon=" + location.Longitude);
            sb.Append("&appid=668f986bf179bbac7174d55d13ad1a71");

            url = sb.ToString();

            WeatherData currentWeather = new WeatherData();

            try
            {
                string result = null;

                using (WebClient syncClient = new WebClient())
                {
                    result = syncClient.DownloadString(url);
                }

                currentWeather           = JsonConvert.DeserializeObject <WeatherData>(result);
                currentWeather.Main.Temp = Math.Round(ConvertToFahrenheit(currentWeather.Main.Temp));
                weatherAPIError          = WeatherAPIError.VALID;
            }
            catch (Exception)
            {
                weatherAPIError = WeatherAPIError.INVALID;
            }

            return(currentWeather);
        }
Exemplo n.º 3
0
        public async Task <OperationResult <IEnumerable <community> > > Search(LocationCoordinates location, string name, string[] tags)
        {
            if (location != null && location.isEmpty())
            {
                new OperationResult <IEnumerable <community> >()
                {
                    Success = false, Message = Messages.MISSING_LOCATION
                }
            }
            ;

            var box = CoordinatesBoundingBox.GetBoundingBox(new CoordinatesBoundingBox.MapPoint {
                Longitude = location.longitude, Latitude = location.latitude
            }, location.radius);

            IEnumerable <community> communities = await communityRepo.GetByParamsAsync(new CoordinatesRange { MaxLatitude = box.MaxPoint.Latitude, MaxLongitude = box.MaxPoint.Longitude, MinLatitude = box.MinPoint.Latitude, MinLongitude = box.MinPoint.Longitude }, name, tags);

            if (communities != null)
            {
                return(new OperationResult <IEnumerable <community> >()
                {
                    Success = true, Message = Messages.COMMUNITY_SUCCESS, Result = communities
                });
            }
            return(new OperationResult <IEnumerable <community> >()
            {
                Success = false, Message = Messages.COMMUNITY_NOT_EXIST_NAME
            });
        }
Exemplo n.º 4
0
        /// <summary>
        ///  This Function returns the nearest taxi with the smallest id , given the customer's current position and the
        ///  position of all taxi cars that are available
        /// </summary>
        /// <param name="locationSource"> location source of the Customer's Current location</param>
        /// <returns>nearest car_id with total time required to reach to customer</returns>
        private (int, int) FindNearestTaxiToCustomer(LocationCoordinates locationSource)
        {
            // Dictionary to hold the car ID and Time to travel to customer
            //
            // car ID     | Time required to reach Customer
            // ---------------------------------------------
            //   1        |       3
            //   2        |       6
            //   3        |       8

            var timeRequiredToTravelToCustomerWithCarIdDict = new Dictionary <int, int>();

            foreach (var taxi in taxis)
            {
                if (!taxi.IsBooked)
                {
                    var timeToTravelToCustomerForTaxi = TimeTakenFromXtoY(taxi.Location, locationSource);
                    timeRequiredToTravelToCustomerWithCarIdDict.Add(taxi.CarId, timeToTravelToCustomerForTaxi);
                }
            }

            if (timeRequiredToTravelToCustomerWithCarIdDict.Count > 0)
            {
                var query = timeRequiredToTravelToCustomerWithCarIdDict.GroupBy(x => x.Value,
                                                                                (k, g) => new {
                    Min   = g.Min(x => x.Key),
                    Value = k
                });
                return(timeRequiredToTravelToCustomerWithCarIdDict.FirstOrDefault().Key,
                       timeRequiredToTravelToCustomerWithCarIdDict.FirstOrDefault().Value);
            }

            return(-1, -1);
        }
Exemplo n.º 5
0
        public void Equality_BothNull()
        {
            LocationCoordinates a = null;
            LocationCoordinates b = null;

            Assert.IsTrue(a == b);
            Assert.IsFalse(a != b);
        }
Exemplo n.º 6
0
        protected override void InitializeMap(LocationCoordinates initial_center)
        {
            InitialCenter = initial_center;
            System.Diagnostics.Debug.WriteLine("InitializeMap(" + initial_center);
            InitializeMap(new Position(initial_center.Latitude, initial_center.Longitude));

            PinUpdateTimer = new Timer(UpdatePin, null,
                                       TimeSpan.Zero, InitialPinRefreshPeriod);
        }
Exemplo n.º 7
0
        public void Equality_LongitudeDifferent()
        {
            double a_lat          = 12.32;
            double a_long         = 5.22;
            LocationCoordinates a = new LocationCoordinates(a_lat, a_long);
            LocationCoordinates b = new LocationCoordinates(a_lat, -5.22);

            Assert.IsFalse(a == b);
        }
Exemplo n.º 8
0
        public void Equality_LatitudeDifferent()
        {
            double a_lat          = 12.32;
            double a_long         = 5.22;
            LocationCoordinates a = new LocationCoordinates(a_lat, a_long);
            LocationCoordinates b = new LocationCoordinates(-12.32, a_long);

            Assert.IsTrue(a != b);
        }
Exemplo n.º 9
0
        public async Task AddLocation(LocationCoordinates coordnates)
        {
            LocationAdded?.Invoke(this, EventArgs.Empty);

            var wuAcLocation = await lookupLocation(coordnates);

            var wuLocation = await getWuLocation(wuAcLocation);

            AddLocation(wuLocation);
        }
Exemplo n.º 10
0
        public void Equality_Equal()
        {
            double a_lat                  = 12.32;
            double a_long                 = 5.22;
            LocationCoordinates a         = new LocationCoordinates(a_lat, a_long);
            LocationCoordinates same_as_a = new LocationCoordinates(a_lat, a_long);

            Assert.IsTrue(a == same_as_a);
            Assert.IsTrue(a.Equals(same_as_a));
            Assert.IsFalse(a != same_as_a);
        }
Exemplo n.º 11
0
        public void Equality_OneIsNull()
        {
            double a_lat          = 12.32;
            double a_long         = 5.22;
            LocationCoordinates a = new LocationCoordinates(a_lat, a_long);
            LocationCoordinates b = null;

            Assert.IsFalse(a == b);
            Assert.IsFalse(a.Equals(b));
            Assert.IsTrue(a != b);
        }
Exemplo n.º 12
0
        public async Task <LocationCoordinates> GetPositionAsync()
        {
            var current_pos = await CrossGeolocator.Current.GetPositionAsync(Timeout, CancelToken, IncludeHeading);

            var pos = new LocationCoordinates(current_pos.Latitude, current_pos.Longitude);

            LastKnownLocation = pos;

            // we return pos the variable instead of LastKnownLocation,
            // since LastKnownLocation could possibly be changed
            // since the last set
            return(pos);
        }
Exemplo n.º 13
0
        public override async Task InitializeAsync(object navigation_data)
        {
            LocationCoordinates initial_position = navigation_data as LocationCoordinates;

            if (initial_position != null)
            {
                InitialMapLocationCenter = initial_position;
            }
            else
            {
                InitialMapLocationCenter = await Geolocator.GetPositionAsync();
            }
        }
        public async void OnGetLocationClicked(object sender, EventArgs e)
        {
            // Start getting the location in Background
            var getLocationTask = DependencyService.Get<IGetCurrentLocation>().GetCurrentLocation();
            var currentLocation = await getLocationTask;

            if (getLocationTask.Status == TaskStatus.RanToCompletion)
            {
                var cords = new LocationCoordinates { Latitude = getLocationTask.Result.Latitude, Longitude = getLocationTask.Result.Longitude, Status = getLocationTask.Result.Status };

                myLocations.Add(cords); 
            }
            
        }
Exemplo n.º 15
0
        void SetInitialMapCenter(LocationCoordinates coords)
        {
            if (coords == null)
            {
                return;
            }

            if (InitialMapCenter != null)
            {
                return;
            }
            InitialMapCenter = coords;

            InitializeMap(coords);
        }
        public LocationCoordinates GetGeocodedLocation(string location)
        {
            var addresses = GetBingAddresses(location);

            if (addresses.Result != null)
            {
                var firstAddr = addresses.Result.First();
                LocationCoordinates coords = new LocationCoordinates()
                {
                    Latitude  = (firstAddr != null) ? firstAddr.Coordinates.Latitude : (double?)null,
                    Longitude = (firstAddr != null) ? firstAddr.Coordinates.Longitude : (double?)null
                };
                return(coords);
            }
            return(null);
        }
Exemplo n.º 17
0
        /// <summary>
        /// get weather data using longitude and latitude
        /// </summary>
        /// <param name="lon">longitude</param>
        /// <param name="lat">latitude</param>
        /// <returns>weather data</returns>
        public WeatherData GetWeatherByLonLat(LocationCoordinates locationCoordinates)
        {
            var restClient = new RestClient();

            restClient.BaseUrl = new Uri(ApiAccess.OPEN_WEATHER_MAP_BASE_URL);

            var request = new RestRequest("weather", Method.GET);

            request.AddParameter("appid", ApiAccess.OPEN_WEATHER_MAP_KEY);
            request.AddParameter("lon", locationCoordinates.Longitude);
            request.AddParameter("lat", locationCoordinates.Latitude);

            RestApiClientSync syncRestClient = new RestApiClientSync();
            WeatherData       weatherData    = syncRestClient.ExecuteRequest(restClient, request);

            return(weatherData);
        }
Exemplo n.º 18
0
        public static int CreateLocations(int OrderId, int TypeId, int Quantity, string Address, string Longitude, string Latitude, DateTime Date, string ClientName)
        {
            LocationCoordinates data = new LocationCoordinates
            {
                OrderId    = OrderId,
                TypeId     = TypeId,
                Quantity   = Quantity,
                Address    = Address,
                Longitude  = Longitude,
                Latitude   = Latitude,
                Date       = Date,
                Collected  = "Fals",
                ClientName = ClientName
            };

            string sql = @"insert into dbo.Location (OrderId, TypeId, Quantity, Address, Longitude, Latitude, Date, Collected, ClientName)
                         values (@OrderId, @TypeId, @Quantity, @Address, @Longitude, @Latitude, @Date, @Collected, @ClientName);";

            return(SqlDataAccess.SaveData(sql, data));
        }
        public async Task <LocationCoordinates> GetCurrentLocation()
        {
            EventHandler <PositionEventArgs> handler = null;
            var result = new LocationCoordinates();
            TaskCompletionSource <LocationCoordinates> tcs = new TaskCompletionSource <LocationCoordinates>();
            Geolocator locator = new Geolocator {
                DesiredAccuracy = 50
            };

            try
            {
                if (!locator.IsListening)
                {
                    locator.StartListening(10, 100);
                }

                handler = (object sender, PositionEventArgs e) =>
                {
                    result.Status            = e.Position.Timestamp;
                    result.Latitude          = e.Position.Latitude;
                    result.Longitude         = e.Position.Longitude;
                    locator.PositionChanged -= handler;
                    tcs.SetResult(result);
                };
                locator.PositionChanged += handler;

                await locator.GetPositionAsync(timeout : 10000).ContinueWith(
                    t =>
                {
                });
            }
            catch (System.Exception ex)
            {
                if (ex.InnerException.GetType().ToString() == "Xamarin.Geolocation.GeolocationException")
                {
                    tcs.SetException(ex);
                }
            }

            return(tcs.Task.Result);
        }
        public async Task<LocationCoordinates> GetCurrentLocation()
        {
            EventHandler<PositionEventArgs> handler = null;
            var result = new LocationCoordinates();
            TaskCompletionSource<LocationCoordinates> tcs = new TaskCompletionSource<LocationCoordinates>();
            Geolocator locator = new Geolocator { DesiredAccuracy = 50 };

            try
            {
                if (!locator.IsListening)
                {
                    locator.StartListening(10, 100);    
                }                

                handler = (object sender, PositionEventArgs e) =>
                {
                    result.Status = e.Position.Timestamp;
                    result.Latitude = e.Position.Latitude;
                    result.Longitude = e.Position.Longitude;
                    locator.PositionChanged -= handler;
                    tcs.SetResult(result);
                };
                locator.PositionChanged += handler;                
                
                await locator.GetPositionAsync(timeout: 10000).ContinueWith(
                    t =>
                    {
                    });               
            }
            catch (System.Exception ex)
            {
                if (ex.InnerException.GetType().ToString() == "Xamarin.Geolocation.GeolocationException")
                {
                    tcs.SetException(ex);
                }
            }

            return tcs.Task.Result;
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            LocationCoordinates coords = (LocationCoordinates)value;

            if (coords == null)
            {
                return("unknown location");
            }

            if (Geolocator.LastKnownLocation == null)
            {
                return(coords.ToString());
            }

            double distance = Geolocator.LastKnownLocation
                              .DistanceTo(coords, DistanceUnits.Miles);

            // TODO: this should be randomized a bit
            // so that people can't easily find the location of
            // an item by checking the distance over and over.

            return($"{Math.Round(distance, 3)} miles away");
        }
Exemplo n.º 22
0
        public async Task GetLocations(string json, LocationCoordinates coordnates)
        {
            var locations = json.GetLocations();

            var oldCurrent = locations.FirstOrDefault(l => l.Current);

            if (oldCurrent != null)
            {
                locations.Remove(oldCurrent);
            }


            var newCurrent = await getCurrentLocation(coordnates);

            if (newCurrent != null)
            {
                locations.Add(newCurrent);

                // if the previous current was selected, or theres not one selected, select this one
                newCurrent.Selected |= oldCurrent?.Selected ?? false || !locations.Any(l => l.Selected);
            }

            await GetLocations(locations);
        }
Exemplo n.º 23
0
        async Task getLocationsFromSettingsStore(LocationCoordinates coordnates)
        {
            var locations = SettingsStudio.Settings.LocationsJson.GetLocations();

            var oldCurrent = locations.FirstOrDefault(l => l.Current);

            if (oldCurrent != null)
            {
                locations.Remove(oldCurrent);
            }


            var newCurrent = await lookupLocation(coordnates);

            if (newCurrent != null)
            {
                locations.Add(newCurrent);

                // if the previous current was selected, or theres not one selected, select this one
                newCurrent.Selected |= oldCurrent?.Selected ?? false || !locations.Any(l => l.Selected);
            }

            await getLocations(locations);
        }
Exemplo n.º 24
0
        async void InitializeLastKnownLocation()
        {
            var last_pos = await CrossGeolocator.Current.GetLastKnownLocationAsync();

            LastKnownLocation = new LocationCoordinates(last_pos.Latitude, last_pos.Longitude);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Calculates the Manhattan distance between two points
 ///  x = (a,b)  and   y = (c,d)
 ///  Manhattan Distance is calculated  = |a - c| + |b - d|
 /// </summary>
 /// <param name="locationSource">Source Location</param>
 /// <param name="locationDestination">Destination Location</param>
 /// <returns></returns>
 private int TimeTakenFromXtoY(LocationCoordinates locationSource, LocationCoordinates locationDestination)
 {
     return(Math.Abs(locationDestination.X - locationSource.X) +
            Math.Abs(locationDestination.Y - locationSource.Y));
 }
Exemplo n.º 26
0
 public Task GetLocations(LocationCoordinates coordnates)
 {
     return(getLocationsFromSettingsStore(coordnates));
 }
Exemplo n.º 27
0
        async Task <WuAcLocation> lookupLocation(LocationCoordinates coordnates)
        {
            var location = coordnates != null ? await GetAsync <GeoLookup> ($"/q/{coordnates.Latitude},{coordnates.Longitude}") : null;

            return(location?.ToWuAcLocation());
        }
Exemplo n.º 28
0
 Uri GetMapsUri(LocationCoordinates coords)
 {
     return(GetMapsUri(coords.ToString()));
 }
Exemplo n.º 29
0
 public void NavigateToCoordinates(LocationCoordinates coords)
 {
     Device.OpenUri(GetMapsUri(coords));
 }
Exemplo n.º 30
0
        public void AssignPackagesToCouriers_Give1Package_ReturnListWith1Position()
        {
            List <Package> packages = new List <Package>();

            packages.Add(new Package()
            {
                Id           = 3,
                RecipientLat = 54,
                RecipientLon = 18,
                Sender       = new User()
                {
                    lat = 53.5,
                    lon = 19
                },
                Size = PackageSize.Average
            });

            List <User> users = new List <User>();

            users.Add(new User()
            {
                Id = 5, lat = 52, lon = 21
            });
            users.Add(new User()
            {
                Id = 6, lat = 53, lon = 20
            });

            Dictionary <int, double> distance = new Dictionary <int, double>();

            distance.Add(5, 20);
            distance.Add(6, 150);

            List <Vehicle> vehicles = new List <Vehicle>();

            vehicles.Add(new Vehicle()
            {
                Id = 5, AverageSpeed = 120
            });
            vehicles.Add(new Vehicle()
            {
                Id = 6, AverageSpeed = 100
            });

            Dictionary <int, int> vehiclesCapacity = new Dictionary <int, int>();

            vehiclesCapacity.Add(5, 200);

            LocationCoordinates firstPackageSender = new LocationCoordinates();

            var userServiceMock = new Mock <IUserService>();

            userServiceMock
            .Setup(x => x.GetAllDrivers())
            .Returns(users);

            var vehicleServiceMock = new Mock <IVehicleService>();

            vehicleServiceMock
            .Setup(x => x.GetAllVehicles())
            .Returns(vehicles);

            vehicleServiceMock
            .Setup(x => x.GetVehicle(5))
            .Returns(new Vehicle()
            {
                Id = 5
            });

            var locationServiceMock = new Mock <ILocationService>();

            locationServiceMock
            .Setup(y => y.CountDistancesFromPackageToCouriers(users, It.IsAny <Package>()))
            .Returns(distance);

            var packageServiceMock = new Mock <IPackageService>();
            var jsonSerializerMock = new Mock <IJsonSerializer>();
            var timeProvider       = new Mock <ITimeProvider>();

            var service = new WaybillsService(
                locationServiceMock.Object,
                vehicleServiceMock.Object,
                packageServiceMock.Object,
                jsonSerializerMock.Object,
                userServiceMock.Object,
                timeProvider.Object);

            List <Package> todaysPackage = service.AssignPackagesToCouriers(packages, users, vehiclesCapacity);

            todaysPackage.Should().HaveCount(1);
        }
Exemplo n.º 31
0
 public void LocationChosen(LocationCoordinates coords)
 {
     NavigationService.GoBackAsync(coords);
 }
Exemplo n.º 32
0
        public ActionResult NewOrder(OrderWasteViewModel OWVM, OrderModel order, LocationCoordinates COO)
        {
            var data1    = LoadCustomers();
            var idClient = 0;

            foreach (var row1 in data1)
            {
                if (row1.EmailAddress == User.Identity.GetUserName())
                {
                    idClient = row1.Id;
                }
            }
            order.Town        = "Baia Mare";
            order.Number      = OWVM.Number;
            order.Address     = OWVM.Address;
            order.PhoneNumber = OWVM.PhoneNumber;
            order.Date        = DateTime.Now;
            order.CustomerId  = idClient;



            CreateComenzi(order.Town, OWVM.Address, OWVM.Number, OWVM.PhoneNumber, DateTime.Now, order.CustomerId);

            var customer = LoadCustomers();
            var id       = 0;
            var q        = 0;
            var data     = LoadComenzi();
            var orderId  = 0;
            var town     = "";
            var street   = "";
            var number   = "";
            var address  = "";

            foreach (var row in data)
            {
                orderId = row.Id;
                town    = row.Town;
                street  = row.Address;
                number  = row.Number.ToString();
                address = town + " Strada " + street + " Numarul " + number;
            }

            foreach (var item in OWVM.WasteTypes)
            {
                if (item.IsChecked == true)
                {
                    COO.ClientName = User.Identity.GetUserName();
                    Coordinate coordinate = new Coordinate();
                    coordinate    = GetCoordinates(address);
                    COO.OrderId   = orderId;
                    COO.TypeId    = item.Id;
                    COO.Quantity  = item.Quantity;
                    COO.Address   = address;
                    COO.Longitude = ((decimal)coordinate.Longitude).ToString();
                    COO.Latitude  = ((decimal)coordinate.Latitude).ToString();
                    COO.Date      = order.Date;
                    CreateLocations(COO.OrderId, COO.TypeId, COO.Quantity, COO.Address, COO.Longitude, COO.Latitude, COO.Date, COO.ClientName);
                    foreach (var row in customer)
                    {
                        if (COO.ClientName == row.EmailAddress)
                        {
                            id = row.Id;
                            q  = q + row.QuantityColected;
                        }
                    }
                    UpdateQuantityColected(id, q, COO.Quantity);
                }
            }


            return(RedirectToAction("Confirmare", "Orders"));
        }