コード例 #1
0
        public async void OnMapReady(GoogleMap map)
        {
            // Register events
            googleMap = map;
            googleMap.CameraChange          += GoogleMap_CameraChange;
            googleMap.MyLocationButtonClick += GoogleMap_MyLocationButtonClick;
            googleMap.MarkerClick           += GoogleMap_MarkerClick;
            googleMap.InfoWindowClick       += GoogleMap_InfoWindowClick;

            // Enable my location if user has granted location permission
            if (ContextCompat.CheckSelfPermission(Activity, Manifest.Permission.AccessFineLocation) == Permission.Granted)
            {
                googleMap.MyLocationEnabled = true;
            }

            await Task.Run(() =>
            {
                Dictionary <string, MarkerOptions> multiStopGrayMarkerOptions = new Dictionary <string, MarkerOptions>();
                Dictionary <Stop, MarkerOptions> multiStopDetailMarkerOptions = new Dictionary <Stop, MarkerOptions>();
                Dictionary <Stop, MarkerOptions> singleStopMarkerOptions      = new Dictionary <Stop, MarkerOptions>();

                Bitmap multiStopIcon = Utils.GetStopIconForColor(Activity, Color.Gray, TramUrWayApplication.MapStopIconSize);
                BitmapDescriptor multiStopIconDescriptor = BitmapDescriptorFactory.FromBitmap(multiStopIcon);

                // Create multistop markers
                foreach (var pair in stops.Where(p => p.Value.Length > 1))
                {
                    MarkerOptions markerOptions = CreateStopMarker(multiStopIconDescriptor, pair.Value);
                    multiStopGrayMarkerOptions.Add(pair.Key, markerOptions);

                    foreach (Stop stop in pair.Value)
                    {
                        Bitmap stopIcon = Utils.GetStopIconForLine(Activity, stop.Line, TramUrWayApplication.MapStopIconSize);
                        BitmapDescriptor stopIconDescriptor = BitmapDescriptorFactory.FromBitmap(stopIcon);

                        markerOptions = CreateStopMarker(stopIconDescriptor, stop).Visible(false);
                        multiStopDetailMarkerOptions.Add(stop, markerOptions);
                    }
                }

                // Create single stop markers
                foreach (var pair in stops.Where(p => p.Value.Length == 1))
                {
                    Stop stop = pair.Value[0];

                    Bitmap stopIcon = Utils.GetStopIconForLine(Activity, stop.Line, TramUrWayApplication.MapStopIconSize);
                    BitmapDescriptor stopIconDescriptor = BitmapDescriptorFactory.FromBitmap(stopIcon);

                    MarkerOptions markerOptions = CreateStopMarker(stopIconDescriptor, stop).Visible(stop.Line.Type == LineType.Tram);
                    singleStopMarkerOptions.Add(stop, markerOptions);
                }

                // Add all markers to the map
                Activity.RunOnUiThread(() =>
                {
                    foreach (var pair in multiStopGrayMarkerOptions)
                    {
                        multiStopGrayMarkers.Add(pair.Key, googleMap.AddMarker(pair.Value));
                    }

                    foreach (var pair in multiStopDetailMarkerOptions)
                    {
                        Marker marker = googleMap.AddMarker(pair.Value);
                        multiStopDetailMarkers.Add(pair.Key, marker);
                        markerStops.Add(marker.Id, pair.Key);
                    }

                    foreach (var pair in singleStopMarkerOptions)
                    {
                        Marker marker = googleMap.AddMarker(pair.Value);
                        singleStopMarkers.Add(pair.Key, marker);
                        markerStops.Add(marker.Id, pair.Key);
                    }
                });
            });
        }
