/* 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 #2
0
 public void Add(Vector3 position, TravelMode state)
 {
     lock (m_lock) {
         m_listOfPositions.Add(position);
         m_listOfStates.Add(state);
     }
 }
Example #3
0
        /// <summary>
        /// Calcula a distância entre <paramref name="origin"></paramref> e <paramref name="destination"></paramref> para um determinado modo de transporte <paramref name="mode"></paramref>,
        /// </summary>
        /// <param name="origin">Origem</param>
        /// <param name="destination">Destino</param>
        /// <param name="mode">Modo de transporte</param>
        /// <returns>Distância entre <paramref name="origin"></paramref> e <paramref name="destination"></paramref></returns>
        public int DistanceBetween(Location origin, Location destination, TravelMode mode)
        {
            string o = $"{Convert.ToDouble(origin.lat.ToString())},{Convert.ToDouble(origin.lng.ToString())}";
            string d = $"{Convert.ToDouble(destination.lat.ToString())},{Convert.ToDouble(destination.lng.ToString())}";

            string url = $"{MatrixBaseUrl}language=pt-PT&units=metric&origins={o}&destinations={d}&key={ApiKey}";

            var root = Magic <DistanceMatrix.RootObject>(url);

            if (root.status != "OK")
            {
                return(-1);                     // TODO: throw new Custom Exception
            }
            if (root.rows.Count < 1)
            {
                return(-1);
            }
            if (root.rows[0].elements.Count < 1)
            {
                return(-1);
            }
            if (root.rows[0].elements[0].status != "OK")
            {
                return(-1);
            }
            return(root.rows[0].elements[0].distance.value);
        }
        /// <summary>
        /// Add Distance to be calculated.
        /// All possible combinations of origins and destinations are calculated
        /// </summary>
        /// <param name="mode">Select the type of Travel</param>
        /// <param name="origins">List of origins for the calculations</param>
        /// <param name="destinations">List of destinations used for the calculation</param>
        /// <returns></returns>
        public static async Task CalculateDistances(TravelMode mode, List <LatLng> origins, List <LatLng> destinations)
        {
            if (_js is null)
            {
                return;
            }

            await _semaphore.WaitAsync();

            _mode         = mode;
            _origins      = origins;
            _destinations = destinations;
            var matrix = new OriginDestinationMatrix
            {
                Origins      = origins,
                Destinations = destinations,
                TravelMode   = _mode switch
                {
                    TravelMode.Driving => "DRIVING",
                    TravelMode.Walking => "WALKING",
                    TravelMode.Bicycling => "BICYCLING",
                    TravelMode.Transit => "TRANSIT",
                    _ => "DRIVING"
                }
            };

            var json = JsonConvert.SerializeObject(matrix);
            await _js.InvokeAsync <string>("getDistance", json);
        }
        public IDistanceMatrixData GetDistanceMatrix(IEnumerable <string> locations, TravelMode travelMode)
        {
            _activeDistanceMatrixConfiguration.Destinations = _activeDistanceMatrixConfiguration.Origins = locations.ToArray();
            _activeDistanceMatrixConfiguration.TravelMode   = _activeDistanceMatrixConfiguration.TravelMode;

            DistanceMatrixResponse response = new DistanceMatrixResponse()
            {
                Origin_Addresses      = Array.Empty <string>(),
                Destination_Addresses = Array.Empty <string>(),
                Rows = Array.Empty <Row>(),
            };

            if (locations.Count() < MAX_REQUEST_DESTINATIONS_COUNT)
            {
                var requests = BuildRequests(locations, _activeDistanceMatrixConfiguration);
                requests.ForEach(async request =>
                {
                    var res  = await HttpRequest.Post <DistanceMatrixResponse>(request);
                    response = response.Merge(res);
                });
            }
            else
            {
                throw new ArgumentException("MAX_REQUEST_DESTINATIONS_COUNT value exceeded");
            }
            return(new DistanceMatrixData(response));
        }
 private void GetTravelTimeForMode(Location origin, Location destination, List<TravelTime> list, TravelMode mode)
 {
     var time = this.GetTravelTime(origin, destination, mode);
     if (time != null)
     {
         list.Add(time);
     }
 }
 public void Add(Vector3 position, TravelMode state)
 {
     lock (m_lock)
     {
         m_listOfPositions.Add(position);
         m_listOfStates.Add(state);
     }
 }
Example #8
0
        public void AddEdge(int e1, int e2, TravelMode mode)
        {
            Edge edge = new Edge();

            edge.Start = e1;
            edge.End   = e2;
            edge.Mode  = mode;
            m_edges.Add(edge);
        }
        public void Notify_Interacted(FactionDef def, TravelMode mode, int profit)
        {
            IEnumerable <Objective> objectives = GetObjectives.Where(o => o.CurrentState == MOState.Active && o.def.type == ObjectiveType.Travel);

            foreach (Objective objective in objectives)
            {
                objective.travelTracker.Notify_Interacted(def, mode, profit);
            }
        }
Example #10
0
        private bool ValidateTraversal(TravelMode Mode)
        {
            if ((Mode == TravelMode.Car) && OnlyFoot)
            {
                return(false);
            }

            return(true);
        }
        public string GetTravelMode()
        {
            if (TravelMode == TravelModeType.Default)
            {
                return(string.Empty);
            }

            return(TravelMode.ToString().ToLower());
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            if (sender == Hplus)
            {
                map1.Heading = (map1.Heading + 12);
            }
            else if (sender == Hmins)
            {
                map1.Heading = (map1.Heading - 12);
            }
            else if (sender == TrMod)
            {
                if (RTrav == TravelMode.Driving)
                {
                    RTrav = TravelMode.Walking;
                    TrMod.Content = "Walk";
                }
                else
                {
                    RTrav = TravelMode.Driving;
                    TrMod.Content = "Drive";
                }
          
            }
            else if (sender == Optim)
            {
                if (ROpti == RouteOptimization.MinimizeTime)
                {
                    ROpti = RouteOptimization.MinimizeDistance;
                    Optim.Content = "Shortest";
                }
                else
                {
                    ROpti = RouteOptimization.MinimizeTime;
                    Optim.Content = "Quickest";
                }
            }
            else if (sender == Rutte)
            {
                if (geoQ.IsBusy == true){
                    geoQ.CancelAsync();
                }

                geoQ.InitialHeadingInDegrees = map1.Heading;

                geoQ.RouteOptimization = ROpti;
                geoQ.TravelMode = RTrav;

                List<GeoCoordinate> MyWayPoints = new List<GeoCoordinate>();
                MyWayPoints.Add(startMark.GeoCoordinate);
                MyWayPoints.Add(enddMark.GeoCoordinate);

                geoQ.Waypoints = MyWayPoints;
                geoQ.QueryAsync();
            }
    }
Example #13
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (sender == Hplus)
            {
                map1.Heading = (map1.Heading + 12);
            }
            else if (sender == Hmins)
            {
                map1.Heading = (map1.Heading - 12);
            }
            else if (sender == TrMod)
            {
                if (RTrav == TravelMode.Driving)
                {
                    RTrav         = TravelMode.Walking;
                    TrMod.Content = "Walk";
                }
                else
                {
                    RTrav         = TravelMode.Driving;
                    TrMod.Content = "Drive";
                }
            }
            else if (sender == Optim)
            {
                if (ROpti == RouteOptimization.MinimizeTime)
                {
                    ROpti         = RouteOptimization.MinimizeDistance;
                    Optim.Content = "Shortest";
                }
                else
                {
                    ROpti         = RouteOptimization.MinimizeTime;
                    Optim.Content = "Quickest";
                }
            }
            else if (sender == Rutte)
            {
                if (geoQ.IsBusy == true)
                {
                    geoQ.CancelAsync();
                }

                geoQ.InitialHeadingInDegrees = map1.Heading;

                geoQ.RouteOptimization = ROpti;
                geoQ.TravelMode        = RTrav;

                List <GeoCoordinate> MyWayPoints = new List <GeoCoordinate>();
                MyWayPoints.Add(startMark.GeoCoordinate);
                MyWayPoints.Add(enddMark.GeoCoordinate);

                geoQ.Waypoints = MyWayPoints;
                geoQ.QueryAsync();
            }
        }
Example #14
0
        public int ValueForMode(TravelMode mode)
        {
            int value = Value(mode);

            if (any)
            {
                return(value);
            }
            return(value * factions.Count);
        }
Example #15
0
        public NavMeshInstance GetNavMesh(string name, TravelMode mode, int startNode, bool random, bool reverse, bool allowU, int timeOut)
        {
            if (m_navMeshes.ContainsKey(name))
            {
                NavMeshInstance navMeshInstance = new NavMeshInstance(m_navMeshes[name], mode, startNode, random, reverse, allowU, timeOut);
                return navMeshInstance;
            }

            throw new System.Exception("NavMesh with name: " + name + " not found.");
        }
Example #16
0
        public override bool CanBeTraversedUsingMode(TravelMode Mode)
        {
            if (Mode.HasFlag(TravelMode.Walking) && !Mode.HasFlag(TravelMode.Car))
            {
                if (this.Tags.ContainsKey("foot"))
                {
                    string footValue = this.Tags["foot"];
                    if (footValue == "no")
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }

                //if (this.Tags.ContainsKey("highway"))
                //{
                //    string highwayValue = this.Tags["highway"];
                //    if (highwayValue == "primary" || highwayValue == "secondary" || highwayValue == "tertiary" ||
                //        highwayValue == "unclassified" || highwayValue == "residential" || highwayValue == "service" ||
                //        highwayValue == "living_street" || highwayValue == "pedestrian" || highwayValue == "track" ||
                //        highwayValue == "footway" || highwayValue == "bridleway" || highwayValue == "steps" ||
                //        highwayValue == "path" || highwayValue == "bridleway" || highwayValue == "crossing" ||
                //        highwayValue == "trunk_link")
                //    {
                //        return true;
                //    }
                //    else
                //        return false;
                //}
            }
            else if (!Mode.HasFlag(TravelMode.Walking) && (Mode.HasFlag(TravelMode.Car)))
            {
                if (this.Tags.ContainsKey("highway"))
                {
                    string highwayValue = this.Tags["highway"];
                    if (highwayValue == "motorway" || highwayValue == "trunk" || highwayValue == "primary" ||
                        highwayValue == "secondary" || highwayValue == "tertiary" || highwayValue == "unclassified" ||
                        highwayValue == "residential" || highwayValue == "motorway_link" || highwayValue == "trunk_link" ||
                        highwayValue == "primary_link" || highwayValue == "secondary_link" || highwayValue == "tertiary_link" ||
                        highwayValue == "living_street" || highwayValue == "road")
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #17
0
        /* CConnection */
        public override double GetTravelTime(string date, double arrivalTime, TravelMode Mode)
        {
            double time         = 0;
            double trafficDelay = 0;

            if (!CanBeTraversedUsingMode(Mode))
            {
                return(double.PositiveInfinity);
            }
            if (arrivalTime > this.SrcArrivalTime)
            {
                return(double.PositiveInfinity);
            }
            if (ResidualCapacity == 0)
            {
                return(double.PositiveInfinity);
            }

            if (Mode.HasFlag(Routing.TravelMode.Carpool))
            {
                //ServiceDates.Contains(date)
                if (!CCValidityStartDayTable.IsValidDate(date, this.Carpooler.Id, this.Carpooler.Activated))
                {
                    return(double.PositiveInfinity);
                }
                else
                {
                    time = (DstArrivalTime - SrcArrivalTime);

                    /* For Car, the time is traffic dependent */
                    if (TrafficReport != null)
                    {
                        double minDistanceFromTraffic;
                        minDistanceFromTraffic = Math.Min(this.TrafficDistanceFromSource, this.TrafficDistanceFromDestination);
                        trafficDelay           = addTrafficDelay(time, minDistanceFromTraffic, TrafficReport);
                    }

                    WaitingTime = (SrcArrivalTime - arrivalTime);
                    time       += WaitingTime + trafficDelay;

                    DepartureTime = (int)SrcArrivalTime;

                    if (time < 0 || WaitingTime < 0)
                    {
                        throw new Exception("negative time value");
                    }
                }
            }
            else
            {
                time = double.PositiveInfinity;
            }

            return(time);
        }
