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);
            }
        }
Example #3
0
        private static Leg PrintDirections(DirectionsResponse directions)
        {
            Route route = directions.Routes.First();
            Leg   leg   = route.Legs.First();

            return(leg);
        }
Example #4
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));
        }
Example #5
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());
        }
Example #6
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));
        }
Example #7
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));
        }
Example #8
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());
                }
            }
        }
Example #9
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);
        }
        void HandleDirectionsResponse(DirectionsResponse response)
        {
            var positions = new List <Vector3>();

            foreach (var leg in response.Routes[0].Legs)
            {
                foreach (var step in leg.Steps)
                {
                    var localOffset = transform.GetPositionFromGeoCoordinate(step.Maneuver.Location);
                    localOffset.y = 1000f;

                    // TODO: we can improve this by having a reference to an elevation component.
                    // Elevation could "decorate" this.
                    RaycastHit hit;
                    if (Physics.Raycast(localOffset + transform.position, Vector3.down, out hit, Mathf.Infinity, _mask))
                    {
                        localOffset.y = hit.point.y;
                        positions.Add(localOffset);
                    }
                }
            }

#if UNITY_5_5_OR_NEWER
            _lineRenderer.numPositions = positions.Count;
#else
            _lineRenderer.SetVertexCount(positions.Count);
#endif
            _lineRenderer.SetPositions(positions.ToArray());
        }
Example #11
0
        public DirectionsResponse Run(string ID, string Start, string End, string WayPoints, bool AvoidHighways, bool AvoidTolls, bool AvoidFerries, string Mode, string Unit, bool Optimize)
        {
            string avoid = "";

            if (AvoidHighways)
            {
                avoid = "highways|";
            }
            if (AvoidTolls)
            {
                avoid = "tolls|";
            }
            if (AvoidFerries)
            {
                avoid = "ferries|";
            }
            if (!string.IsNullOrWhiteSpace(avoid))
            {
                avoid = avoid.Remove(avoid.LastIndexOf('|'));
            }

            DirectionsResponse result = GoogleAPIHelper.GetDirections(Start, End, WayPoints, Mode.ToLowerInvariant(), avoid, Unit.ToLowerInvariant(), Optimize);

            return(result);
        }
Example #12
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);
        }
Example #13
0
    void HandleDirectionsResponse(DirectionsResponse res)
    {
        var    data = JsonConvert.SerializeObject(res, Formatting.Indented, JsonConverters.Converters);
        string sub  = data.Substring(0, data.Length > 5000 ? data.Length : data.Length) + "\n. . . ";
        int    summary_index;
        string _summary;

        summary_index = sub.IndexOf("summary");
        _summary      = sub.Substring(summary_index + 10, 60);

        int    duration_index;
        int    distance_index;
        string _duration;
        string _distance;

        duration_index = _summary.IndexOf("duration");
        distance_index = _summary.IndexOf("distance");
        _duration      = _summary.Substring(duration_index + 10, 4);
        _distance      = _summary.Substring(distance_index + 10, 4);

        int _durationnum;

        _durationnum = int.Parse(_duration);
        _durationnum = _durationnum / 60;
        _duration    = _durationnum.ToString();

        _resultsText.text = "時間: " + _duration + " mins(分鐘)" + "\n" + "距離:" + _distance + " m(公尺)";
    }
Example #14
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);
        }
Example #15
0
    void HandleDirectionsResponse(DirectionsResponse response)
    {
        if (null == response.Routes || response.Routes.Count < 1)
        {
            return;
        }

        var meshData = new MeshData();
        var dat      = new List <Vector3>();

        foreach (var point in response.Routes[0].Geometry)
        {
            Vector3 p = Conversions.GeoToWorldPosition(point.x, point.y, _map.CenterMercator, _map.WorldRelativeScale).ToVector3xz();
            p = Conversions.GeoToWorldPosition(point.x, point.y, _map.CenterMercator, _map.WorldRelativeScale).ToVector3xz()
                + tht.GetOffsetPosition();
            dat.Add(p);
        }

        var feat = new VectorFeatureUnity();

        feat.Points.Add(dat);
        //if (movePerfab != null && movePerfab.Length > 0) MoveTheCar(dat);

        foreach (MeshModifier mod in MeshModifiers.Where(x => x.Active))
        {
            var lineMod = mod as LineMeshModifier;
            if (lineMod != null)
            {
                lineMod.Width = _directionsLineWidth / _map.WorldRelativeScale;
            }
            mod.Run(feat, meshData, _map.WorldRelativeScale);
        }
        Debug.Log("CreateGameObject");
        CreateGameObject(meshData);
    }