コード例 #2
0
ファイル: Assets.cs プロジェクト: jbatonnet/TramUrWay
        private void LoadLine(Line line)
        {
            JObject lineObject = lineData[line];

            List <Stop> lineStops = new List <Stop>();

            foreach (JObject stopObject in lineObject["Stops"] as JArray)
            {
                Stop stop = new Stop()
                {
                    Id       = stopObject["Id"].Value <int>(),
                    Name     = stopObject["Name"].Value <string>(),
                    Position = new Position(stopObject["Position"][0].Value <float>(), stopObject["Position"][1].Value <float>()),
                    Line     = line
                };

                lineStops.Add(stop);
            }

            line.Stops = lineStops.ToArray();

            List <Route> lineRoutes = new List <Route>();

            foreach (JObject routeObject in lineObject["Routes"] as JArray)
            {
                Route route = new Route()
                {
                    Id   = routeObject["Id"].Value <int>(),
                    Name = routeObject["Name"].Value <string>(),
                    Line = line
                };

                List <Step> routeSteps = new List <Step>();

                foreach (JObject stepObject in routeObject["Steps"] as JArray)
                {
                    int stopId = stepObject["Stop"].Value <int>();

                    Step step = new Step()
                    {
                        Stop      = line.Stops.First(s => s.Id == stopId),
                        Partial   = stepObject["Partial"].Value <bool>(),
                        Duration  = ParseTimeSpan(stepObject["Duration"].Value <string>()),
                        Direction = stepObject["Direction"].Value <string>(),
                        Speed     = ParseCurve(stepObject["Speed"].Value <string>()),
                        Route     = route
                    };

                    JArray trajectoryArray = stepObject["Trajectory"] as JArray;
                    if (trajectoryArray != null)
                    {
                        List <TrajectoryStep> stepTrajectory = new List <TrajectoryStep>();

                        foreach (JToken positionObject in stepObject["Trajectory"] as JArray)
                        {
                            stepTrajectory.Add(new TrajectoryStep()
                            {
                                Index = positionObject[0].Value <float>(), Position = new Position(positionObject[1][0].Value <float>(), positionObject[1][1].Value <float>())
                            });
                        }

                        step.Trajectory = stepTrajectory.ToArray();
                    }

                    routeSteps.Add(step);
                }

                route.Steps = routeSteps.ToArray();

                JObject timeTableObject = routeObject["TimeTable"] as JObject;
                if (timeTableObject != null)
                {
                    string[]  tableNames = new[] { "Week", "Friday", "Saturday", "Sunday", "Holiday" };
                    TimeTable timeTable  = new TimeTable()
                    {
                        Route = route
                    };

                    foreach (string tableName in tableNames)
                    {
                        JArray tableArray = timeTableObject[tableName] as JArray;
                        if (tableArray == null)
                        {
                            continue;
                        }

                        List <TimeSpan?[]> tableValues = new List <TimeSpan?[]>();
                        foreach (JArray tableLineArray in tableArray.Cast <JArray>())
                        {
                            tableValues.Add(tableLineArray.Select(j => ParseTimeSpan(j.Value <string>())).ToArray());
                        }

                        TimeSpan?[,] table = new TimeSpan?[tableValues.Count, route.Steps.Length];
                        for (int i = 0; i < tableValues.Count; i++)
                        {
                            for (int j = 0; j < route.Steps.Length; j++)
                            {
                                table[i, j] = tableValues[i][j];
                            }
                        }

                        switch (tableName)
                        {
                        case "Week": timeTable.WeekTable = table; break;

                        case "Friday": timeTable.FridayTable = table; break;

                        case "Saturday": timeTable.SaturdayTable = table; break;

                        case "Sunday": timeTable.SundayTable = table; break;

                        case "Holidays": timeTable.HolidaysTable = table; break;
                        }
                    }

                    route.TimeTable = timeTable;
                }

                // Post process each step to build the linked list
                for (int i = 0; i < route.Steps.Length; i++)
                {
                    route.Steps[i].Previous = i > 0 ? route.Steps[i - 1] : null;
                    route.Steps[i].Next     = i < route.Steps.Length - 1 ? route.Steps[i + 1] : null;
                }

                lineRoutes.Add(route);
            }

            line.Routes = lineRoutes.ToArray();
        }
