Ejemplo n.º 1
0
        private DirectionsResponse GetDirectionsResponse(Entry from, Entry to)
        {
            var cacheKey  = from.ToString() + "-" + to.ToString() + "-directions";
            var cachedVal = FindInCache <DirectionsResponse>(cacheKey);

            if (cachedVal != null)
            {
                return(cachedVal);
            }

            var directionsRequest = new DirectionsRequest {
                Origin = from.Where.Name, Destination = to.Where.Name
            };

            directionsRequest.ApiKey = this.apikey;
            DirectionsResponse directions = GoogleMaps.Directions.Query(directionsRequest);


            if (directions.Status == DirectionsStatusCodes.OK)
            {
                return(AddToCache(cacheKey, directions));
            }

            return(null);
        }
        /* This function was written by Lennart de Waart (563079) */
        /// <summary>
        /// Public asynchronous method that returns the optimal Leg class between two points.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="vehicle"></param>
        /// <param name="departureTime">Time when person starts driving</param>
        /// <param name="apiKey"></param>
        /// <returns>Filled Leg class or null</returns>
        public async Task <Leg> TravelTo(LatLng from, LatLng to, Vehicles vehicle, DateTime departureTime, string apiKey)
        {
            try
            {
                _logger.Information($"A request has been made to get the Leg of a route between latFrom {from.Latitude}, longFrom {from.Longitude}" +
                                    $"and latTo {to.Latitude}, longTo {to.Longitude} from the Google Directions API.");
                // Set travel mode based on vehicle parameter
                TravelMode t = TravelMode.Driving;
                if (vehicle == Vehicles.Fiets)
                {
                    t = TravelMode.Bicycling;
                }
                // Create a DirectionsRequest
                DirectionsRequest d = new DirectionsRequest
                {
                    TravelMode    = t,
                    DepartureTime = departureTime,
                    Origin        = new GoogleApi.Entities.Common.Location(from.Latitude, from.Longitude),
                    Destination   = new GoogleApi.Entities.Common.Location(to.Latitude, to.Longitude),
                    Key           = apiKey
                };
                // POST request to Google Directions API
                DirectionsResponse r = await GoogleMaps.Directions.QueryAsync(d);

                // Response contains a list of routes to the destination. A route contains multiple legs of ways to get to the destination. Get the first (and best)
                Leg results = r.Routes.ToList()[0].Legs.ToList()[0];
                return(results ?? throw new Exception($"Dependency failure: Google Directions API request returned null for latFrom " +
                                                      $"{from.Latitude}, longFrom {from.Longitude} to latTo {to.Latitude}, longTo {to.Longitude}."));
            }
            catch (Exception e) // Error handling
            {
                _logger.Error($"ILocationsService says: {e.Message} Exception occured on line {new StackTrace(e, true).GetFrame(0).GetFileLineNumber()}.");
                return(null);
            }
        }
Ejemplo n.º 3
0
        private double _CalculateDrivingTime(LatLong origin, LatLong destination)
        {
            try
            {
                var transitDirectionRequest = new DirectionsRequest
                {
                    Origin        = string.Format("{0},{1}", origin.Latitude, origin.Longitude),
                    Destination   = string.Format("{0},{1}", destination.Latitude, destination.Longitude),
                    TravelMode    = TravelMode.Driving,
                    DepartureTime = DateTime.Now
                };

                DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);
                if (transitDirections.Status == DirectionsStatusCodes.OK)
                {
                    double totalTime = 0;
                    foreach (var route in transitDirections.Routes)
                    {
                        foreach (var routeLeg in route.Legs)
                        {
                            totalTime += routeLeg.Duration.Value.TotalSeconds;
                        }
                    }

                    return(totalTime / 3600.0);
                }
            }
            catch (Exception)
            {
            }

            return(0);
        }
