Esempio n. 1
0
        public static Models.Models.Location GetLocation(string address)
        {
            address = address.Replace(" ", "+");
            WebRequest  request    = WebRequest.Create("https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&language=bg&key=AIzaSyCqFT1vjwghgVYc9Y_jbuD-ux10qQD9H0s");
            WebResponse response   = request.GetResponse();
            Stream      dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            RequestFormat flight = Newtonsoft.Json.JsonConvert.DeserializeObject <RequestFormat>(responseFromServer);

            if (flight.results.Count == 0)
            {
                return(null);
            }
            var location = new Models.Models.Location()
            {
                Latitude  = flight.results[0].geometry.location.lat,
                Longitude = flight.results[0].geometry.location.lng
            };

            return(location);
        }
Esempio n. 2
0
        /// <summary>
        /// Updates some basic information about the car
        /// </summary>
        /// <param name="car"></param>
        /// <param name="location"></param>
        /// <param name="absent"></param>
        /// <param name="free"></param>
        public void UpdateCarInfo(Car car, Models.Models.Location location, bool absent, bool free)
        {
            car.Location           = location;
            car.LastActiveDateTime = DateTime.Now;
            if (car.CarStatus == CarStatus.Offline)
            {
                if (_data.TakenRequests.Any(x => x.Car.Id == car.Id))
                {
                    car.CarStatus = CarStatus.Busy;
                }
                else
                {
                    car.CarStatus = CarStatus.Free;
                }
            }


            if (absent)
            {
                car.CarStatus = CarStatus.Absent;
            }
            if (free)
            {
                car.CarStatus = CarStatus.Free;
            }

            _data.SaveChanges();
        }
Esempio n. 3
0
        public static Place PlaceDetail(string placeId)
        {
            WebRequest request =
                WebRequest.Create(
                    "https://maps.googleapis.com/maps/api/place/details/xml?placeid=" + placeId +
                    "&key=AIzaSyCqFT1vjwghgVYc9Y_jbuD-ux10qQD9H0s&language=bg");

            WebResponse  response   = request.GetResponse();
            Stream       dataStream = response.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);

            string      responseFromServer = reader.ReadToEnd();
            var         place = new Place();
            XmlDocument doc   = new XmlDocument();

            doc.LoadXml(responseFromServer);

            place.Address  = doc.SelectSingleNode("/PlaceDetailsResponse/result/formatted_address")?.InnerText;
            place.MainText = doc.SelectSingleNode("/PlaceDetailsResponse/result/name")?.InnerText;
            var lat = doc.SelectSingleNode("/PlaceDetailsResponse/result/geometry/location/lat")?.InnerText;
            var lon = doc.SelectSingleNode("/PlaceDetailsResponse/result/geometry/location/lng")?.InnerText;

            if (lat != null && lon != null)
            {
                Models.Models.Location placeLocation = new Models.Models.Location()
                {
                    Longitude = Double.Parse(lon.Replace(".", ",")),
                    Latitude  = Double.Parse(lat.Replace(".", ","))
                };
                place.Location = placeLocation;
            }
            return(place);
        }
        private Car AppropriateCar(Models.Models.Location startingLocaion, RequestInfo request, Company company)
        {
            var nearBycars = _data.Cars.Where(x => x.Company.Id == company.Id).Where(x => x.CarStatus == CarStatus.Free).Where(x => Math.Abs(x.Location.Latitude - startingLocaion.Latitude) <= 0.0150 && Math.Abs(x.Location.Longitude - startingLocaion.Longitude) <= 0.0150).ToList();
            var distances  = new List <double>();
            var dictionary = new Dictionary <double, Car>();
            Car chosenCar  = null;

            if (nearBycars.Count == 0)
            {
                return(null);
            }
            foreach (var item in nearBycars)
            {
                var distance = DistanceBetweenTwoPoints.GetDistance(startingLocaion, item.Location);
                distances.Add(distance);
                dictionary.Add(distance, item);
            }

            var sortedDistances = distances.OrderBy(x => x);

            foreach (var item in sortedDistances)
            {
                var car = dictionary[item];
                if (!(_data.CarsDismissedRequests.Where(x => x.Request.Id == request.Id).Any(x => x.Car.Id == car.Id)) && !(_data.ActiveRequests.Any(x => x.AppropriateCar.Id == car.Id)))
                {
                    chosenCar = car;
                }
            }


            return(chosenCar);
        }
        public static double GetDistance(Models.Models.Location PointA, Models.Models.Location PointB)
        {
            double lat1 = PointA.Latitude; double long1 = PointA.Longitude; double lat2 = PointB.Latitude;
            double long2 = PointB.Longitude;

            var    d2r   = Math.PI / 180;
            double dlong = (long2 - long1) * d2r;
            double dlat  = (lat2 - lat1) * d2r;
            double a     = Math.Pow(Math.Sin(dlat / 2.0), 2) + Math.Cos(lat1 * d2r) * Math.Cos(lat2 * d2r) * Math.Pow(Math.Sin(dlong / 2.0), 2);
            double c     = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            double d     = 6367 * c;

            return(d);
        }
