Beispiel #1
0
        public ActionResult UpcomingTripDetails(int tripId)
        {
            Trip trip;

            if (TempData.ContainsKey("CurrentUpcomingTrips"))
            {
                trip = ((List <Trip>)TempData["CurrentUpcomingTrips"]).FirstOrDefault(i => i.Id == tripId);
                TempData.Keep("CurrentUpcomingTrips");

                if (trip != null)
                {
                    if (trip.Steps != null)
                    {
                        foreach (Step step in trip.Steps)
                        {
                            if (step.EncodedMapString != null)
                            {
                                step.googlePoints = GooglePoints.Decode(step.EncodedMapString);
                            }
                        }
                    }

                    return(View(trip));
                }
            }
            return(RedirectToAction("Index", "TripDashboard"));
        }
        public async Task <string> BuildMap(long activityId, string summaryPolyline)
        {
            var decodedSummaryPolyline = GooglePoints.Decode(summaryPolyline).ToList();

            var path = string.Join("|", decodedSummaryPolyline.Select(p => $"{p.Latitude},{p.Longitude}"));

            var formatString = @"https://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=800x800&path={0}&key={1}&size=800x800";

            var url = string.Format(formatString, path, _googleSettings.ApiKey);

            var response = await _client.GetAsync(url);

            var result = await response.Content.ReadAsByteArrayAsync();

            var s3Filename = $"{activityId}.png";

            using (var image = Image.Load(result))
            {
                image.Save(s3Filename);
            }

            await UploadFileToS3(s3Filename);

            var s3Url = $"{CloudFrontBaseUrl}{s3Filename}";

            _logger.LogInformation($"New activity image uploaded: {s3Url}");

            return(s3Url);
        }
Beispiel #3
0
        public ActionResult ItineraryDetails(Guid itineraryId)
        {
            Plan plan;

            if (TempData.ContainsKey("CurrentPlan"))
            {
                plan = (Plan)TempData["CurrentPlan"];
                TempData.Keep("CurrentPlan");

                if (plan.GetItinerary(itineraryId) != null)
                {
                    Itinerary itinerary = plan.GetItinerary(itineraryId);

                    if (itinerary.legs != null)
                    {
                        foreach (Leg leg in itinerary.legs)
                        {
                            if (leg.legGeometry != null)
                            {
                                if (leg.legGeometry.points != null)
                                {
                                    leg.googlePoints = GooglePoints.Decode(leg.legGeometry.points);
                                }
                            }
                        }
                    }

                    return(View(itinerary));
                }
            }

            return(RedirectToAction("Index", "TripDashboard"));
        }
Beispiel #4
0
        public async Task Create(Area region)
        {
            string areaId = Guid.NewGuid().ToString();

            region.AreaID         = areaId;
            region.Points         = GooglePoints.Decode(region.EncodedPolygon).Select(x => new LocationPoint(x.Latitude, x.Longitude)).ToList();
            region.EncodedPolygon = null;
            List <Tile> tiles = this.GetCoordinateTile(region.Points.Select(x => new PointF((float)x.Lat, (float)x.Lng)).ToList(), true).tiles;

            AreaMaster areaMaster = new AreaMaster()
            {
                AreaID                = areaId,
                AreaName              = region.AreaName,
                IsPredefine           = false,
                EncodedPolygon        = GooglePoints.EncodeBase64(region.Points.Select(x => new CoordinateEntity(Convert.ToDouble(x.Lat), Convert.ToDouble(x.Lng)))),
                EncodedCompletedTiles = GooglePoints.EncodeBase64(tiles.Where(x => !x.IsPartialTile).Select(x => new CoordinateEntity(x.Row, x.Column))),
                EncodedPartialTiles   = GooglePoints.EncodeBase64(tiles.Where(x => x.IsPartialTile).Select(x => new CoordinateEntity(x.Row, x.Column)))
            };

            List <Task> tasks = new List <Task>();

            tasks.Add(Task.Factory.StartNew(() =>
            {
                this.context.SaveAsync <AreaMaster>(areaMaster).Wait();
            }));


            List <Area> areas = this.transformRegion(region, tiles);

            SaveAreas(areas);

            Task.WaitAll(tasks.ToArray());
        }