コード例 #3
0
ファイル: StopActivity.cs プロジェクト: jbatonnet/TramUrWay
        protected override void OnCreate(Bundle savedInstanceState)
        {
            OnCreate(savedInstanceState, Resource.Layout.StopActivity);

            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            // Handle bundle parameter
            Bundle extras = Intent.Extras;

            if (extras != null && extras.ContainsKey("Stop"))
            {
                int stopId = extras.GetInt("Stop");
                stop = TramUrWayApplication.GetStop(stopId);
            }
#if DEBUG
            else
            {
                stop = TramUrWayApplication.Lines.SelectMany(l => l.Stops).FirstOrDefault(s => s.Name == "Saint-Lazare");
            }
#endif
            if (stop == null)
            {
                throw new Exception("Could not find any stop matching the specified id");
            }

            if (extras != null && extras.ContainsKey("Line"))
            {
                int lineId = extras.GetInt("Line");
                line = TramUrWayApplication.GetLine(lineId);
            }
            else
            {
                line = stop.Line;
            }

            Title = stop.Name;

            // Change toolbar color
            Color color     = Utils.GetColorForLine(this, line);
            Color darkColor = new Color(color.R * 2 / 3, color.G * 2 / 3, color.B * 2 / 3);

            SupportActionBar.SetBackgroundDrawable(new ColorDrawable(color));

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
                Window.SetStatusBarColor(darkColor);
            }

            // Refresh widget
            swipeRefresh          = FindViewById <SwipeRefreshLayout>(Resource.Id.StopActivity_SwipeRefresh);
            swipeRefresh.Refresh += SwipeRefresh_Refresh;
            swipeRefresh.SetColorSchemeColors(color.ToArgb());

            // Initialize UI
            lineLabel      = FindViewById <TextView>(Resource.Id.StopActivity_LineLabel);
            lineLabel.Text = line.Name;
            lineLabel.SetTextColor(darkColor);

            listStopList = FindViewById <RecyclerView>(Resource.Id.StopActivity_LineStopList);
            listStopList.HasFixedSize           = true;
            listStopList.NestedScrollingEnabled = false;
            listStopList.SetLayoutManager(new WrapLayoutManager(this));
            listStopList.AddItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.Vertical));

            otherLabel = FindViewById <TextView>(Resource.Id.StopActivity_OtherLabel);
            otherLabel.SetTextColor(darkColor);

            otherStopList = FindViewById <RecyclerView>(Resource.Id.StopActivity_OtherStopList);
            otherStopList.HasFixedSize           = true;
            otherStopList.NestedScrollingEnabled = false;
            otherStopList.SetLayoutManager(new WrapLayoutManager(this));
            otherStopList.AddItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.Vertical));
        }