Example #18
0
            private double GetObjValueBasedOnDistance(Connection C, TravelMode Modes)
            {
                //if (!(C is RConnection))
                /* Added TConnection in order to also consider carpooling Tconnection network */
                if (!(C is RConnection) && !(C is TConnectionForCarpooling))
                {
                    return(double.PositiveInfinity);
                }

                return(minObjValue + C.GetDistance(Modes));
            }
Example #19
0
        public bool FactionInteractionComplete(Dictionary <FactionDef, int> pairs, TravelMode mode)
        {
            int amountAny = (mode == TravelMode.Raid ? raidAmount : tradeAmount);
            int amount    = amountAny * factions.Count;

            if (any)
            {
                return(pairs.Any(k => k.Value == amountAny));
            }
            return(factions.All(pairs.Keys.Contains) && pairs.Sum(k => k.Value) == amount);
        }
Example #20
0
        public async Task <RouteInformation> GetRouteInformationAsync(string location, string destination,
                                                                      TravelMode travelMode, int arrivalTimeEpoch)
        {
            //setup the call params
            var callParams = $"?key={_apiKey}&origin={location}&destination={destination}&mode={travelMode.ToString().ToLower()}";

            if (travelMode == TravelMode.Transit)
            {
                callParams += $"&arrival_time={arrivalTimeEpoch.ToString()}";
            }

            //call the maps api
            var apiReq = await _client.GetAsync(callParams);

            //return the results
            var res = new RouteInformation()
            {
                Success = apiReq.IsSuccessStatusCode
            };

            if (res.Success)
            {
                var jo = JObject.Parse(await apiReq.Content.ReadAsStringAsync());

                //check route was actually created
                if (!jo["routes"].HasValues)
                {
                    res.Success = false;
                    return(res);
                }

                var joRoute = jo["routes"][0]["legs"][0];

                //get duration and distance
                res.TravelDistance = joRoute["distance"]["value"].ToObject <int>();
                res.TravelDuration = joRoute["duration"]["value"].ToObject <int>();

                if (travelMode == TravelMode.Transit)
                {
                    //calculate departure time based on route information
                    res.ArrivalTime   = joRoute["arrival_time"]["value"].ToObject <int>();
                    res.DepartureTime = joRoute["departure_time"]["value"].ToObject <int>();
                }
                else
                {
                    //calculate departure time based on arrival time
                    res.ArrivalTime   = arrivalTimeEpoch;
                    res.DepartureTime = arrivalTimeEpoch - res.TravelDuration;
                }
            }

            return(res);
        }