Beispiel #5
0
        public async Task <GenerateResponseFP> GenerateRouteAsync(GenerateFP fp)
        {
            var teste = JsonConvert.SerializeObject(fp);

            using (var content = new StringContent(teste, Encoding.UTF8, "application/json"))
            {
                var response = await Client.PostAsync(Const.generateUrl, content).ConfigureAwait(false);

                var json = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var show = JsonConvert.DeserializeObject <GenerateResponseFP>(json);
                    //show.Positions = new List<Position>();
                    var myFp = GooglePoints.Decode(show.EncodedPolyline);

                    foreach (var item in myFp)
                    {
                        show.Positions.Add(new Position(item.Latitude, item.Longitude));
                    }

                    return(show);
                }

                else
                {
                    var msg = ApiException(json);
                    throw new BadRequestException(msg);
                }
            }
        }
Beispiel #6
0
        public async Task <TripSearchResult> SearchForTrip(TripSearch search)
        {
            TripSearchResult val = await Task.Factory.StartNew <TripSearchResult>(() =>
            {
                TripSearchResult searchResult = new TripSearchResult();

                var client = new RestClient(URI_STRING);

                client.UserAgent = USER_AGENT;
                var request      = new RestRequest("/api/OTP", Method.GET);

                request.RequestFormat = DataFormat.Json;

                request.AddParameter("startLatitude", search.StartLatitude);
                request.AddParameter("startLongitude", search.StartLongitude);
                request.AddParameter("startLocation", search.StartLocation);
                request.AddParameter("endLatitude", search.EndLatitude);
                request.AddParameter("endLongitude", search.EndLongitude);
                request.AddParameter("endLocation", search.EndLocation);
                request.AddParameter("searchByArriveByTime", search.SearchByArriveByTime);
                request.AddParameter("time", search.Time);
                request.AddParameter("needWheelchairAccess", search.NeedWheelchairAccess);
                request.AddParameter("maxWalkMeters", search.MaxWalkMeters);

                IRestResponse <TripSearchResult> response = client.Execute <TripSearchResult>(request);

                searchResult = response.Data;

                if (searchResult != null)
                {
                    foreach (Itinerary itinerary in searchResult.itineraries)
                    {
                        if (itinerary.legs != null)
                        {
                            foreach (Leg leg in itinerary.legs)
                            {
                                if (leg.legGeometry != null)
                                {
                                    if (leg.legGeometry.points != null)
                                    {
                                        leg.googlePoints = GooglePoints.Decode(leg.legGeometry.points);
                                    }
                                }
                            }
                        }
                    }
                }

                return(searchResult);
            });

            return(val);
        }
Beispiel #7
0
 public Models.Route generateRoute(Tracker tracker)
 {
     using (var ctx = new SimulationContext())
     {
         Address start;
         Address end;
         getRouteAddres(tracker, out start, out end);
         Route route = new Route(start, end, getPolyline(mapResponse(start, end)));
         route.Markers = (ICollection <Marker>)GooglePoints.Decode(route.Polyline.points).ToList();
         ctx.SaveChanges();
         return(route);
     }
 }
Beispiel #8
0
        public async Task <List <Trip> > GetTripsByType(int travelerId, TripType.Type type)
        {
            List <Trip> list = await Task.Factory.StartNew <List <Trip> >(() =>
            {
                List <Trip> tripList = new List <Trip>();

                var client            = new RestClient(URI_STRING);
                client.UserAgent      = USER_AGENT;
                var request           = new RestRequest("/api/Trip", Method.GET);
                request.RequestFormat = DataFormat.Json;

                request.AddParameter("travelerID", travelerId);
                request.AddParameter("type", type);

                IRestResponse <List <Trip> > response = client.Execute <List <Trip> >(request);

                tripList = response.Data;


                foreach (Trip trip in tripList)
                {
                    if (trip.Steps != null)
                    {
                        foreach (Step step in trip.Steps)
                        {
                            if (step.EncodedMapString != null)
                            {
                                step.googlePoints = GooglePoints.Decode(step.EncodedMapString);
                            }
                        }
                    }
                }

                return(tripList);
            });

            return(list);
        }