コード例 #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.RoutesActivity);
            NavigationItemId = Resource.Id.SideMenu_Routes;

            OnPostCreate();

            Stop[]   stops     = TramUrWayApplication.Lines.SelectMany(l => l.Stops).ToArray();
            string[] stopNames = stops.Select(s => s.Name).Distinct().ToArray();

            // Initialize UI
            fromLayout   = FindViewById <TextInputLayout>(Resource.Id.RoutesActivity_FromLayout);
            fromTextView = FindViewById <AutoCompleteTextView>(Resource.Id.RoutesActivity_From);
            //fromTextView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.RouteAutocompleteItem, stopNames);
            fromTextView.Adapter      = new StopNameAdapter(this);
            fromTextView.TextChanged += TextView_TextChanged;

            View fromButton = FindViewById(Resource.Id.RoutesActivity_FromButton);

            fromButton.Click += FromButton_Click;

            toLayout   = FindViewById <TextInputLayout>(Resource.Id.RoutesActivity_ToLayout);
            toTextView = FindViewById <AutoCompleteTextView>(Resource.Id.RoutesActivity_To);
            //toTextView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.RouteAutocompleteItem, stopNames);
            toTextView.Adapter      = new StopNameAdapter(this);
            toTextView.TextChanged += TextView_TextChanged;

            View toButton = FindViewById(Resource.Id.RoutesActivity_ToButton);

            toButton.Click += ToButton_Click;

            View dateLayout = FindViewById(Resource.Id.RoutesActivity_DateLayout);

            dateLayout.Click += DateLayout_Click;

            // Handle bundle parameter
            Bundle extras = Intent.Extras;

            if (extras != null && extras.ContainsKey("From"))
            {
                int  stopId = extras.GetInt("From");
                Stop stop   = TramUrWayApplication.GetStop(stopId);
                if (stop != null)
                {
                    fromTextView.Text = stop.Name;
                }
            }

            if (extras != null && extras.ContainsKey("To"))
            {
                int  stopId = extras.GetInt("To");
                Stop stop   = TramUrWayApplication.GetStop(stopId);
                if (stop != null)
                {
                    toTextView.Text = stop.Name;
                }
            }
#if DEBUG
            //else
            //    toTextView.Text = "Odysseum";
#endif

            recyclerView = FindViewById <RecyclerView>(Resource.Id.RoutesActivity_RoutesList);
            recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));
            recyclerView.AddItemDecoration(new DividerItemDecoration(recyclerView.Context, LinearLayoutManager.Vertical));
            recyclerView.SetAdapter(routeSegmentAdapter = new RouteSegmentsAdapter());

            // Refresh widget
            swipeRefresh          = FindViewById <SwipeRefreshLayout>(Resource.Id.RoutesActivity_SwipeRefresh);
            swipeRefresh.Refresh += SwipeRefresh_Refresh;
            swipeRefresh.SetColorSchemeColors(Resources.GetColor(Resource.Color.colorAccent).ToArgb());

            noResultsView            = FindViewById(Resource.Id.RoutesActivity_NoResults);
            noResultsView.Visibility = ViewStates.Gone;
        }
コード例 #5
0
        private async Task Search(Stop from, Stop to, DateConstraint constraint, DateTime date)
        {
            swipeRefresh?.Post(() => swipeRefresh.Refreshing = true);

            await Task.Run(() =>
            {
                routeSegments.Clear();

                // Build a new route searcher
                RouteSearch routeSearch             = new RouteSearch();
                routeSearch.Settings.AllowWalkLinks = false;
                routeSearch.Prepare(TramUrWayApplication.Lines);

                // Start enumeration
                DateTime end = DateTime.Now + TimeSpan.FromSeconds(5);

                IEnumerable <RouteLink[]> routesEnumerable = routeSearch.FindRoutes(from, to);
                IEnumerator <RouteLink[]> routesEnumerator = routesEnumerable.GetEnumerator();

                while (true)
                {
                    Task <bool> moveNextTask = Task.Run(() => routesEnumerator.MoveNext());

                    // Exit if timed out
                    TimeSpan timeout = end - DateTime.Now;
                    if (!moveNextTask.Wait(timeout))
                    {
                        break;
                    }

                    // Exit if enumeration finished
                    if (moveNextTask.Result == false)
                    {
                        break;
                    }

                    RouteLink[] route  = routesEnumerator.Current;
                    TimeSpan tolerance = TimeSpan.FromMinutes(15);

                    // We found a route, try to find times
                    if (constraint == DateConstraint.Now)
                    {
                        routeSegments.AddRange(routeSearch.SimulateTimeStepsFrom(route, date, TimeSpan.Zero, tolerance));
                    }
                    else if (constraint == DateConstraint.From)
                    {
                        routeSegments.AddRange(routeSearch.SimulateTimeStepsFrom(route, date, tolerance, tolerance));
                    }
                    else if (constraint == DateConstraint.To)
                    {
                        throw new NotImplementedException();
                    }
                    else if (constraint == DateConstraint.Last)
                    {
                        throw new NotImplementedException();
                    }

                    // Filter out too long times
                    TimeSpan maxTime = TimeSpan.FromMinutes(0.05 * (to.Position - from.Position));

                    routeSegments.RemoveAll(r => r.Last().DateTo - r.First().DateFrom > maxTime);
                    routeSegments.Sort((r1, r2) => (int)(ComputeRouteWeight(constraint, date, r1) - ComputeRouteWeight(constraint, date, r2)));

                    // Group routes by from and to time steps
                    RouteSegment[][] routeSegmentsCopy = routeSegments.GroupBy(r => GetRouteHash(r)).Select(g => g.First()).ToArray();
                    RunOnUiThread(() => routeSegmentAdapter.RouteSegments = routeSegmentsCopy);
                }

                RunOnUiThread(() =>
                {
                    noResultsView.Visibility = routeSegments.Count == 0 ? ViewStates.Visible : ViewStates.Gone;
                    recyclerView.Visibility  = routeSegments.Count > 0 ? ViewStates.Visible : ViewStates.Gone;

                    swipeRefresh?.PostDelayed(() => swipeRefresh.Refreshing = false, 200);
                });
            });
        }