Ejemplo n.º 4
0
        public void TestConnectivityWithNoKey()
        {
            DirectionsResponse directionsResponse = new DirectionsRequest()
            {
                Key    = Environment.GetEnvironmentVariable("GOOGLE_MAP_KEY"),
                Origin = new LocationParameter()
                {
                    LatLongPair = new LatLongPair()
                    {
                        Latitude  = 40.6700,
                        Longitude = -73.9400
                    }
                },
                Destination = new LocationParameter()
                {
                    LatLongPair = new LatLongPair()
                    {
                        Latitude  = 40.6860,
                        Longitude = -73.9450
                    }
                }, _DepartureTime = DateTime.Now + TimeSpan.FromDays(10)
            }.GetDirections();

            Assert.IsTrue(directionsResponse.Successfull);
        }
Ejemplo n.º 5
0
        public void GetQueryStringParametersWhenTravelModeTransitTest()
        {
            var request = new DirectionsRequest
            {
                Key         = "key",
                Origin      = new LocationEx(new Address("address")),
                Destination = new LocationEx(new Address("address")),
                TravelMode  = TravelMode.Transit
            };

            var queryStringParameters = request.GetQueryStringParameters();

            Assert.IsNotNull(queryStringParameters);

            var mode         = queryStringParameters.FirstOrDefault(x => x.Key == "mode");
            var modeExpected = request.TravelMode.ToString().ToLower();

            Assert.IsNotNull(mode);
            Assert.AreEqual(modeExpected, mode.Value);

            var transitMode         = queryStringParameters.FirstOrDefault(x => x.Key == "transit_mode");
            var transitModeExpected = request.TransitMode.ToEnumString('|');

            Assert.IsNotNull(transitMode);
            Assert.AreEqual(transitModeExpected, transitMode.Value);

            var          departureTime           = queryStringParameters.FirstOrDefault(x => x.Key == "departure_time");
            const string DEPARTURE_TIME_EXPECTED = "now";

            Assert.IsNotNull(departureTime);
            Assert.AreEqual(DEPARTURE_TIME_EXPECTED, departureTime.Value);
        }
Ejemplo n.º 6
0
        public void GetQueryStringParametersWhenTravelModeTransitAndDepartureTimeTest()
        {
            var request = new DirectionsRequest
            {
                Key           = "key",
                Origin        = new LocationEx(new Address("address")),
                Destination   = new LocationEx(new Address("address")),
                TravelMode    = TravelMode.Transit,
                DepartureTime = DateTime.UtcNow.AddHours(1)
            };

            var queryStringParameters = request.GetQueryStringParameters();

            Assert.IsNotNull(queryStringParameters);

            var mode         = queryStringParameters.FirstOrDefault(x => x.Key == "mode");
            var modeExpected = request.TravelMode.ToString().ToLower();

            Assert.IsNotNull(mode);
            Assert.AreEqual(modeExpected, mode.Value);

            var transitMode         = queryStringParameters.FirstOrDefault(x => x.Key == "transit_mode");
            var transitModeExpected = request.TransitMode.ToEnumString('|');

            Assert.IsNotNull(transitMode);
            Assert.AreEqual(transitModeExpected, transitMode.Value);

            var departureTime         = queryStringParameters.FirstOrDefault(x => x.Key == "departure_time");
            var departureTimeExpected = request.DepartureTime.GetValueOrDefault().DateTimeToUnixTimestamp().ToString(CultureInfo.InvariantCulture);

            Assert.IsNotNull(departureTime);
            Assert.AreEqual(departureTimeExpected, departureTime.Value);
        }