Esempio n. 6
0
        public Car AppropriateCar(Models.Models.Location startingLocaion, Company company = null)
        {
            var nearBycars = new List <Car>();

            if (company == null)
            {
                nearBycars = _data.Cars.Where(x => x.CarStatus == CarStatus.Free).Where(x => Math.Abs(x.Location.Latitude - startingLocaion.Latitude) <= 0.0300 && Math.Abs(x.Location.Longitude - startingLocaion.Longitude) <= 0.0300).ToList();
            }
            else
            {
                nearBycars = _data.Cars.Where(x => x.Company.Id == company.Id).Where(x => x.CarStatus == CarStatus.Free).Where(x => Math.Abs(x.Location.Latitude - startingLocaion.Latitude) <= 0.0300 && Math.Abs(x.Location.Longitude - startingLocaion.Longitude) <= 0.0300).ToList();
            }

            var distances      = new List <double>();
            var dictionary     = new Dictionary <double, Car>();
            Car appropriateCar = null;

            if (nearBycars.Count == 0)
            {
                return(null);
            }
            foreach (var item in nearBycars)
            {
                var distance = DistanceBetweenTwoPoints.GetDistance(startingLocaion, item.Location);
                distances.Add(distance);
                dictionary.Add(distance, item);
            }

            var sortedDistances = distances.OrderBy(x => x);

            foreach (var item in sortedDistances)
            {
                var car = dictionary[item];
                if (!_data.ActiveRequests.Any(x => x.AppropriateCar.Id == car.Id))
                {
                    appropriateCar = car;
                    break;
                }
            }


            return(appropriateCar);
        }
Esempio n. 7
0
        public static List <Place> AutoCompleteList(string text, Models.Models.Location location, int radius, string types)
        {
            WebRequest request =
                WebRequest.Create("https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + text +
                                  "&location=" + location.Latitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "," + location.Longitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "&radius=" + radius + "&key=AIzaSyAJ1lJPmsUd0xhzn97x8kZXQtJEwh0dgGQ&strictbounds&language=bg&types=" + types);

            WebResponse  response   = request.GetResponse();
            Stream       dataStream = response.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);

            string responseFromServer = reader.ReadToEnd();

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(new StringReader(responseFromServer));
            var PlaceList = new List <Place>();

            foreach (XmlNode item in xmlDoc.ChildNodes[1])
            {
                if (item.ChildNodes.Count > 1)
                {
                    double.TryParse(item["geometry"].ChildNodes[0]["lat"].InnerText, out double lat);
                    double.TryParse(item["geometry"].ChildNodes[0]["lng"].InnerText, out double lng);


                    PlaceList.Add(new Place()
                    {
                        Address  = item["formatted_address"].InnerText,
                        Location = new Models.Models.Location()
                        {
                            Latitude  = lat,
                            Longitude = lng,
                        },
                        MainText = item["name"].InnerText,
                        PlaceId  = item["place_id"].InnerText,
                        Type     = item["type"].InnerText
                    });
                }
            }
            return(PlaceList);
        }
        /// <summary>
        /// Adds a new request
        /// </summary>
        /// <param name="startingAddress"></param>
        /// <param name="finishAddress"></param>
        /// <returns></returns>
        public JsonResult CreateRequest(string startingAddress, string finishAddress)
        {
            var userId     = User.Identity.GetUserId();
            var dispatcher = _dispatcherService.GetAll().First(x => x.UserId == userId);
            var company    = _companyService.GetAll().First(x => x.Id == dispatcher.Company.Id);

            var startingLocation = GoogleAPIRequest.GetLocation(startingAddress + " " + company.City);
            var finishLocation   = GoogleAPIRequest.GetLocation(finishAddress + " " + company.City);

            if (startingLocation == null)
            {
                return(Json(new { status = "INVALID STARTING LOCATION" }));
            }
            if (finishLocation == null)
            {
                finishLocation = new Models.Models.Location()
                {
                    Latitude  = 0,
                    Longitude = 0
                };
            }



            var request = new RequestInfo()
            {
                CreatedBy                = CreatedBy.Dispatcher,
                CreatorUserId            = userId,
                RequestStatus            = RequestStatusEnum.NoCarChosen,
                StartingAddress          = startingAddress,
                StartingLocation         = startingLocation,
                FinishAddress            = finishAddress,
                FinishLocation           = finishLocation,
                CreatedDateTime          = DateTime.Now,
                LastModificationDateTime = DateTime.Now,
                Company = company
            };

            _requestService.AddRequestInfo(request);
            var dashboardCell = new DispatcherDashboard()
            {
                DispatcherUserId = userId,
                LastSeen         = DateTime.Now,
                LastSeenStatus   = RequestStatusEnum.NoCarChosen,
                Request          = request
            };

            _dashboardService.AddDispatcherDashboard(dashboardCell);
            var activeRequest = new ActiveRequest()
            {
                AppropriateCar    = null,
                DateTimeChosenCar = DateTime.Now,
                Request           = request
            };

            _requestService.AddActiveRequest(activeRequest);
            var car = _carService.AppropriateCar(startingLocation, dispatcher.Company);

            if (car != null)
            {
                request.RequestStatus        = RequestStatusEnum.NotTaken;
                activeRequest.AppropriateCar = car;
                _requestService.ModifyActiveRequest(activeRequest);
                _requestService.ModifyRequestInfo(request);
            }



            return(Json(new { status = "OK" }));
        }