Example #21
0
        public RoutingPath(List <Connection> Connections, string Date, double StartTime, TravelMode Modes)
        {
            this.Connections = new List <Connection>();

            this.Connections.AddRange(Connections);
            this.Legs      = new List <SolutionLeg>();
            this.Date      = Date;
            this.StartTime = StartTime;
            this.Modes     = Modes;

            this.ConstructLegs();
        }
Example #22
0
            public void Update(Connection C, TravelMode Modes, Node Target = null)
            {
                v = C.GetDestination();

                if (ObjValues.ContainsKey(v))
                {
                    return; // already processed
                }
                if (!Q.TryGetPriority(v, out crntObjValue))
                {
                    crntObjValue = double.PositiveInfinity;
                }

                double ObjValue = 0.0;

                if (Func == ObjFunction.Distance)
                {
                    ObjValue = GetObjValueBasedOnDistance(C, Modes);
                }
                else if (Func == ObjFunction.Time)
                {
                    ObjValue = GetObjValueBasedOnTime(C, Modes);
                }
                else if (Func == ObjFunction.Weighted)
                {
                    ObjValue = GetWeightedObjValue(C, Modes);
                }


                /* Check if the PT of this connection was already taken or there is at least one carpooling leg on the previous connections */
                /* WARNING: this function would take too much time to run */
                //bool cutConnection = false;
                //cutConnection = checkConstraints(C);
                //if (cutConnection)
                //    ObjValue = double.PositiveInfinity;


                if (ObjValue < crntObjValue)
                {
                    Q[v] = ObjValue;
                    if (Parent.ContainsKey(v))
                    {
                        Parent[v]      = C;
                        ArrivalTime[v] = ArrivalTime[C.GetSource()] + C.GetTravelTime(Date, ArrivalTime[C.GetSource()], Modes);
                    }
                    else
                    {
                        Parent.Add(v, C);
                        ArrivalTime.Add(v, ArrivalTime[C.GetSource()] + C.GetTravelTime(Date, ArrivalTime[C.GetSource()], Modes));
                    }
                }
            }
        public TravelTime GetTravelTime(Location origin, Location destination, TravelMode mode)
        {
            string originString = StringForm(origin);
            string destinationString = StringForm(destination);
            var request = new DirectionsRequest()
            {
                ApiKey = apiKey,
                Origin = originString,
                Destination = destinationString,
                TravelMode = mode,
                DepartureTime = DateTime.Now,
            };

            var response = GoogleMapsApi.GoogleMaps.Directions.Query(request);

            var route = response.Routes.FirstOrDefault();
            if (route != null)
            {
                // For routes that contain no waypoints, the route will consist of a single "leg".
                var leg = route.Legs.FirstOrDefault();
                if (leg != null)
                {
                    // Get the origin and destination's lat/long if not yet known.
                    origin.Latitude = origin.Latitude ?? leg.StartLocation.Latitude.ToString();
                    origin.Longitude = origin.Longitude ?? leg.StartLocation.Longitude.ToString();

                    destination.Latitude = destination.Latitude ?? leg.EndLocation.Latitude.ToString();
                    destination.Longitude = destination.Longitude ?? leg.EndLocation.Longitude.ToString();

                    var transitStep = leg.Steps.FirstOrDefault(a => a.TransitDetails != null);

                    TimeSpan duration = leg.Duration.Value;
                    TravelTime time = new TravelTime
                     {
                         Mode = mode.ToString(),
                         Days = duration.Days,
                         Hours = duration.Hours,
                         Minutes = duration.Minutes,
                         Seconds = duration.Seconds,
                         TransitDepartureTime = transitStep == null ? null : transitStep.TransitDetails.DepartureTime.Text,
                         TransitDepartureStop = transitStep == null ? null : transitStep.TransitDetails.DepartureStop.Name,
                         TransitArrivalTime = transitStep == null ? null : transitStep.TransitDetails.ArrivalTime.Text,
                         TransitArrivalStop = transitStep == null ? null : transitStep.TransitDetails.ArrivalStop.Name,
                         TransitRoute = transitStep == null ? null : transitStep.TransitDetails.Lines.ShortName,
                         TransitRouteDescription = transitStep == null ? null : transitStep.TransitDetails.Lines.Name
                     };
                    return time;
                }
            }
            return null;
        }