Example #16
0
        /// <summary>
        /// Log directions response to UI.
        /// </summary>
        /// <param name="res">Res.</param>
        private void HandleDirectionsResponse(DirectionsResponse res)
        {
            var    data = JsonConvert.SerializeObject(res, Formatting.Indented, JsonConverters.Converters);
            string sub  = data.Substring(0, data.Length > 5000 ? 5000 : data.Length) + "\n. . . ";

            _resultsText.text = sub;
        }
 public MainPageViewModel()
 {
     myMap            = new Map();
     rService         = new RouteService();
     dr               = new DirectionsResponse();
     ShowRouteCommand = new Command(async() => await AddPolylineAsync());
 }
Example #18
0
        void HandleDirectionsResponse(DirectionsResponse response)
        {
            if (null == response.Routes || response.Routes.Count < 1)
            {
                return;
            }

            var meshData = new MeshData();
            var dat      = new List <Vector3>();

            foreach (var point in response.Routes[0].Geometry)
            {
                dat.Add(Conversions.GeoToWorldPosition(point.x, point.y, _map.CenterMercator, _map.WorldRelativeScale).ToVector3xz());
            }

            var feat = new VectorFeatureUnity();

            feat.Points.Add(dat);

            foreach (MeshModifier mod in MeshModifiers.Where(x => x.Active))
            {
                mod.Run(feat, meshData, _map.WorldRelativeScale);
            }

            CreateGameObject(meshData);
        }
Example #19
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);
        }
Example #20
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);
        }
Example #21
0
 /// <summary>
 /// If the response status indicates fail because of quota exceeded - mark test as inconclusive.
 /// </summary>
 public static void NotExceedQuota(DirectionsResponse response)
 {
     if (response?.Status == DirectionsStatusCodes.OVER_QUERY_LIMIT)
     {
         throw new InconclusiveException(QuotaExceedMessage);
     }
 }
Example #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
            });
        }
Example #23
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;
            }
        }
Example #24
0
    public void InstantiateController(DirectionsResponse res)
    {
        Debug.Log("Instantiate waypoint | Count: " + res.Waypoints.Count);

        this.waypointsToSpawn = res.Waypoints;

        Debug.Log("Instantiate routes | Count: " + res.Routes.Count);

        this.routes = res.Routes;
    }
Example #25
0
        private static void ProcessResponse(DirectionsResponse response)
        {
            foreach (var journey in response.Journeys)
            {
                var leg = journey.Legs.Skip(1).Take(1).First();

                Console.WriteLine($"Bus No: {leg.LinkedTransitRouteInfo.LineName} (" +
                                  $"{leg.LinkedTransitTripInfo.Headsign}");
                Console.WriteLine(new string('-', 20));
                leg.ScheduledStopCalls.ForEach(stop => Console.WriteLine(stop.Stop.Name));
                Console.WriteLine(new string('-', 20));

                TransitStopScheduledCall firstStop = null;
                TransitStopScheduledCall lastStop  = null;
                var longestBusDistance             = 0.0;

                for (int i = 0; i < leg.ScheduledStopCalls.Count; i++)
                {
                    if (i + 3 >= leg.ScheduledStopCalls.Count - 3)
                    {
                        break;
                    }

                    var lengthTest = CalculateDistanceAlongStops(leg.ScheduledStopCalls.GetRange(i, 3));

                    if (lengthTest > longestBusDistance)
                    {
                        longestBusDistance = lengthTest;
                        firstStop          = leg.ScheduledStopCalls[i];
                        lastStop           = leg.ScheduledStopCalls[i + 3];
                    }
                }

                if (firstStop == null || lastStop == null)
                {
                    throw new Exception("A three stop hop could not be found.");
                }

                var totalDistance = CalculateDistanceAlongStops(leg.ScheduledStopCalls);

                var firstWalkDistance = CalculateDistanceAlongStops(leg.ScheduledStopCalls.GetRange(0, leg.ScheduledStopCalls.IndexOf(firstStop) + 1));

                var lastWalkDistance =
                    CalculateDistanceAlongStops(leg.ScheduledStopCalls.GetRange(
                                                    leg.ScheduledStopCalls.IndexOf(lastStop),
                                                    leg.ScheduledStopCalls.Count - leg.ScheduledStopCalls.IndexOf(lastStop)));

                Console.WriteLine($"Best value for three stop hop: {firstStop.Stop.Name} to {lastStop.Stop.Name}.");
                Console.WriteLine($"Total bus distance: {longestBusDistance:N2} miles");
                Console.WriteLine($"Total journey distance: {totalDistance:N2} miles");
                Console.WriteLine($"First walk distance: {firstWalkDistance:N2} miles");
                Console.WriteLine($"Last walk distance: {lastWalkDistance:N2} miles");
                break;
            }
        }