Ejemplo n.º 7
0
        public async Task <RouteEM> GetRoute(Coordinate origin, Coordinate destination, IEnumerable <Coordinate> waypoints)
        {
            var result = new RouteEM();

            var directionRequest = new DirectionsRequest
            {
                Key               = GoogleConfig.ApiKey,
                Origin            = origin.ToLocation(),
                Destination       = destination.ToLocation(),
                Waypoints         = waypoints.Select(p => p.ToLocation()).ToArray(),
                Language          = Language.Russian,
                OptimizeWaypoints = false
            };

            var directionResponse = await GoogleMaps.Directions.QueryAsync(directionRequest);

            result.Status = (Status)directionResponse.Status;

            var firstRoute = directionResponse.Routes.FirstOrDefault();

            if (firstRoute != null)
            {
                foreach (var leg in firstRoute.Legs)
                {
                    result.Legs.Add(LegFromGoogleLeg(leg));
                }
            }

            return(result);
        }
        public async Task <DirectionsResponse> GetDirections(DirectionsRequest directionsRequest)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = _baseUri;
                    var response = await client.GetAsync(_baseUri + constructUriParameters(directionsRequest));

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}");
                    }

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

                    return(JsonConvert.DeserializeObject <DirectionsResponse>(responseString));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                    Console.WriteLine(ex.InnerException.StackTrace);
                }

                return(new DirectionsResponse());
            }
        }
Ejemplo n.º 9
0
        private double _CalculateDistance(LatLong origin, LatLong destination)
        {
            try
            {
                var transitDirectionRequest = new DirectionsRequest
                {
                    Origin        = string.Format("{0},{1}", origin.Latitude, origin.Longitude),
                    Destination   = string.Format("{0},{1}", destination.Latitude, destination.Longitude),
                    TravelMode    = TravelMode.Driving,
                    DepartureTime = DateTime.Now
                };

                DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);
                if (transitDirections.Status == DirectionsStatusCodes.OK)
                {
                    int distanceMeters = 0;
                    foreach (var route in transitDirections.Routes)
                    {
                        foreach (var routeLeg in route.Legs)
                        {
                            distanceMeters += routeLeg.Distance.Value;
                        }
                    }

                    return(distanceMeters / 1000.00);
                }
            }
            catch (Exception ex)
            {
            }

            return(0);
        }
Ejemplo n.º 10
0
        public void GetQueryStringParametersWhenTravelModeDrivingAndDepartureTimeAndTrafficModelAndWayPointsViaTest()
        {
            var request = new DirectionsRequest
            {
                Key           = "key",
                Origin        = new LocationEx(new Address("address")),
                Destination   = new LocationEx(new Address("address")),
                TravelMode    = TravelMode.Driving,
                DepartureTime = DateTime.UtcNow.AddHours(1),
                TrafficModel  = TrafficModel.Best_Guess,
                WayPoints     = new[]
                {
                    new WayPoint(new LocationEx(new Address("waypoint_address")), true)
                }
            };

            var queryStringParameters = request.GetQueryStringParameters();

            Assert.IsNotNull(queryStringParameters);

            var departureTime         = queryStringParameters.FirstOrDefault(x => x.Key == "departure_time");
            var departureTimeExpected = request.DepartureTime.GetValueOrDefault().DateTimeToUnixTimestamp().ToString(CultureInfo.InvariantCulture);

            Assert.IsNotNull(departureTime);
            Assert.AreEqual(departureTimeExpected, departureTime.Value);

            var trafficModel         = queryStringParameters.FirstOrDefault(x => x.Key == "traffic_model");
            var trafficModelExpected = request.TrafficModel.ToString().ToLower();

            Assert.IsNotNull(trafficModel);
            Assert.AreEqual(trafficModelExpected, trafficModel.Value);
        }
Ejemplo n.º 11
0
        private double _CalculateTransit(LatLong origin, LatLong destination, DateTime depTime)
        {
            try
            {
                var transitDirectionRequest = new DirectionsRequest
                {
                    Origin        = string.Format("{0},{1}", origin.Latitude, origin.Longitude),
                    Destination   = string.Format("{0},{1}", destination.Latitude, destination.Longitude),
                    TravelMode    = TravelMode.Transit,
                    DepartureTime = depTime,
                    ApiKey        = GoogleKey
                };

                DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);
                if (transitDirections.Status == DirectionsStatusCodes.OK)
                {
                    string jsonStr = JsonConvert.SerializeObject(transitDirections);
                    return(0);
                }
            }
            catch (Exception)
            {
            }

            return(0);
        }