Example #24
0
        private DirectionsResponse GetDirections(string origin, string destination, TravelMode travelMode)
        {
            DirectionsRequest directionsRequest = new AuthorizedDirectionRequest(configuration["GoogleMaps:ApiKey"])
            {
                Origin        = origin,
                Destination   = destination,
                TravelMode    = travelMode,
                DepartureTime = DateTime.Now
            };

            DirectionsResponse directions = GoogleMaps.Directions.QueryAsync(directionsRequest).Result;

            return(directions);
        }
Example #25
0
        public static TravelMode GetMode()
        {
            Console.WriteLine("Select the Mode of Transport from the List below");
            Array allModes = Enum.GetValues(typeof(TravelMode));

            foreach (var mode in allModes)
            {
                Console.WriteLine(mode);
            }
            string     value = Console.ReadLine();
            TravelMode tmode = (TravelMode)Enum.Parse(typeof(TravelMode), value);

            return(tmode);
        }
Example #26
0
        public NavMeshInstance(NavMesh mesh, TravelMode mode, int startNode, bool random, bool reverse, bool allowU, int timeOut)
        {
            m_navMesh = mesh;
            m_currentNode = new Node(startNode);

            m_overrideMode = mode;
            m_startNode = startNode;
            m_random = random;
            m_reverse = reverse;
            m_allowU = allowU;
            timeOut = Math.Max(0, timeOut);

            m_timeOut = timeOut;
        }