Beispiel #9
0
        private static readonly string pw   = ""; /* PW */

        public static List <Carpooler> getCarpoolingDataFromBackend(Routing.Nodes.Point MinPoint, Point MaxPoint, bool updateExternalRides)
        {
            /* Set this to true if you want to use real waypoints instead of intermediate ptstops, remember to also change the use_waypoints value in the CarpoolParser.cs file */
            bool use_waypoints = false;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                   | SecurityProtocolType.Tls11
                                                   | SecurityProtocolType.Tls12
                                                   | SecurityProtocolType.Ssl3;
            List <Carpooler> CarpoolRides = new List <Carpooler> {
            };
            CarpoolerJson Carpooler       = new CarpoolerJson {
            };

            string url = rides_boundary + "?" +
                         "min_lat=" + MinPoint.Latitude + "&" +
                         "min_lon=" + MinPoint.Longitude + "&" +
                         "max_lat=" + MaxPoint.Latitude + "&" +
                         "max_lon=" + MaxPoint.Longitude + "&" +
                         "site=" + Program.site;

            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method      = WebRequestMethods.Http.Get;
                httpWebRequest.Accept      = "application/json";
                httpWebRequest.Credentials = new NetworkCredential(user, pw);
                httpWebRequest.UserAgent   = "RP client";

                HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
                log.Info(url);
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    Stream       stream         = response.GetResponseStream();
                    StreamReader reader         = new StreamReader(stream, Encoding.UTF8);
                    String       responseString = reader.ReadToEnd();

                    Carpooler = JsonConvert.DeserializeObject <CarpoolerJson>(responseString);

                    if ((Carpooler == null) || (Carpooler.rides.Count == 0))
                    {
                        log.Warn("Carpooling: no data available from backend");
                    }
                    else
                    {
                        int numExtRidesIgnored = 0;

                        foreach (CarpoolerJson.Ride el in Carpooler.rides)
                        {
                            // Just for testing if the carpooling rides are expired
                            if (el.date < Program.DynamicData.sites.First().carpooling_info.nightly_updated)
                            {
                                log.Error("Ride should be expired but it is present el.date:" + el.date + " nightly_timestampVersion:" + Program.DynamicData.sites.First().carpooling_info.nightly_updated);
                            }

                            //!!!DEBUG EDIMBURGO!!!
                            //if ((String.Compare(el._id, "5976e793e04bd56a9a84ffa8") == 0) ||
                            //    (String.Compare(el._id, "1dfd2cd0faebcf1b768a77bd") == 0) )
                            //{

                            //!!!DEBUG TICINO!!!
                            //if ((String.Compare(el.name, "Test Milano Lugano 01") == 0) ||
                            //    (String.Compare(el.name, "Test Biella Lugano 01") == 0) ||
                            //    (String.Compare(el.name, "Test Cavaglietto Lugano 01") == 0) ||
                            //    (String.Compare(el.name, "Test Biasca Lugano 01") == 0) ||
                            //    (String.Compare(el.name, "Test Airolo Lugano 01") == 0) ||
                            //    (String.Compare(el.name, "Test Bergamo Lugano 01") == 0) ||
                            //     (String.Compare(el._id, "5d85a82ea07e1160a5669e29") == 0))
                            //{

                            IEnumerable <Routing.Nodes.Point> Points = GooglePoints.Decode(el.polyline.Replace(@"\\", @"\"));
                            //List<Routing.Nodes.Point> Points = GooglePoints.DecodePolylinePoints(el.polyline.Replace(@"\\", @"\"));
                            //List<Routing.Nodes.Point> Points = GooglePoints.decodePoly(el.polyline);

                            //string test = GooglePoints.DecodeLocations(el.polyline.Replace(@"\\", @"\"));
                            //foreach (Point p in Points)
                            //log.Info(p.Latitude + ", " + p.Longitude);

                            string startDate = Globals.GetDateFromTimestamp(el.date);

                            SourceCPRide provider = SourceCPRide.Unknown;
                            if (el.extras != null)
                            {
                                provider = SourceCPRide.External;
                            }
                            else
                            {
                                provider = SourceCPRide.SocialCar;
                            }

                            if ((provider == SourceCPRide.SocialCar) ||
                                ((provider == SourceCPRide.External) && (updateExternalRides == true)))
                            {
                                Carpooler Pooler = new Carpooler(el._id, el.name, Globals.GetLocalTimeSinceMidnight(el.date), int.MaxValue, el.activated, startDate, provider);

                                /* Add start point to the ride */
                                Pooler.WayPointsOrig.Add(new Point(el.start_point.lat, el.start_point.lon));
                                Pooler.WayPointsUsed.Add(new Point(el.start_point.lat, el.start_point.lon));

                                /* Add all waypoints to the ride (THIS DOES NOT WORK SINCE THE WAYPOINTS DON'T MATCH WITH OUR NETWORK )*/
                                if (use_waypoints == true)
                                {
                                    //Pooler.WayPointsTmpList.Add(new Point(el.start_point.lat, el.start_point.lon));
                                    //foreach (Point p in Points)
                                    //{
                                    //    Pooler.WayPointsOrig.Add(p);
                                    //    Pooler.WayPointsUsed.Add(p);
                                    //}
                                }

                                /* Add end point to the ride */
                                Pooler.WayPointsUsed.Add(new Point(el.end_point.lat, el.end_point.lon));
                                Pooler.WayPointsOrig.Add(new Point(el.end_point.lat, el.end_point.lon));

                                CarpoolRides.Add(Pooler);
                            }
                            else
                            {
                                if (updateExternalRides == false)
                                {
                                    numExtRidesIgnored++;
                                }
                            }
                            //}
                        }
                        if (updateExternalRides == false)
                        {
                            log.Info("updateExternalRides:" + updateExternalRides + " Ignored:" + numExtRidesIgnored + " external rides");
                        }
                    }
                }
                else
                {
                    log.Error("An error occured while calling the carpooling data service: StatusCode=" + response.StatusCode);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                log.Error("An error occured during the carpooling data get: " + ex.ToString());
                return(null);
            }

            if (CarpoolRides != null)
            {
                if (CarpoolRides.Count == 0)
                {
                    log.Warn(CarpoolRides.Count + " carpooling rides received");
                }
                else
                {
                    log.Info(CarpoolRides.Count + " carpooling rides received");
                }
            }

            return(CarpoolRides);
        }
Beispiel #10
0
        public async Task <GetListingWrapper> GetListing(Area area, string north = null, string east = null, string south = null, string west = null, string beds = null, string bathsFull = null, string bathsHalf = null, string propertyAddressId = null, string averageValue = null, string averageRent = null, string encodedCompletedTiles = null, string encodedPartialTiles = null)
        {
            List <Listing> listings = new List <Listing>();

            List <PointF> boundingBox = null;

            if (!string.IsNullOrEmpty(north) && !string.IsNullOrEmpty(east) && !string.IsNullOrEmpty(south) && !string.IsNullOrEmpty(west))
            {
                boundingBox = new List <PointF>();
                boundingBox.Add(new PointF((float)Convert.ToDouble(north), (float)Convert.ToDouble(east)));
                boundingBox.Add(new PointF((float)Convert.ToDouble(north), (float)Convert.ToDouble(west)));
                boundingBox.Add(new PointF((float)Convert.ToDouble(south), (float)Convert.ToDouble(west)));
                boundingBox.Add(new PointF((float)Convert.ToDouble(south), (float)Convert.ToDouble(east)));
            }

            DateTime    startLambdaTime = DateTime.Now;
            List <Tile> tiles           = new List <Tile>();

            if (!string.IsNullOrEmpty(encodedCompletedTiles) || !string.IsNullOrEmpty(encodedPartialTiles))
            {
                if (!string.IsNullOrEmpty(area.EncodedPolygon))
                {
                    area.Points = GooglePoints.DecodeBase64(area.EncodedPolygon).Select(x => new LocationPoint(x.Latitude, x.Longitude)).ToList();
                }

                if (boundingBox == null || boundingBox.Count() == 0)
                {
                    tiles.AddRange(GooglePoints.DecodeBase64(encodedCompletedTiles).Select(x => new Tile()
                    {
                        Row = (int)x.Latitude, Column = (int)x.Longitude, IsPartialTile = false
                    }).ToList());
                    tiles.AddRange(GooglePoints.DecodeBase64(encodedPartialTiles).Select(x => new Tile()
                    {
                        Row = (int)x.Latitude, Column = (int)x.Longitude, IsPartialTile = true
                    }).ToList());
                }
                else
                {
                    RasterizeObject rasterizeObject = this.GetCoordinateTile(area.Points.Select(x => new PointF((float)x.Lat, (float)x.Lng)).ToList(), true, boundingBox);
                    tiles       = rasterizeObject.tiles;
                    area.Points = new WKTReader().Read(rasterizeObject.intersectionPolygon).Coordinates.Select(x => new LocationPoint(x.X, x.Y)).ToList();
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(area.EncodedPolygon))
                {
                    area.Points = GooglePoints.Decode(area.EncodedPolygon).Select(x => new LocationPoint(x.Latitude, x.Longitude)).ToList();
                }

                RasterizeObject rasterizeObject = this.GetCoordinateTile(area.Points.Select(x => new PointF((float)x.Lat, (float)x.Lng)).ToList(), true, boundingBox);
                tiles = rasterizeObject.tiles;

                if (boundingBox != null && boundingBox.Count() > 0)
                {
                    area.Points = new WKTReader().Read(rasterizeObject.intersectionPolygon).Coordinates.Select(x => new LocationPoint(x.X, x.Y)).ToList();
                }
            }
            DateTime endLambdaTime = DateTime.Now;

            //if (tiles == null || tiles.Count() == 0)
            //{
            //    throw new Exception("Unable To Calculate Tiles");
            //}

            DateTime startQueryTime            = DateTime.Now;
            GetRegionByPropertyWrapper listing = getRegionByProperty(tiles, beds, bathsFull, bathsHalf, propertyAddressId, averageValue, averageRent).Result;
            DateTime endQueryTime = DateTime.Now;

            foreach (var item in listing.CompleteProperties)
            {
                if (item != null)
                {
                    listings.Add(new Listing
                    {
                        Name = item.PropertyAddressName,
                        Lat  = item.Latitude,
                        Lng  = item.Longitude
                    });
                }
            }

            Stopwatch containsStopwatch = Stopwatch.StartNew();

            Parallel.ForEach(listing.PartialProperties, item =>
            {
                if (item != null && this.polyCheck(new Vector2((float)item.Latitude, (float)item.Longitude), area.Points.Select(x => new Vector2((float)x.Lat, (float)x.Lng)).ToArray()))
                {
                    listings.Add(new Listing
                    {
                        Name = item.PropertyAddressName,
                        Lat  = item.Latitude,
                        Lng  = item.Longitude
                    });
                }
            });
            containsStopwatch.Stop();

            List <ListingMaster> customProperties = listings.Select(x => new ListingMaster()
            {
                Lat  = x.Lat,
                Lng  = x.Lng,
                Name = x.Name
            }).ToList();

            return(new GetListingWrapper
            {
                PropertyCount = listing.TotalRecordCount,
                ScanCount = listing.ScanCount,
                ConsumedCapacityCount = listing.ConsumedCapacityCount,
                TotalQueryExecutionTime = (endQueryTime - startQueryTime).TotalMilliseconds,
                TotalLambdaExecutionTime = (endLambdaTime - startLambdaTime).TotalMilliseconds,
                TotalContainsExecutionTime = containsStopwatch.ElapsedMilliseconds,
                Properties = customProperties,
            });
        }