Example #26
0
        public void SerializesAndDeserializesBasic()
        {
            // First, deserialize the example response
            DirectionsResponse basicResp = _directions.Deserialize(_basicResponse);

            // Then deserialize it back to a string.
            string basicReserialized = _directions.Serialize(basicResp);

            // Ensure the two match
            Assert.AreEqual(_basicResponse, basicReserialized);
        }
Example #27
0
        public void WriteToFile(Student student, DirectionsResponse directionsResponse)
        {
            var directionsResponseDirectory = getDirectionsResponseDirectory();
            var file       = new FileInfo($"{directionsResponseDirectory}{student.ID}.json");
            var fileStream = getFileStreamForFile(file);

            using (var textWriter = new StreamWriter(fileStream))
            {
                textWriter.Write(JsonConvert.SerializeObject(directionsResponse, Formatting.Indented));
            }
        }
Example #28
0
        /// <summary>
        ///return the distance by google maps(km)
        /// </summary>
        /// <param name="source">nanny address</param>
        /// <param name="dest">mother address</param>
        /// <returns></returns>
        public static double distance(string source, string dest)//distance by google maps
        {
            var v = new DirectionsRequest {
                TravelMode = TravelMode.Walking, Origin = source, Destination = dest
            };
            DirectionsResponse direction = GoogleMapsApi.GoogleMaps.Directions.Query(v);
            Route route = direction.Routes.First();
            Leg   leg   = route.Legs.First();

            return((double)leg.Distance.Value / 1000);
        }
        public void SerializesAndDeserializesBasic()
        {
            // First, deserialize the example response
            DirectionsResponse basicResp = this.directions.Deserialize(this.basicResponse);

            // Then deserialize it back to a string.
            string basicReserialized = JsonConvert.SerializeObject(basicResp);

            // Ensure the two match
            Assert.AreEqual(this.basicResponse, basicReserialized);
        }
Example #30
0
        public void SerializesAndDeserializesWithSteps()
        {
            // First, deserialize the example response.
            DirectionsResponse withStepsResp = _directions.Deserialize(_responseWithSteps);

            // Then deserialize it back to a string.
            string withStepsReserialized = _directions.Serialize(withStepsResp);

            // Ensure the two match.
            Assert.AreEqual(_responseWithSteps, withStepsReserialized);
        }
Example #31
0
        private static Route MapRoute(Location origin, Location destination, DirectionsResponse result)
        {
            var points = result.Routes.First()
                .Legs.SelectMany(leg => leg.Steps)
                .Select(step => new RouteLeg(
                    new Position(step.StartLocation.Latitude, step.StartLocation.Longitude),
                    new Position(step.EndLocation.Latitude, step.EndLocation.Longitude),
                    step.Distance.Value))
                .ToArray();

            return new Route(origin, destination, points);
        }
Example #32
0
        public void CreateDirectionsResponse()
        {
            Location[] locations = new Location[this.RouteLocations.Count];
            for (int a = 0; a < locations.Length; a++)
            {
                locations[a] = new Location(this.RouteLocations[a].Latitude, this.RouteLocations[a].Longitude);
            }

            String[] wayPoints = new String[locations.Length - 2];
            for (int a = 1; a < locations.Length - 1; a++)
            {
                wayPoints[a - 1] = locations[a].LocationString;
            }

            DirectionsRequest directionsRequest = new DirectionsRequest()
            {
                Origin = locations[0].LocationString,
                Destination = locations[locations.Length - 1].LocationString,
                Waypoints = wayPoints,
                TravelMode = TravelMode.Driving,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            this.DirectionsResponse = GoogleMapsApi.GoogleMaps.Directions.Query(directionsRequest);
        }
Example #33
0
        public double GetDistance(DirectionsResponse directionsResponse)
        {
            double distance = 0.0;

            Leg[] legs = directionsResponse.Routes.ElementAt(0).Legs.ToArray();
            for (int a = 0; a < legs.Length; a++)
            {
                distance += legs[a].Distance.Value;
            }

            return distance / 1000.0;
        }
Example #34
0
		private static void PrintDirections(DirectionsResponse directions)
		{
			Route route = directions.Routes.First();
			Leg leg = route.Legs.First();

			foreach (Step step in leg.Steps)
			{
				Console.WriteLine(StripHTML(step.HtmlInstructions));
			}

			Console.WriteLine();
		}
Example #35
0
        private static void PrintDirections(DirectionsResponse directions)
        {
            Route route = directions.Routes.First();
            Leg leg = route.Legs.First();

            foreach (Step step in leg.Steps)
            {
                Console.WriteLine(StripHTML(step.HtmlInstructions));

                var localIcon = step.TransitDetails?.Lines?.Vehicle?.LocalIcon;
                if (localIcon != null)
                    Console.WriteLine("Local sign: " + localIcon);
            }

            Console.WriteLine();
        }