Example #27
0
        private async void UpdateRoute(TravelMode selectedTravelMode)
        {
            try
            {
                // Create a list of stops.
                List <Stop> stops = new List <Stop>();

                // Add a stop to the list for each graphic in the stops overlay.
                foreach (Graphic stopGraphic in _stopsOverlay.Graphics)
                {
                    Stop stop = new Stop((MapPoint)stopGraphic.Geometry);
                    stops.Add(stop);
                }

                if (stops.Count < 2)
                {
                    // Don't route, there's no where to go (and the route task would throw an exception).
                    return;
                }

                // Configure the route parameters with the list of stops.
                _offlineRouteParameters.SetStops(stops);

                // Configure the travel mode.
                _offlineRouteParameters.TravelMode = selectedTravelMode;

                // Solve the route.
                RouteResult offlineRouteResult = await _offlineRouteTask.SolveRouteAsync(_offlineRouteParameters);

                // Clear the old route result.
                _routeOverlay.Graphics.Clear();

                // Get the geometry from the route result.
                Polyline routeGeometry = offlineRouteResult.Routes.First().RouteGeometry;

                // Note: symbology left out here because the symbology was set once on the graphics overlay.
                Graphic routeGraphic = new Graphic(routeGeometry);

                // Display the route.
                _routeOverlay.Graphics.Add(routeGraphic);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                ShowMessage("Couldn't update route", "There was an error updating the route. See debug output for details.");
                _selectedStopGraphic = null;
            }
        }
        private void TravelMode_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                // Get the selected travel mode.
                TravelMode selectedTravelMode = _availableTravelModes[_travelModeSpinner.SelectedItemPosition];

                // Update the route.
                UpdateRoute(selectedTravelMode);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                ShowMessage("Couldn't change travel mode", "Couldn't change travel mode. See debug output for details.");
            }
        }
Example #29
0
        public override double GetDistance(TravelMode Mode)
        {
            if (Mode == TravelMode.Car)
            {
                if (!CanBeTraversedUsingMode(Mode))
                {
                    return(double.PositiveInfinity);
                }
                if (!ValidateTraversal(Mode))
                {
                    return(double.PositiveInfinity);
                }
            }

            return(this.Distance);
        }
Example #30
0
 public Router(Node Source, Node Target, string Date, double StartTime, TravelMode Modes, ObjFunction Func, int index = 0, RouterFactors Param = null)
 {
     this.Source    = Source;
     this.Target    = Target;
     this.Date      = Date;
     this.StartTime = StartTime;
     this.ObjFunc   = Func;
     this.Modes     = Modes;
     RPMessage      = new Message {
     };
     RI             = new RouterInfo((int)StartTime, Date, ObjFunc, Param);
     if (RI.routerFactors != null)
     {
         this.RI.routerFactors.Index = index;
     }
 }
Example #31
0
        public Directions GetDirections(Coordinate origin, Coordinate destination, TravelMode travelMode = TravelMode.Driving)
        {
            if (!CoordinateValidator.Validate(origin.Latitude, origin.Longitude))
            {
                throw new ArgumentException("Invalid origin coordinate supplied.");
            }

            if (!CoordinateValidator.Validate(destination.Latitude, destination.Longitude))
            {
                throw new ArgumentException("Invalid destination coordinate supplied.");
            }

            return(GetDirections(XDocument.Load(String.Format(ApiDirections,
                                                              String.Format("{0},{1}", origin.Latitude, origin.Longitude),
                                                              String.Format("{0},{1}", destination.Latitude, destination.Longitude),
                                                              travelMode.ToString().ToLower()))));
        }