Ejemplo n.º 12
0
        public async Task <RouteInformation> GetRoute(double startLat, double startLon, double endLat, double endLon)
        {
            DirectionsRequest directionsRequest = new DirectionsRequest()
            {
                Origin      = string.Format("{0},{1}", startLat, startLon),
                Destination = string.Format("{0},{1}", endLat, endLon),
                ApiKey      = Config.MappingConfig.GoogleMapsApiKey
            };

            async Task <RouteInformation> getRoute()
            {
                DirectionsResponse directions = await GoogleMapsApi.GoogleMaps.Directions.QueryAsync(directionsRequest);

                var info = new RouteInformation();

                if (directions != null && directions.Status == DirectionsStatusCodes.OK)
                {
                    var route = directions.Routes.FirstOrDefault();

                    if (route != null)
                    {
                        info.Name        = route.Summary;
                        info.ProcessedOn = DateTime.UtcNow;
                        info.Successful  = true;
                    }
                }

                return(info);
            };

            return(await _cacheProvider.RetrieveAsync <RouteInformation>(string.Format(RouteCacheKey, string.Format("{0}{1}", startLat, startLon).GetHashCode(), string.Format("{0}{1}", endLat, endLon).GetHashCode()), getRoute, CacheLength));
        }
Ejemplo n.º 13
0
        public static string GetTravelTime(string origin, string dest = "50.0154346,36.2284612")
        {
            StringBuilder result = new StringBuilder();

            DirectionsRequest directionsRequest = new DirectionsRequest()
            {
                Origin        = origin,
                Destination   = dest,
                ApiKey        = "AIzaSyDgjuPVvAcN9RtqgFc35OhxJPXNjQ_ugPM",
                Language      = "ru",
                TravelMode    = TravelMode.Transit,
                DepartureTime = DateTime.Now.AddMinutes(10),
            };

            DirectionsResponse directions = GoogleMaps.Directions.Query(directionsRequest);
            var route = directions.Routes.First().Legs.First();
            StaticMapsEngine        staticMapGenerator = new StaticMapsEngine();
            IEnumerable <Step>      steps = route.Steps;
            IList <ILocationString> path  = steps.Select(step => step.StartLocation).ToList <ILocationString>();

            path.Add(steps.Last().EndLocation);

            string url =
                $"https://www.google.com.ua/maps/dir/'{origin}'/{dest}'";

            result.AppendLine($"Отлично, от вас до ВУЗа {route.Distance.Text}");
            result.AppendLine($"Если выйти через 10 минут, то можно добратся за {route.Duration.Text}");
            result.AppendLine($"В ВУЗе вы будете около {route.ArrivalTime.Text}");
            result.AppendLine($"Вот оптимальный маршрут для тебя {url}");
            return(result.ToString());
        }