コード例 #6
0
        private void TriggerSearch()
        {
            snackbar?.Dismiss();

            if (string.IsNullOrWhiteSpace(fromTextView.Text))
            {
                fromLayout.Error = "Spécifiez une station de départ";
                swipeRefresh?.Post(() => swipeRefresh.Refreshing = false);
                return;
            }

            Stop from = TramUrWayApplication.Lines.SelectMany(l => l.Stops).FirstOrDefault(s => s.Name == fromTextView.Text);

            if (from == null)
            {
                fromLayout.Error = "La station spécifiée n'existe pas";
                swipeRefresh?.Post(() => swipeRefresh.Refreshing = false);
                return;
            }

            if (string.IsNullOrWhiteSpace(toTextView.Text))
            {
                toLayout.Error = "Spécifiez une station de destination";
                swipeRefresh?.Post(() => swipeRefresh.Refreshing = false);
                return;
            }

            Stop to = TramUrWayApplication.Lines.SelectMany(l => l.Stops).FirstOrDefault(s => s.Name == toTextView.Text);

            if (to == null)
            {
                toLayout.Error = "La station spécifiée n'existe pas";
                swipeRefresh?.Post(() => swipeRefresh.Refreshing = false);
                return;
            }

            if (from == to)
            {
                toLayout.Error = "Spécifiez une station différente de celle de départ";
                swipeRefresh?.Post(() => swipeRefresh.Refreshing = false);
                return;
            }

            defaultFocus.RequestFocus();
            fromTextView.PostDelayed(() =>
            {
                InputMethodManager inputMethodManager = GetSystemService(Context.InputMethodService) as InputMethodManager;
                inputMethodManager.HideSoftInputFromWindow(fromTextView.WindowToken, HideSoftInputFlags.None);
            }, 250);

            routeSegments.Clear();
            routeSegmentAdapter.RouteSegments = Enumerable.Empty <RouteSegment[]>();

            View initialHintView = FindViewById(Resource.Id.RoutesActivity_InitialHint);

            initialHintView.Visibility = ViewStates.Gone;

#if DEBUG
            //Search(from, to, DateConstraint.From, new DateTime(2016, 05, 27, 16, 24, 00));
            Search(from, to, DateConstraint.Now, DateTime.Now);
#else
            Search(from, to, DateConstraint.Now, DateTime.Now);
#endif
        }
コード例 #7
0
ファイル: Config.cs プロジェクト: jbatonnet/TramUrWay
 public static bool GetIsFavorite(this Stop me)
 {
     return(TramUrWayApplication.Config.FavoriteStops.Any(s => s.Name == me.Name && s.Line.Id == me.Line.Id));
 }