Example #32
0
        /* LConnection */
        public override double GetTravelTime(string date, double arrivalTime, TravelMode Mode)
        {
            double time = 0;

            if (Mode.HasFlag(Routing.TravelMode.Bus))
            {
                if (!CanBeTraversedUsingMode(Mode))
                {
                    time = double.PositiveInfinity;
                }
            }
            else
            {
                time = double.PositiveInfinity;
            }

            return(time);
        }
        /*oblicza trasę na podstawie otrzymanych współrzędnych
         * jesli waypointów mniej niż dwa informacja
         * w przeciwnym wypadku zapisz je na mapie
        */
        public void CalculateRoute(Microsoft.Phone.Controls.Maps.Map map, GeocodeService.GeocodeResult[] coordinates, Helper.MapResultReceived croute, TravelMode tm = TravelMode.Driving)
        {
            if (coordinates.Length < 2)
            {
                MessageBox.Show("Too small number od location: you need startPoint and endpoint at least");
                return;
            }
            try
            {
                MapResponseSendHere = new Helper.MapResultReceived(croute);
                routedMap = map;
                RouteService.RouteServiceClient routeService = new RouteService.RouteServiceClient("BasicHttpBinding_IRouteService");
                routeService.Endpoint.Binding.ReceiveTimeout = timeout;
                routeService.Endpoint.Binding.SendTimeout = timeout;
                routeService.Endpoint.Binding.OpenTimeout = timeout;

                RouteRequest routeRequest = new RouteRequest();
                {
                    routeRequest.Credentials = new Microsoft.Phone.Controls.Maps.Credentials() { ApplicationId = bingMapKey };
                    routeRequest.Options = new RouteService.RouteOptions()
                    { RoutePathType = RouteService.RoutePathType.Points, Mode = tm };
                }
                routeRequest.Waypoints = new System.Collections.ObjectModel.ObservableCollection<RouteService.Waypoint>();
                foreach (GeocodeService.GeocodeResult coord in coordinates)
                {
                    if (null != coord)
                    {
                        if (coordinates[coordinates.Length - 1] != coord) //jesli to ostatni punkt ustaw: MOBICA
                            routeRequest.Waypoints.Add(GeocodeToWaypoint(coord));
                        else
                            routeRequest.Waypoints.Add(GeocodeToWaypoint(coord, "MOBICA"));
                    }
                }

                routeService.CalculateRouteCompleted += (sender, e) => CalculateRouteCompleted(sender, e);
                routeService.CalculateRouteAsync(routeRequest, coordinates.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An exception occurred: " + ex.Message);

            }
        }
        private async void SolveRoute()
        {
            try
            {
                // Create route parameters and configure them to enable navigation.
                _routeParameters = await _routeTask.CreateDefaultParametersAsync();

                _routeParameters.ReturnStops      = true;
                _routeParameters.ReturnDirections = true;
                _routeParameters.ReturnRoutes     = true;

                // Prefer walking directions if available.
                TravelMode walkingMode =
                    _routeTask.RouteTaskInfo.TravelModes.FirstOrDefault(mode => mode.Name.Contains("Walk")) ??
                    _routeTask.RouteTaskInfo.TravelModes.First();
                _routeParameters.TravelMode = walkingMode;

                // Set the stops for the route.
                Stop stop1 = new Stop(_startPoint);
                Stop stop2 = new Stop(_endPoint);
                _routeParameters.SetStops(new[] { stop1, stop2 });

                // Calculate the route.
                _routeResult = await _routeTask.SolveRouteAsync(_routeParameters);

                // Get the first result.
                _route = _routeResult.Routes.First();

                // Create and show a graphic for the route.
                Graphic routeGraphic = new Graphic(_route.RouteGeometry);
                _routeOverlay.Graphics.Add(routeGraphic);

                // Allow the user to start navigating.
                EnableNavigation();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Failed to calculate route.", "OK");

                Debug.WriteLine(ex);
            }
        }
Example #35
0
        private async void SolveRoute()
        {
            try
            {
                // Create route parameters and configure them to enable navigation.
                _routeParameters = await _routeTask.CreateDefaultParametersAsync();

                _routeParameters.ReturnStops      = true;
                _routeParameters.ReturnDirections = true;
                _routeParameters.ReturnRoutes     = true;

                // Prefer walking directions if available.
                TravelMode walkingMode =
                    _routeTask.RouteTaskInfo.TravelModes.FirstOrDefault(mode => mode.Name.Contains("Walk")) ??
                    _routeTask.RouteTaskInfo.TravelModes.First();
                _routeParameters.TravelMode = walkingMode;

                // Set the stops for the route.
                Stop stop1 = new Stop(_startPoint);
                Stop stop2 = new Stop(_endPoint);
                _routeParameters.SetStops(new[] { stop1, stop2 });

                // Calculate the route.
                _routeResult = await _routeTask.SolveRouteAsync(_routeParameters);

                // Get the first result.
                _route = _routeResult.Routes.First();

                // Create and show a graphic for the route.
                Graphic routeGraphic = new Graphic(_route.RouteGeometry);
                _routeOverlay.Graphics.Add(routeGraphic);

                // Allow the user to start navigating.
                EnableNavigation();
            }
            catch (Exception ex)
            {
                new Android.Support.V7.App.AlertDialog.Builder(this).SetMessage("Failed to calculate route.")
                .SetTitle("Error").Show();
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        /// <summary>
        /// Query the distance and time for a specified Route.
        /// Returns Null if route not calculated yet
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="origin"></param>
        /// <param name="destination"></param>
        /// <returns>RouteStats with time and distance or Null if route was not calculated</returns>
        public static async Task <RouteStats> GetDistanceAndTime(TravelMode mode, LatLng origin, LatLng destination)
        {
            if (_js is null)
            {
                return(null);
            }

            await _semaphore.WaitAsync();

            var route = new Route(mode, origin, destination);

            if (_distancesAndTime.TryGetValue(route, out var res))
            {
                _semaphore.Release();
                return(res);
            }

            _semaphore.Release();
            return(null);
        }
Example #37
0
        private async void SolveRoute()
        {
            try
            {
                // Create the route parameters and configure to enable navigation.
                _routeParameters = await _routeTask.CreateDefaultParametersAsync();

                _routeParameters.ReturnStops      = true;
                _routeParameters.ReturnDirections = true;
                _routeParameters.ReturnRoutes     = true;

                // Prefer walking directions if available.
                TravelMode walkingMode = _routeTask.RouteTaskInfo.TravelModes.FirstOrDefault(mode => mode.Name.Contains("Walk")) ?? _routeTask.RouteTaskInfo.TravelModes.First();
                _routeParameters.TravelMode = walkingMode;

                // Set the stops.
                Stop stop1 = new Stop(_startPoint);
                Stop stop2 = new Stop(_endPoint);
                _routeParameters.SetStops(new[] { stop1, stop2 });

                // Solve the rotue.
                _routeResult = await _routeTask.SolveRouteAsync(_routeParameters);

                _route = _routeResult.Routes.First();

                // Show the route on the map.
                Graphic routeGraphic = new Graphic(_route.RouteGeometry);
                _routeOverlay.Graphics.Add(routeGraphic);

                // Update the UI and allow the user to start navigating.
                _navigateButton.Enabled = true;
                _helpLabel.Text         = "You're ready to start navigating!";
            }
            catch (Exception ex)
            {
                _helpLabel.Text = "Routing failed, restart sample to retry.";
                new UIAlertView("Error", "Failed to calculate route", (IUIAlertViewDelegate)null, "OK", null).Show();
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
Example #38
0
 public Directions GetDirections(string originAddress, Coordinate destination, TravelMode travelMode = TravelMode.Driving)
 {
     return GetDirections(XDocument.Load(String.Format(ApiDirections, originAddress, String.Format("{0},{1}", destination.Latitude, destination.Longitude), travelMode.ToString().ToLower())));
 }
Example #39
0
 public Directions GetDirections(string originAddress, string destinationAddress, TravelMode travelMode = TravelMode.Driving)
 {
     return GetDirections(XDocument.Load(String.Format(ApiDirections, originAddress, destinationAddress, travelMode.ToString().ToLower())));
 }
        public bool GetNextPosition(Vector3 currentPosition, float closeToRange, int secondsBeforeForcedTeleport,
                                    out Vector3 position, out TravelMode state, out bool needsToTeleportToPosition)
        {
            const bool found = false;

            lock (m_lock)
            {
                findNewTarget:
                position = Vector3.Zero;
                state = TravelMode.None;
                needsToTeleportToPosition = false;

                if ((m_listOfPositions.Count - m_currentpos) > 0)
                {
                    position = m_listOfPositions[m_currentpos];
                    state = m_listOfStates[m_currentpos];
                    if (state != TravelMode.Wait && state != TravelMode.TriggerHereEvent && position.ApproxEquals(currentPosition, closeToRange))
                    {
                        //Its close to a position, go look for the next pos
                        m_currentpos++;
                        m_lastChangedPosition = DateTime.MinValue;
                        goto findNewTarget;
                    }

                    if (state == TravelMode.TriggerHereEvent)
                    {
                        m_currentpos++; //Clear for next time, as we only fire this one time
                        m_lastChangedPosition = DateTime.MinValue;
                    }
                    else if (state == TravelMode.Wait)
                    {
                        if (m_waitingSince == DateTime.MinValue)
                            m_waitingSince = DateTime.Now;
                        else
                        {
                            if ((DateTime.Now - m_waitingSince).Seconds > position.X)
                            {
                                m_waitingSince = DateTime.MinValue;
                                m_currentpos++;
                                m_lastChangedPosition = DateTime.MinValue;
                                goto findNewTarget;
                            }
                        }
                    }
                    else
                    {
                        m_lastChangedPosition = DateTime.Now;
                        if ((DateTime.Now - m_lastChangedPosition).Seconds > secondsBeforeForcedTeleport)
                            needsToTeleportToPosition = true;
                    }

                    return true;
                }

                if (m_listOfPositions.Count == 0)          
                    return false;

                if (FollowIndefinitely)
                {
                    m_currentpos = 0; //Reset the position to the beginning if we have run out of positions
                    goto findNewTarget;
                }
            }

            return found;
        }
Example #41
0
        public bool GetNextPosition(ScenePresence scenePresence, float closeToRange, TimeSpan diffFromLastFrame, float secondsBeforeForcedTeleport,
                                    out Vector3 position, out TravelMode state, out bool needsToTeleportToPosition, out bool changingNodes)
        {
            changingNodes = false;
            lock (m_lock)
            {
                while(true)
                {
                    //Initialize default values
                    position = Vector3.Zero;
                    state = TravelMode.None;
                    needsToTeleportToPosition = false;

                    //See if we have a valid position to attempt to move to
                    if(CurrentPos < m_listOfPositions.Count)
                    {
                        //Get the position/state and make sure that it is within the region
                        position = m_listOfPositions[CurrentPos];
                        Util.ForceValidRegionXYZ(ref position);
                        state = m_listOfStates[CurrentPos];

                        if (state == TravelMode.Wait)
                        {
                            if (!m_waitingSince.HasValue)//Has no value, so we're just starting to wait
                                m_waitingSince = DateTime.Now;
                            else
                            {
                                double ms = (DateTime.Now - m_waitingSince.Value).TotalMilliseconds;
                                if (ms > (position.X * 1000f))
                                {
                                    //We're done waiting, increment the position counter and go around the loop again
                                    m_waitingSince = null;
                                    CurrentPos++;
                                    changingNodes = true;
                                    m_timeSinceLastChangedPosition = TimeSpan.FromMilliseconds(0);
                                    continue;
                                }
                            }
                            return true;
                        }
                        else
                        {
                            //We are attempting to move somewhere
                            if (scenePresence.IsAtTarget(position, closeToRange))
                            {
                                //We made it to the position, begin proceeding towards the next position 
                                CurrentPos++;
                                changingNodes = true;
                                m_timeSinceLastChangedPosition = TimeSpan.FromMilliseconds(0);
                                continue;
                            }
                            else 
                            {
                                m_timeSinceLastChangedPosition = m_timeSinceLastChangedPosition.Add(diffFromLastFrame);
                                //We need to see if we should teleport to the next node rather than waiting for us to get there
                                if (m_timeSinceLastChangedPosition.TotalMilliseconds > (secondsBeforeForcedTeleport * 1000))
                                {
                                    changingNodes = true;
                                    m_timeSinceLastChangedPosition = TimeSpan.FromMilliseconds(0);
                                    needsToTeleportToPosition = true;
                                }
                            }
                            return true;
                        }
                    }
                    else
                    {
                        //We've finished all the states in the position list
                        m_timeSinceLastChangedPosition = TimeSpan.FromMilliseconds(0);

                        if (m_listOfPositions.Count == 0)//Sanity check
                            return false;

                        if (FollowIndefinitely)
                        {
                            //If we're following indefinitely, then the counter is reset to the beginning and we go around again
                            CurrentPos = 0;
                            changingNodes = true;
                            continue;
                        }
                        return false;
                    }
                }
            }
        }
Example #42
0
 public void GetDirections(string origin, string destination, TravelMode mode, RouteMethod method, Units unit, Action<IRestResponse<RoutesResponse>> callback)
 {
     var result = new RestResponse<RoutesResponse>
     {
         StatusCode = HttpStatusCode.OK,
         Data = JsonConvert.DeserializeObject<RoutesResponse>(RoutesResponse)
     };
     callback(result);
 }
Example #43
0
 public Node(int index)
 { 
     Index = index;
     Mode = TravelMode.None;
     Position = Vector3.Zero;
 }
Example #44
0
 public void AddEdge(int e1, int e2, TravelMode mode)
 {
     Edge edge = new Edge();
     edge.Start = e1;
     edge.End = e2;
     edge.Mode = mode;
     m_edges.Add(edge);
 }
Example #45
0
        public Directions GetDirections(Coordinate origin, Coordinate destination, TravelMode travelMode = TravelMode.Driving)
        {
            if (!CoordinateValidator.Validate(origin.Latitude, origin.Longitude))
                throw new ArgumentException("Invalid origin coordinate supplied.");

            if (!CoordinateValidator.Validate(destination.Latitude, destination.Longitude))
                throw new ArgumentException("Invalid destination coordinate supplied.");

            return GetDirections(XDocument.Load(String.Format(ApiDirections,
                        String.Format("{0},{1}", origin.Latitude, origin.Longitude),
                        String.Format("{0},{1}", destination.Latitude, destination.Longitude),
                        travelMode.ToString().ToLower())));
        }