Ejemplo n.º 14
0
        protected void btnTestar_Click(Object sender, EventArgs e)
        {
            var geocodingRequest = new GeocodingRequest {
                Location = new Location(-19.904356, -43.925691)
            };

            GeocodingResponse geocodingResponse = GoogleMaps.Geocode.Query(geocodingRequest);

            if (geocodingResponse != null && geocodingResponse.Status == Status.OK)
            {
                var drivingDirectionRequest = new DirectionsRequest
                {
                    Origin       = ObterEndereco(geocodingResponse),
                    Destination  = "Avenida Amazonas 7000, Belo Horizonte, MG, Brazil",
                    Sensor       = false,
                    Alternatives = false
                };

                DirectionsResponse drivingDirections = GoogleMaps.Directions.Query(drivingDirectionRequest);
                if (drivingDirections != null && drivingDirections.Status == DirectionsStatusCodes.OK)
                {
                    lblDistancia.Text = string.Format("Distância Total: {0} m.", ObterDistanciaTotal(drivingDirections).ToString());
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// use Google Api to get distance between two address stored in strings
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public float distanceBetweenAddresses(string source, string dest)
        {
            // in case at least one address is empty - return immediately
            if (source == null || dest == null)
            {
                return(-1);
            }

            var drivingDirectionRequest = new DirectionsRequest
            {
                TravelMode  = TravelMode.Walking,
                Origin      = source,
                Destination = dest,
            };

            DirectionsResponse drivingDirections = GoogleMaps.Directions.Query(drivingDirectionRequest);

            if (drivingDirections.Routes.ElementAtOrDefault(0) == null)
            {
                return(-1);
            }

            Route route = drivingDirections.Routes.First();
            Leg   leg   = route.Legs.First();

            return(Convert.ToSingle(leg.Distance.Value / 1000.0));
        }
Ejemplo n.º 16
0
        public static CoordGoogleResponse Send(this DirectionsRequest req, Vehicle v, string serviceScope = "")
        {
            CoordGoogleRequest coordGoogleRequest = JsonConvert.DeserializeObject <CoordGoogleRequest>(JsonConvert.SerializeObject(req));

            coordGoogleRequest.Vehicle = v;
            return(coordGoogleRequest.Send(serviceScope));
        }
Ejemplo n.º 17
0
        public void Directions_WithIcons()
        {
            var depTime = DateTime.Today
                          .AddDays(1)
                          .AddHours(13);

            var request = new DirectionsRequest
            {
                Origin        = "T-centralen, Stockholm, Sverige",
                Destination   = "Kungsträdgården, Stockholm, Sverige",
                TravelMode    = TravelMode.Transit,
                DepartureTime = depTime,
                Language      = "sv",
                ApiKey        = ApiKey
            };

            DirectionsResponse result = GoogleMaps.Directions.Query(request);

            AssertInconclusive.NotExceedQuota(result);

            var route = result.Routes.First();
            var leg   = route.Legs.First();
            var steps = leg.Steps;

            Assert.IsNotEmpty(steps.Where(s =>
                                          s.TransitDetails?
                                          .Lines?
                                          .Vehicle?
                                          .Icon != null));
        }
Ejemplo n.º 18
0
        public void Directions_ExceedingRouteLength()
        {
            var request = new DirectionsRequest
            {
                Origin = "NYC, USA", Destination = "Miami, USA", Waypoints = new string[]
                {
                    "Seattle, USA",
                    "Dallas, USA",
                    "Naginey, USA",
                    "Edmonton, Canada",
                    "Seattle, USA",
                    "Dallas, USA",
                    "Naginey, USA",
                    "Edmonton, Canada",
                    "Seattle, USA",
                    "Dallas, USA",
                    "Naginey, USA",
                    "Edmonton, Canada"
                },
                ApiKey = ApiKey
            };
            var result = GoogleMaps.Directions.Query(request);

            AssertInconclusive.NotExceedQuota(result);
            Assert.AreEqual(DirectionsStatusCodes.MAX_ROUTE_LENGTH_EXCEEDED, result.Status, result.ErrorMessage);
        }
Ejemplo n.º 19
0
        public List <Nanny> DistanceNannys(Mother mother)//this function find all the nannys with distans of 1 KM from mammy
        {
            List <Nanny> distanceNannys = new List <Nanny>();

            foreach (Nanny nanny in GetNannys())
            {
                string motherAddress = mother.BabbySitterAdress.ToString();
                if (motherAddress == null)
                {
                    motherAddress = mother.Address.ToString();
                }
                var walkingDirectionRequest = new DirectionsRequest
                {
                    TravelMode  = TravelMode.Walking,
                    Origin      = motherAddress,
                    Destination = nanny.Address.ToString()
                };
                DirectionsResponse walkingDirections = GoogleMaps.Directions.Query(walkingDirectionRequest);
                Route route = walkingDirections.Routes.First();
                Leg   leg   = route.Legs.First();
                if (leg.Distance.Value < 1000)
                {
                    distanceNannys.Add(nanny);
                }
            }
            return(distanceNannys);
        }
Ejemplo n.º 20
0
        public void Directions_VerifyBounds()
        {
            var request = new DirectionsRequest
            {
                Origin      = "Genk, Belgium",
                Destination = "Brussels, Belgium",
                TravelMode  = TravelMode.Driving,
                ApiKey      = ApiKey
            };

            DirectionsResponse result = GoogleMaps.Directions.Query(request);

            AssertInconclusive.NotExceedQuota(result);

            var route = result.Routes.First();

            Assert.NotNull(route);
            Assert.NotNull(route.Bounds);
            Assert.Greater(route.Bounds.NorthEast.Latitude, 50);
            Assert.Greater(route.Bounds.NorthEast.Longitude, 3);
            Assert.Greater(route.Bounds.SouthWest.Latitude, 50);
            Assert.Greater(route.Bounds.SouthWest.Longitude, 3);
            Assert.Greater(route.Bounds.Center.Latitude, 50);
            Assert.Greater(route.Bounds.Center.Longitude, 3);
        }
Ejemplo n.º 21
0
        public void DirectionsWhenWayÆointsAndOptimizeWaypointsTest()
        {
            var request = new DirectionsRequest
            {
                Key               = this.ApiKey,
                Origin            = new Location("NYC, USA"),
                Destination       = new Location("Miami, USA"),
                Waypoints         = new[] { new Location("Philadelphia, USA") },
                OptimizeWaypoints = true
            };
            var result = GoogleMaps.Directions.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var route = result.Routes.FirstOrDefault();

            Assert.IsNotNull(route);

            var leg = route.Legs.FirstOrDefault();

            Assert.IsNotNull(leg);
            Assert.AreEqual(156084, leg.Steps.Sum(s => s.Distance.Value), 15000);
            Assert.IsTrue(leg.EndAddress.Contains("Philadelphia"));
        }
Ejemplo n.º 22
0
        public Route GetRoute(string origin, string dest)
        {
            var directionsRequest = new DirectionsRequest()
            {
                ApiKey      = "AIzaSyAOzM-wrIj6ANCLEf3XI37mPc_JH0LDx5U",
                Origin      = origin,
                Destination = dest,
            };

            DirectionsResponse directions = GoogleMaps.Directions.Query(directionsRequest);

            if (!directions.Routes.Any() || !directions.Routes.First().Legs.Any())
            {
                return(null);
            }

            var leg = directions.Routes.First().Legs.First();
            var distanceInMeters  = (double)leg.Distance.Value;
            var distanceInMiles   = distanceInMeters * 0.000621371192237;
            var durationInMinutes = leg.Duration.Value.TotalMinutes;

            return(new Route {
                DistanceInMiles = distanceInMiles, DurationInMinutes = durationInMinutes
            });
        }
Ejemplo n.º 23
0
        public void BuildDirectionsUrl_ShouldFail_ForInvalidRequest()
        {
            var request = new DirectionsRequest();

            var result = DirectionsUrlFactory.BuildDirectionsUrl(request, "APIKEY");

            Assert.True(result.IsFailure);
        }
Ejemplo n.º 24
0
        private void _SaveTransitDetails(int originId, int destinationId, DateTime depTime)
        {
            try
            {
                using (TravelogyDevEntities1 context = new TravelogyDevEntities1())
                {
                    var origin      = context.Places.Find(originId);
                    var destination = context.Places.Find(destinationId);

                    if (origin == null || destination == null)
                    {
                        return;
                    }

                    var transitDirectionRequest = new DirectionsRequest
                    {
                        Origin        = origin.Name,
                        Destination   = destination.Name,
                        TravelMode    = TravelMode.Transit,
                        DepartureTime = depTime,
                        ApiKey        = GoogleKey
                    };

                    DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);

                    if (transitDirections.Status == DirectionsStatusCodes.OK)
                    {
                        string jsonStr      = JsonConvert.SerializeObject(transitDirections);
                        string transitStart = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().DepartureTime.Text;
                        var    _dbVal       = context.Transits.Where(p => p.SourceId == originId &&
                                                                     p.DestinationId == destinationId &&
                                                                     p.departure_time == transitStart);

                        if (_dbVal.Count() == 0)
                        {
                            var _transitDetail = new Transit();

                            _transitDetail.SourceId      = originId;
                            _transitDetail.DestinationId = destinationId;

                            _transitDetail.Distance       = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value / 1000;
                            _transitDetail.departure_time = transitStart;
                            _transitDetail.arrival_time   = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().ArrivalTime.Text;
                            _transitDetail.Transit_Time   = (decimal)transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().Duration.Value.TotalHours;

                            context.Transits.Add(_transitDetail);

                            context.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string _debug = ex.Message;
            }
        }
Ejemplo n.º 25
0
 private static void addStudentHomeMapMarker(DirectionsRequest directionsRequest, List <MapMarker> mapMarkers)
 {
     mapMarkers.Add(new MapMarker  // Home
     {
         Color       = MapFeatureColor.Blue,
         Label       = 'H',
         Address     = directionsRequest.OriginLocation.Address,
         Coordinates = directionsRequest.OriginLocation.Coordinates
     });
 }
Ejemplo n.º 26
0
        public async Task <IActionResult> Post([FromBody] DirectionsRequest directionsRequest)
        {
            var directions = await _mapService.GetDirections(directionsRequest);

            if (directions == null)
            {
                return(NotFound());
            }
            return(Ok(directions));
        }
Ejemplo n.º 27
0
        public void GetQueryStringParametersTest()
        {
            var request = new DirectionsRequest
            {
                Origin      = new Location("test"),
                Destination = new Location("test")
            };

            Assert.DoesNotThrow(() => request.GetQueryStringParameters());
        }
Ejemplo n.º 28
0
 private static void addSchoolMapMarker(DirectionsRequest directionsRequest, List <MapMarker> mapMarkers)
 {
     mapMarkers.Add(new MapMarker  // School
     {
         Color       = MapFeatureColor.Blue,
         Label       = 'S',
         Address     = directionsRequest.DestinationLocation.Address,
         Coordinates = directionsRequest.DestinationLocation.Coordinates
     });
 }
Ejemplo n.º 29
0
        public async Task <DirectionsResult> GetTransitAsync(DirectionsRequest request)
        {
            Coordinate       from, to;
            ResolvedLocation resolvedStart, resolvedEnd = null;

            if (request.UserId != null)
            {
                var locationBias = (await locationsService.ResolveAsync(request.UserId, new UnresolvedLocation(UnresolvedLocation.Home))) ?? Vienna;
                resolvedStart = await locationsService.ResolveAsync(request.UserId, request.StartAddress, locationBias);

                if (null != resolvedStart)
                {
                    resolvedEnd = await locationsService.ResolveAsync(request.UserId, request.EndAddress, resolvedStart);
                }
            }
            else
            {
                var locationBias = Vienna;
                resolvedStart = await locationsService.ResolveAnonymousAsync(request.StartAddress, locationBias);

                if (null != resolvedStart)
                {
                    resolvedEnd = await locationsService.ResolveAnonymousAsync(request.EndAddress, resolvedStart);
                }
            }
            if (null == resolvedStart)
            {
                throw new LocationNotFoundException(request.StartAddress);
            }
            if (null == resolvedEnd)
            {
                throw new LocationNotFoundException(request.EndAddress);
            }
            from = resolvedStart.Coordinate;
            to   = resolvedEnd.Coordinate;
            var plan = await transitDirectionProvider.GetDirectionsAsync(new TransitDirectionsRequest
            {
                ArriveBy = request.ArriveBy,
                DateTime = request.DateTime,
                From     = from,
                To       = to
            });

            if (null == plan)
            {
                return(null);
            }
            await directionsCache.PutAsync(plan.Id, plan);

            return(new DirectionsResult()
            {
                CacheKey = plan.Id,
                TransitDirections = plan.GetTransitDirections()
            });
        }
Ejemplo n.º 30
0
        public void GetQueryStringParametersWhenKeyIsEmptyTest()
        {
            var request = new DirectionsRequest
            {
                Key = string.Empty
            };

            var exception = Assert.Throws <ArgumentException>(() => request.GetQueryStringParameters());

            Assert.AreEqual("'Key' is required", exception.Message);
        }