示例#1
0
        private async void UserMain_Loaded(object sender, RoutedEventArgs e)
        {
            UserMap.MapServiceToken = "AKs4qGlBeOVCM1QL6YsY~dFLxTRCFZAK9cyU6nYjDow~AlfE7e6w-DJpHo-8d-_3-LKJW_sQlhBNMQh37nzvhlcenKKqnZiXCR48G87zL4Cn";
            UserMap.ZoomLevel       = 15;
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                Geolocator geolocator = new Geolocator {
                    DesiredAccuracyInMeters = 1, ReportInterval = 10000
                };
                try
                {
                    Geoposition map_pos = await geolocator.GetGeopositionAsync();

                    UserLocIcon.NormalizedAnchorPoint = new Point(0.5, 1);
                    UserLocIcon.Title = "Your Location";
                    Package   packageUsr   = Package.Current;
                    PackageId packageIdUsr = packageUsr.Id;
                    String    outputUsr    = packageIdUsr.Name;
                    string    strUsr       = string.Format("ms-appx://{0}/Assets/user.png", outputUsr);
                    UserLocIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(strUsr));

                    Package   packageDrv   = Package.Current;
                    PackageId packageIdDrv = packageDrv.Id;
                    String    outputDrv    = packageIdDrv.Name;
                    string    strDrv       = string.Format("ms-appx://{0}/Assets/bus.png", outputDrv);
                    for (int i = 0; i < 25; i++)
                    {
                        DriverIcon[i] = new MapIcon();
                        DriverIcon[i].NormalizedAnchorPoint = new Point(0.5, 1);
                        DriverIcon[i].Image  = RandomAccessStreamReference.CreateFromUri(new Uri(strDrv));
                        DriverIcon[i].ZIndex = i;
                    }
                    GetDriverPos();
                    BasicGeoposition PointLoc = new BasicGeoposition()
                    {
                        Latitude  = map_pos.Coordinate.Latitude,
                        Longitude = map_pos.Coordinate.Longitude
                    };
                    UserLocIcon.Location = new Geopoint(PointLoc);
                    UserMap.MapElements.Add(UserLocIcon);
                    UserMap.Center = new Geopoint(PointLoc);
                    UpdateLocationData(map_pos);
                }
                catch (Exception E)
                {
                    var Err3Msg = new MessageDialog(E.Message.ToString(), "Error");
                    await Err3Msg.ShowAsync();
                }

                // if the user position stored in the variable "geolocator" changes, then change in the map also
                geolocator.PositionChanged += geolocator_PostionChanged;
                break;

            case GeolocationAccessStatus.Denied:
                var ErrMsg = new MessageDialog("Please Provide Access to your locaion.", "Error");
                await ErrMsg.ShowAsync();

                break;

            case GeolocationAccessStatus.Unspecified:
                var Err2Msg = new MessageDialog("Please Provide Access to your locaion.", "Error");
                await Err2Msg.ShowAsync();

                break;
            }
        }
        private async void GPS_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button button = sender as Button;
                button.IsEnabled     = false;
                LoadingRing.IsActive = true;

                // Cancel other tasks
                cts.Cancel();
                cts = new CancellationTokenSource();
                var ctsToken = cts.Token;

                ctsToken.ThrowIfCancellationRequested();

                var geoStatus = GeolocationAccessStatus.Unspecified;

                try
                {
                    // Catch error in case dialog is dismissed
                    geoStatus = await Geolocator.RequestAccessAsync();
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error requesting location permission");
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }

                ctsToken.ThrowIfCancellationRequested();

                Geolocator geolocal = new Geolocator()
                {
                    DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600
                };
                Geoposition geoPos = null;

                // Setup error just in case
                MessageDialog error = null;

                switch (geoStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    try
                    {
                        geoPos = await geolocal.GetGeopositionAsync();
                    }
                    catch (Exception ex)
                    {
                        if (Windows.Web.WebError.GetStatus(ex.HResult) > Windows.Web.WebErrorStatus.Unknown)
                        {
                            error = new MessageDialog(App.ResLoader.GetString("WError_NetworkError"), App.ResLoader.GetString("Label_Error"));
                        }
                        else
                        {
                            error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                        }
                        await error.ShowAsync();

                        Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error getting geolocation");
                    }
                    break;

                case GeolocationAccessStatus.Denied:
                    error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied"));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) =>
                    {
                        await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                    }, 0));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1));
                    error.DefaultCommandIndex = 0;
                    error.CancelCommandIndex  = 1;
                    await error.ShowAsync();

                    break;

                case GeolocationAccessStatus.Unspecified:
                default:
                    error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                    await error.ShowAsync();

                    break;
                }

                // Access to location granted
                if (geoPos != null)
                {
                    LocationQueryViewModel view = null;

                    ctsToken.ThrowIfCancellationRequested();

                    button.IsEnabled = false;

                    await Task.Run(async() =>
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        view = await wm.GetLocation(geoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    // Weather Data
                    var location = new LocationData(view, geoPos);
                    if (!location.IsValid())
                    {
                        await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short);

                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    Weather weather = await Settings.GetWeatherData(location.query);

                    if (weather == null)
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        try
                        {
                            weather = await wm.GetWeather(location);
                        }
                        catch (WeatherException wEx)
                        {
                            weather = null;
                            await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                        }
                    }

                    if (weather == null)
                    {
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    // We got our data so disable controls just in case
                    EnableControls(false);

                    // Save weather data
                    Settings.SaveLastGPSLocData(location);
                    await Settings.DeleteLocations();

                    await Settings.AddLocation(new LocationData(view));

                    if (wm.SupportsAlerts && weather.weather_alerts != null)
                    {
                        await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
                    }
                    await Settings.SaveWeatherData(weather);

                    Settings.FollowGPS     = true;
                    Settings.WeatherLoaded = true;

                    this.Frame.Navigate(typeof(Shell), location);
                }
                else
                {
                    EnableControls(true);
                }
            }
            catch (OperationCanceledException)
            {
                // Restore controls
                EnableControls(true);
                Settings.FollowGPS     = false;
                Settings.WeatherLoaded = false;
            }
        }
示例#3
0
        public static async void SetLiveTileBackgroundTask(bool Val)
        {
            try
            {
                var req = await BackgroundExecutionManager.RequestAccessAsync();

                if (req == BackgroundAccessStatus.AlwaysAllowed || req == BackgroundAccessStatus.AllowedSubjectToSystemPolicy ||
                    req == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || req == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
                {
                    var list = BackgroundTaskRegistration.AllTasks.Where(x => x.Value.Name == "WinGoMapsTile");
                    foreach (var item in list)
                    {
                        item.Value.Unregister(false);
                    }
                    if (Val)
                    {
                        BackgroundTaskBuilder build = new BackgroundTaskBuilder();
                        build.IsNetworkRequested = true;
                        build.Name           = "WinGoMapsTile";
                        build.TaskEntryPoint = "LiveTileTask.Update";
                        build.SetTrigger(new TimeTrigger(15, false));
                        var b = build.Register();
                        if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed)
                        {
                            var geolocator = new Geolocator();
                            var Location   = await geolocator.GetGeopositionAsync();

                            var ul   = Location.Coordinate.Point.Position;
                            var http = AppCore.HttpClient;
                            http.DefaultRequestHeaders.UserAgent.ParseAdd("MahStudioWinGoMaps");
                            var res      = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=200x200", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var reswide  = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=310x150", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var resLarge = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=310x310", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var f        = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTile.png", CreationCollisionOption.OpenIfExists);

                            var fWide = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTileWide.png", CreationCollisionOption.OpenIfExists);

                            var fLarge = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTileLarge.png", CreationCollisionOption.OpenIfExists);

                            var str = await f.OpenAsync(FileAccessMode.ReadWrite);

                            var strwide = await fWide.OpenAsync(FileAccessMode.ReadWrite);

                            var strLarge = await fLarge.OpenAsync(FileAccessMode.ReadWrite);

                            await str.WriteAsync(res);

                            await strwide.WriteAsync(reswide);

                            await strLarge.WriteAsync(resLarge);

                            str.Dispose();
                            strwide.Dispose();
                            strLarge.Dispose();

                            var    update = TileUpdateManager.CreateTileUpdaterForApplication();
                            string xml    = "<tile>\n";
                            xml += "<visual version=\"4\">\n";
                            xml += "  <binding template=\"TileSquare150x150Image\" fallback=\"TileSquareImage\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTile.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "  <binding template=\"TileWide310x150Image\" fallback=\"TileWideImage\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTileWide.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "  <binding template=\"TileSquare310x310Image\" fallback=\"TileSquareImageLarge\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTileLarge.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "</visual>\n";
                            xml += "</tile>";

                            XmlDocument txml = new XmlDocument();
                            txml.LoadXml(xml);
                            TileNotification tNotification = new TileNotification(txml);

                            update.Clear();
                            update.Update(tNotification);
                            //XmlDocument tileXmlwide = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);
                            //new Windows.UI.Popups.MessageDialog(tileXmlwide.GetXml()).ShowAsync();
                            //XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Image);
                            //tileXml.GetElementsByTagName("image")[0].Attributes[1].NodeValue = "ms-appdata:///local/LiveTile.png";
                            //tileXmlwide.GetElementsByTagName("image")[0].Attributes[1].NodeValue = "ms-appdata:///local/LiveTileWide.png";
                            //update.Update(new TileNotification(xml));
                        }
                    }
                }
            }
            catch { }
        }
示例#4
0
        protected override async Task InitializeAsyncCore()
        {
            await Geolocator.RequestAccessAsync();

            IsAvailable = true;
        }
示例#5
0
        public MapViewVM()
        {
            LocationFlagVisibility       = Visibility.Visible;
            StepsTitleProviderVisibility = Visibility.Collapsed;
            if (UserLocation == null)
            {
                UserLocation = new ViewModel()
                {
                    AttractionName = "My Location"
                }
            }
            ;
            StaticVM = this;
            LoadPage();
        }

        async void LocateUser()
        {
            try
            {
                var accessStatus = await Geolocator.RequestAccessAsync();

                if (accessStatus == GeolocationAccessStatus.Allowed)
                {
                    Map = MapView.MapControl;
                    if (FastLoadGeoPosition != null)
                    {
                        if (geolocator == null)
                        {
                            geolocator = new Geolocator()
                            {
                                MovementThreshold       = 1,
                                ReportInterval          = 1,
                                DesiredAccuracyInMeters = 1
                            };
                            GeoLocate = geolocator;
                        }
                        else
                        {
                            UserLocation.Location = FastLoadGeoPosition;
                            Map.Center            = FastLoadGeoPosition;
                            await AppCore.Dispatcher.RunAsync(CoreDispatcherPriority.High, async delegate
                            {
                                await Map.TryZoomToAsync(16);
                            });
                        }
                        // Subscribe to the StatusChanged event to get updates of location status changes.
                        //geolocator.StatusChanged += Geolocator_StatusChanged;
                        // Carry out the operation.
                        GeoLocatorHelper.GetUserLocation();
                        GeoLocatorHelper.LocationFetched += GeoLocatorHelper_LocationFetched;
                        geolocator.PositionChanged       += Geolocator_PositionChanged;
                        await AppCore.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate
                        {
                            var savedplaces = SavedPlacesVM.GetSavedPlaces();
                            foreach (var item in savedplaces)
                            {
                                Map.MapElements.Add(new MapIcon()
                                {
                                    Location = new Geopoint(new BasicGeoposition()
                                    {
                                        Latitude = item.Latitude, Longitude = item.Longitude
                                    }),
                                    Title = item.PlaceName
                                });
                            }
                        });

                        await Task.Delay(150);

                        LocationFlagVisibility = Visibility.Visible;
                        //if (Map.Is3DSupported)
                        //{
                        //    Map.Style = MapStyle.Aerial3DWithRoads;
                        //    MapScene mapScene = MapScene.CreateFromLocationAndRadius(snPoint, 500, 150, 70);
                        //    await Map.TrySetSceneAsync(mapScene);
                        //}
                        //var r = await MapLocationFinder.FindLocationsAtAsync(snPoint);
                        //if(r.Locations != null)
                        //{
                        //    var re = r.Locations.FirstOrDefault();
                        //    var rg = RegionInfo.CurrentRegion;
                        //    var rg2 = new RegionInfo(re.Address.Country);
                        //}
                    }
                    else
                    {
                        LocationFlagVisibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    LocationFlagVisibility = Visibility.Collapsed;
                    var msg = new MessageDialog(MultilingualHelpToolkit.GetString("StringLocationPrivacy", "Text"));
                    msg.Commands.Add(new UICommand(MultilingualHelpToolkit.GetString("StringOK", "Text"), async delegate
                    {
                        await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location", UriKind.RelativeOrAbsolute));
                    }));
                    msg.Commands.Add(new UICommand(MultilingualHelpToolkit.GetString("StringCancel", "Text"), delegate { }));
                    await msg.ShowAsync();

                    Window.Current.Activated += Current_Activated;
                }
            }
            catch { }
            //try
            //{
            //    ApplicationData.Current.LocalSettings.Values["WCReponse"].ToString();
            //}
            //catch
            //{
            //    var message = new MessageDialog("windowscentral is not a Microsoft News website that you are looking for. See our reply to WindowsCentral post about WinGo Maps.");
            //    message.Commands.Add(new UICommand("See our response on twitter.", async delegate
            //    {
            //        await Launcher.LaunchUriAsync(new Uri("https://twitter.com/NGameAli/status/1028157663752978432"));
            //    }));
            //    await message.ShowAsync();
            //    ApplicationData.Current.LocalSettings.Values["WCReponse"] = "windowscentral is not a Microsoft News website that you are looking for";
            //}
        }
示例#6
0
        private static void Main(string[] args)
        {
            //Optional, build the StationDataTable without any actions, otherwise it will be built upon first loopkup like below.
            //On average, increases the first lookup time by 5 times. Obviously it's of no use in this application, but for an
            //application that runs lookups at a later time, you could build the table at the start and have it ready for later (assuming you even want persistant lookup).
            //StationLookup.ZeroActionInitialize();
            //Console.WriteLine("Don't wait more than 10 seconds...");

            Task t = new Task(() => {
                //GeoPositionPermission

                Watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                // Catch the StatusChanged event.

                Watcher.MovementThreshold      = 0;
                CancellationTokenSource source = new CancellationTokenSource();

                Task t3NonBlocking = new Task(() =>
                {
                    Task t2 = new Task(() =>
                    {
                        try
                        {
                            Console.Write("Locating Device...");
                            var accessStatus = Geolocator.RequestAccessAsync();

                            while (accessStatus.Status == Windows.Foundation.AsyncStatus.Completed)
                            {
                                Console.Write(".");
                                System.Threading.Thread.Sleep(1);
                                //t2.Status
                                if (source.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                            Console.WriteLine();
                        }
                        catch (TimeoutException ex)
                        {
                            Console.WriteLine("Error: " + ex.Message);
                        }
                    });
                    t2.Start();
                    t2.Wait();
                });

                t3NonBlocking.Start();
                t3NonBlocking.Wait(TimeSpan.FromSeconds(15));
                source.Cancel();

                if (t3NonBlocking.IsCompleted)
                {
                    // Subscribe to StatusChanged event to get updates of location status changes
                    //_geolocator.StatusChanged += OnStatusChanged;

                    if (Watcher.Permission != GeoPositionPermission.Granted)
                    {
                        Console.WriteLine("Make sure Windows 10 location privacy settings is enabled in settings.");
                    }

                    Watcher.StatusChanged += Watcher_StatusChanged;
                    // Start the watcher.

                    Watcher.Start();
                }
                else
                {
                    Console.WriteLine("Failed to get location.");
                }
                //ResolveAddressSync();
            });

            t.Start();
            Console.ReadLine();
        }
示例#7
0
        public async void dajLokaciju()
        {
            try
            {
                Geoposition pos = null;
                //da li se smije uzeti lokacija, trazi se odobrenje od korisnika (takodjer treba i capability)
                var accessStatus = await Geolocator.RequestAccessAsync();

                if (accessStatus == GeolocationAccessStatus.Allowed)
                {
                    //uzimanje pozicije ako smije
                    Geolocator geolocator = new Geolocator {
                        DesiredAccuracyInMeters = 10
                    };
                    pos = await geolocator.GetGeopositionAsync();
                }
                //tacka iz pozicije
                TrenutnaLokacija = pos.Coordinate.Point;
                Lokacija         = "Geolokacija Lat: " + TrenutnaLokacija.Position.Latitude + " Lng: " + TrenutnaLokacija.Position.Longitude;
                //uzeti adresu na osnovu GeoTacke
                MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pos.Coordinate.Point);

                //Nadje li adresu ispisi je
                if (result.Status == MapLocationFinderStatus.Success)
                {
                    Adresa = "Adresa je " + result.Locations[0].Address.Street;
                }
                //nacrtati pravougaonik na mapi za oblast gdje bi korisnik mogao biti
                double      centerLatitude  = Mapa.Center.Position.Latitude;
                double      centerLongitude = Mapa.Center.Position.Longitude;
                MapPolyline mapPolyline     = new MapPolyline();
                mapPolyline.Path = new Geopath(new List <BasicGeoposition>()
                {
                    new BasicGeoposition()
                    {
                        Latitude = centerLatitude - 0.0005, Longitude = centerLongitude - 0.001
                    },
                    new BasicGeoposition()
                    {
                        Latitude = centerLatitude + 0.0005, Longitude = centerLongitude - 0.001
                    },
                    new BasicGeoposition()
                    {
                        Latitude = centerLatitude + 0.0005, Longitude = centerLongitude + 0.001
                    },
                    new BasicGeoposition()
                    {
                        Latitude = centerLatitude - 0.0005, Longitude = centerLongitude + 0.001
                    },
                    new BasicGeoposition()
                    {
                        Latitude = centerLatitude - 0.0005, Longitude = centerLongitude - 0.001
                    }
                });
                mapPolyline.StrokeColor     = Colors.Black;
                mapPolyline.StrokeThickness = 3;
                mapPolyline.StrokeDashed    = true;
                Mapa.MapElements.Add(mapPolyline);
            }
            catch (Exception e)
            {
                var dialog11 = new MessageDialog(e.Message);
                dialog11.ShowAsync();
            }
        }
示例#8
0
 private static async Task <GeolocationAccessStatus> RequestLocationAccess()
 {
     return(await Geolocator.RequestAccessAsync());
 }
示例#9
0
        private async void DismissedEventHandler(SplashScreen sender, object args)
        {
            dismissed = true;
            await SQLAction.CheckDB();

            SetLongTimeTimer();
            var settings = SettingsModel.Current;
            var license  = new License.License();

            if (!license.IsPurchased)
            {
                settings.Preferences.EnableAlarm   = false;
                settings.Preferences.EnableEvening = false;
                settings.Preferences.EnableMorning = false;
                settings.Preferences.Set(240);
            }

            if (settings.Preferences.MainColor.A > 0)
            {
                App.MainColor = settings.Preferences.MainColor;
                await Dispatcher.RunAsync(CoreDispatcherPriority.High, new DispatchedHandler(() =>
                {
                    App.ChangeThemeColor(settings.Preferences.MainColor);
                    ChangeThemeColor(settings.Preferences.MainColor);
                }));
            }
            if (!settings.Inited)
            {
                NavigatetoStart();
                return;
            }
            if (!this.args.IsNullorEmpty())
            {
                settings.Cities.ChangeCurrent(this.args);
            }
            try
            {
                if (settings.Cities.GetCurrentCity() == null)
                {
                    NavigatetoStart();
                    return;
                }
            }
            catch (Exception)
            {
            }

            if (settings.Cities.CurrentIndex == -1 && settings.Cities.EnableLocate)
            {
                try
                {
                    var accessStatus = await Geolocator.RequestAccessAsync();

                    if (accessStatus == GeolocationAccessStatus.Allowed)
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.High, new DispatchedHandler(async() =>
                        {
                            var l = new ResourceLoader();
                            SplashWelcome.Text = l.GetString("Locating");
                            try
                            {
                                var _geolocator = new Geolocator();
                                var pos = await _geolocator.GetGeopositionAsync();
                                if ((_geolocator.LocationStatus != PositionStatus.NoData) && (_geolocator.LocationStatus != PositionStatus.NotAvailable) && (_geolocator.LocationStatus != PositionStatus.Disabled))
                                {
                                    var t = ThreadPool.RunAsync(async(w) =>
                                    {
                                        await CalcPosition(pos, settings);
                                        GetCityListandCompelte(settings);
                                    });
                                }
                                else
                                {
                                    GetCityListandCompelte(settings);
                                }
                            }
                            catch (Exception)
                            {
                                GetCityListandCompelte(settings);
                            }
                        }));
                    }
                    else
                    {
                        if (!settings.Cities.SavedCities.IsNullorEmpty())
                        {
                            settings.Cities.CurrentIndex = 0;
                        }
                        else
                        {
                            GetCityListandCompelte(settings);
                        }
                    }
                }
                catch (Exception)
                {
                    NavigatetoStart();
                }
            }
            else if (settings.Cities.CurrentIndex >= 0 && !settings.Cities.SavedCities.IsNullorEmpty())
            {
                foreach (var citty in settings.Cities.SavedCities)
                {
                    if (citty.Latitude == 0 && citty.Longitude == 0)
                    {
                        var tar = SQLAction.Find(citty.Id);
                        citty.Latitude  = tar.Latitude;
                        citty.Longitude = tar.Longitude;
                    }
                }
                settings.Cities.Save();
                GetCityListandCompelte(settings);
            }
            else
            {
                NavigatetoStart();
                return;
            }
        }
示例#10
0
        public async Task LoadCurrentWeatherAsync()
        {
            IsLoading      = true;
            Status         = 0;
            CurrentWeather = null;

            //get coordinate
            double lat = 0, lon = 0;

            if ((int)AppSettingsService.GetSetting(AppSettingsService.DEFAULT_LOCATION_MODE) == 0)
            {
                var accessStatus = await Geolocator.RequestAccessAsync();

                switch (accessStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    Geolocator  geolocator = new Geolocator();
                    Geoposition pos        = await geolocator.GetGeopositionAsync();

                    lat = pos.Coordinate.Point.Position.Latitude;
                    lon = pos.Coordinate.Point.Position.Longitude;
                    break;

                case GeolocationAccessStatus.Unspecified:
                case GeolocationAccessStatus.Denied:
                    Status = 1;
                    break;
                }
            }
            else
            {
                string[] temp = AppSettingsService.GetSetting(AppSettingsService.DEFAULT_LOCATION).ToString().Split('|');
                lat = double.Parse(temp[0]);
                lon = double.Parse(temp[1]);
            }

            //http call
            if (Status == 0)
            {
                if (IsInternetAvailable())
                {
                    try
                    {
                        CurrentWeather = await OpenWeatherService.GetWeatherByCoordinateAsync(lat, lon);

                        #region Update live tile
                        var liveTile = TileUpdateManager.CreateTileUpdaterForApplication();

                        string temperature = CurrentWeather.temperature.TemperatureUnit ? $"{CurrentWeather.temperature.temp_c}C" : $"{CurrentWeather.temperature.temp_f}F";
                        string time        = DateTime.Now.ToString("ddd h:mm tt");

                        //tile template
                        string tileXMLString = $@"<tile>
                                                    <visual baseUri=""Assets/Weather/"">
                                                  
                                                      <binding template=""TileSmall"" hint-textStacking=""center"">
                                                        <text hint-style=""body"" hint-align=""center"">{temperature}</text>
                                                      </binding>
                                                  
                                                      <binding displayName=""{CurrentWeather.city.name}"" template=""TileMedium"" hint-textStacking=""center"">
                                                        <text hint-style=""body"" hint-align=""center"">{CurrentWeather.weather.value}</text>
                                                        <text hint-style=""titleSubtle"" hint-align=""center"">{temperature}</text>
                                                        <text hint-style=""captionSubtle"" hint-align=""center"">{time}</text>
                                                      </binding>
                                                  
                                                      <binding displayName=""{CurrentWeather.city.name}"" template=""TileWide"" branding=""nameAndLogo"" hint-textStacking=""center"">
                                                        <group>
                                                          <subgroup hint-weight=""44"">
                                                            <image src=""{CurrentWeather.weather.iconUrl}"" hint-removeMargin=""false""/>
                                                          </subgroup>
                                                          <subgroup>
                                                            <text hint-style=""body"">{CurrentWeather.weather.value}</text>
                                                            <text hint-style=""titleSubtle"">{temperature}</text>
                                                            <text hint-style=""captionSubtle"">{time}</text>
                                                          </subgroup>
                                                        </group>
                                                      </binding>
                                                  
                                                      <binding displayName=""{CurrentWeather.city.name}"" template=""TileLarge"" branding=""nameAndLogo"" hint-textStacking=""center"">
                                                        <group>
                                                          <subgroup hint-weight=""1""/>
                                                          <subgroup hint-weight=""2"">
                                                            <image src=""{CurrentWeather.weather.iconUrl}""/>
                                                          </subgroup>
                                                          <subgroup hint-weight=""1""/>
                                                        </group>
                                                        <text hint-style=""body"" hint-align=""center"">{CurrentWeather.weather.value}</text>
                                                        <text hint-style=""titleSubtle"" hint-align=""center"">{temperature}</text>
                                                        <text hint-style=""captionSubtle"" hint-align=""center"">{time}</text>
                                                      </binding>
                                                  
                                                    </visual>
                                                  </tile>";

                        XmlDocument tileXML = new XmlDocument();
                        tileXML.LoadXml(tileXMLString);
                        liveTile.Update(new TileNotification(tileXML));
                        #endregion
                    }
                    catch
                    {
                        Status = 2;
                    }
                }
                else
                {
                    Status = 2;
                }
            }

            IsLoading = false;
        }
示例#11
0
        private async void Run_Click(object sender, RoutedEventArgs e)
        {
            if (RunButton.Content.Equals("Stop"))
            {
                RunButton.Content    = "Run";
                MainButton.IsEnabled = true;
                errormessage.Text    = "Ready to go";

                Stop_Band();

                ////////////////////////
                StopTracking(sender, e);
                /////////////////////
                return;
            }
            try
            {
                var now = DateTime.Now.ToString("dd/MM/yyyy@H:mm:ss");
                HttpStringContent stringContent = new HttpStringContent(
                    "{ \"partitionKey\": \"HRs\"," +
                    "\"rowKey\": \"" + localSettings.Values["pemail"] + "\"," +
                    "\"reads\": \"" + localSettings.Values["preads"] +
                    //  "\"," + "\"lastHR\": \"" + now +
                    "\"}",
                    UnicodeEncoding.Utf8, "application/json");



                var now2 = DateTime.Now.ToString("dd/MM/yyyy@H:mm:ss");
                HttpStringContent stringContent2 = new HttpStringContent(
                    "{ \"partitionKey\": \"Locations\"," +
                    "\"rowKey\": \"" + localSettings.Values["pemail"] + "\"," +
                    "\"readLatitude\": \"" + localSettings.Values["pLatitude"] + "\"," +
                    "\"readLongitude\": \"" + localSettings.Values["pLongitude"] + "\"," +
                    "\"lastLocatoin\": \"" + now2 + "\"}",
                    UnicodeEncoding.Utf8, "application/json");



                /*
                 * catch (Exception ex)
                 * {
                 *  errormessage.Text = "Location is unavailble";
                 * }
                 */
                try
                {
                    HttpResponseMessage response = await httpClient.PostAsync(requestUri, stringContent);

                    if ((int)response.StatusCode == 204)
                    {
                        localSettings.Values["plasthr"] = now;
                    }
                    else
                    {
                        errormessage.Text = await response.Content.ReadAsStringAsync();
                    }



                    HttpResponseMessage response2 = await httpClient.PostAsync(requestUriGPS, stringContent2);

                    if ((int)response2.StatusCode == 204)
                    {
                        localSettings.Values["plastLocation"] = now;
                    }
                    else
                    {
                        errormessage.Text = await response2.Content.ReadAsStringAsync();
                    }
                }
                catch (Exception ex)
                {
                    errormessage.Text = "Error: " + ex.Message;
                }
                RunButton.Content    = "Stop";
                MainButton.IsEnabled = false;
                errormessage.Text    = "Sampling in progress...";

                // Start reading data
                await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                await bandClient.SensorManager.Calories.StartReadingsAsync();

                await bandClient.SensorManager.Contact.StartReadingsAsync();

                await bandClient.SensorManager.Distance.StartReadingsAsync();

                await bandClient.SensorManager.Gyroscope.StartReadingsAsync();

                await bandClient.SensorManager.HeartRate.StartReadingsAsync();

                await bandClient.SensorManager.Pedometer.StartReadingsAsync();

                await bandClient.SensorManager.SkinTemperature.StartReadingsAsync();



                if (await Geolocator.RequestAccessAsync() != GeolocationAccessStatus.Allowed)
                {
                    if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Denied)
                    {
                        System.Diagnostics.Debug.Write("Access to location is denied");
                    }
                    else
                    {
                        System.Diagnostics.Debug.Write("Access to location isn't allowed: Unspecified ");
                    }

                    return;
                }
                else
                {
                    await StartTracking(sender, e);
                }
            }
            catch (Exception ex)
            {
                errormessage.Text = bterr;
            }
        }
        private async void ShowRouteOnMap()
        {
            // Request permission to access location
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                Geolocator geolocator = new Geolocator {
                    DesiredAccuracyInMeters = 100
                };

                // Carry out the operation
                Geoposition startPosition = await geolocator.GetGeopositionAsync().AsTask();

                BasicGeoposition endLocation = new BasicGeoposition()
                {
                    Latitude = 50.937000, Longitude = 4.033180
                };
                BasicGeoposition gep = new BasicGeoposition();
                gep.Latitude  = startPosition.Coordinate.Latitude;
                gep.Longitude = startPosition.Coordinate.Longitude;
                Geopoint gp1 = new Geopoint(gep);
                Geopoint gp2 = new Geopoint(endLocation);

                // Get the route between the points.
                MapRouteFinderResult routeResult =
                    await MapRouteFinder.GetDrivingRouteAsync(
                        gp1,
                        gp2,
                        MapRouteOptimization.Time,
                        MapRouteRestrictions.None);

                // Create a MapIcon.
                MapIcon mapIcon1 = new MapIcon();
                mapIcon1.Location = gp1;
                mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon1.Title  = "Uw locatie";
                mapIcon1.ZIndex = 0;
                // Add the MapIcon to the map.
                MyMap.MapElements.Add(mapIcon1);

                MapIcon mapIcon2 = new MapIcon();
                mapIcon2.Location = gp2;
                mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon2.Title  = "Hogent Campus Aalst Arbeidstraat 14";
                mapIcon2.ZIndex = 0;
                MyMap.MapElements.Add(mapIcon2);

                if (routeResult.Status == MapRouteFinderStatus.Success)
                {
                    // Use the route to initialize a MapRouteView.
                    MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                    viewOfRoute.RouteColor   = Colors.Yellow;
                    viewOfRoute.OutlineColor = Colors.Black;

                    // Add the new MapRouteView to the Routes collection
                    // of the MapControl.
                    MyMap.Routes.Add(viewOfRoute);

                    // Fit the MapControl to the route.
                    await MyMap.TrySetViewBoundsAsync(
                        routeResult.Route.BoundingBox,
                        null,
                        Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);
                }

                break;

            case GeolocationAccessStatus.Denied:
                //
                break;
            }
        }
示例#13
0
        /// <summary>
        /// Requests permission to access location data.
        /// </summary>
        /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
#if WINDOWS_UWP
        public virtual async Task <LocationServiceRequestResult> RequestAccessAsync()
        {
            var result = await Geolocator.RequestAccessAsync();

            return(result.ToLocationServiceRequestResult());
        }
示例#14
0
        // Main
        private async void MainCommands(string commands)
        {
            // Commands
            if (commands.ToLower().Contains("commands"))
            {
                MessageShow("Show Commands");
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Commands.Visibility = Visibility.Visible;
                });
            }
            // Mirror
            if (commands.ToLower().Contains("mirror"))
            {
                MessageShow("Show Mirror");
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Commands.Visibility = Visibility.Collapsed;
                    Map.Visibility      = Visibility.Collapsed;
                    Map.MapElements.Clear();
                    Map.ZoomLevel = 1;
                });
            }
            // Map
            if (commands.ToLower().Contains("map"))
            {
                MessageShow("Show Map");
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Map.Visibility = Visibility.Visible;
                });
            }
            // Location
            if (commands.ToLower().Contains("location"))
            {
                MessageShow("Show Location");
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        var locationAccessStatus = await Geolocator.RequestAccessAsync();
                        if (locationAccessStatus == GeolocationAccessStatus.Allowed)
                        {
                            Geolocator geolocator       = new Geolocator();
                            Geoposition currentPosition = await geolocator.GetGeopositionAsync();
                            Map.Center = new Geopoint(new BasicGeoposition()
                            {
                                Latitude  = currentPosition.Coordinate.Latitude,
                                Longitude = currentPosition.Coordinate.Longitude
                            });
                            Map.ZoomLevel = 13;
                        }
                    }
                    catch (Exception message)
                    {
                        Debug.WriteLine(message);
                    }
                });
            }
            // Landslides
            if (commands.ToLower().Contains("land") || (commands.ToLower().Contains("slides")))
            {
                MessageShow("Show Land Slides");

                // Visualize Land Slides
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        // JSON
                        var client   = new HttpClient();
                        var response = await client.GetAsync(new Uri("https://data.nasa.gov/resource/tfkf-kniw.json"));
                        var json     = await response.Content.ReadAsStringAsync();
                        JsonSerializer serializer = new JsonSerializer();
                        landslides = JsonConvert.DeserializeObject <List <LandSlides> >(json);
                        // Process
                        foreach (var item in landslides)
                        {
                            Geopoint _point = new Geopoint(new BasicGeoposition()
                            {
                                Latitude  = double.Parse(item.latitude),
                                Longitude = double.Parse(item.longitude)
                            });
                            MapIcon _icon = new MapIcon
                            {
                                Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/landslide.png")),
                                Location = _point,
                                NormalizedAnchorPoint = new Point(0.5, 1.0),
                                Title  = item.adminname1 + ", " + item.countryname + ", " + DateTime.Parse(item.date).ToString("dd.MM.yyyy"),
                                ZIndex = 0
                            };
                            Map.MapElements.Add(_icon);
                        }
                    }
                    catch (Exception message)
                    {
                        Debug.WriteLine(message);
                    }
                });
            }
        }
 public async Task <GeolocationAccessStatus> getGPSAccessStatus()
 {
     return(await Geolocator.RequestAccessAsync());
 }
示例#16
0
        private async void AfterPageLoaded()
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:

                // Get the current location.
                Geolocator geolocator = new Geolocator();
                try
                {
                    Geoposition pos = await geolocator.GetGeopositionAsync();

                    Geopoint myLocation = pos.Coordinate.Point;


                    // Create a MapIcon.
                    MapIcon mapIcon1 = new MapIcon();
                    mapIcon1.Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/neddle.png"));
                    mapIcon1.Location = myLocation;
                    mapIcon1.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0);

                    //mapIcon1.Title = "当前位置";
                    mapIcon1.ZIndex = 0;

                    // Add the MapIcon to the map.
                    map.Routes.Clear();
                    map.MapElements.Clear();
                    map.MapElements.Add(mapIcon1);
                    // Set the map location.
                    map.Center    = myLocation;
                    map.ZoomLevel = 16;

                    GetDefaultCity();
                    MyPresentLocation.name     = "我的位置";
                    MyPresentLocation.location = new BaiduSuggestion.Location {
                        lat = myLocation.Position.Latitude + 0.0058, lng = myLocation.Position.Longitude + 0.0064
                    };


                    LocationSearch.Text = "";
                    MapStartBox.Text    = "";
                    MapEndBox.Text      = "";
                }
                catch (Exception) {
                    MyPresentLocation.location = null;
                    var dialog = new MessageDialog("定位失败,请检查网络和定位服务是否开启", "消息提示");
                    dialog.Commands.Add(new UICommand("确定", cmd => { }, commandId: 0));
                    await dialog.ShowAsync();
                }
                break;

            case GeolocationAccessStatus.Denied:
                // Handle the case  if access to location is denied.
                break;

            case GeolocationAccessStatus.Unspecified:
                // Handle the case if  an unspecified error occurs.
                break;
            }
        }
示例#17
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _serviceDeferral       = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            // Get trigger details

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
            {
                try
                {
                    _voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

                    _voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync();

                    switch (voiceCommand.CommandName)
                    {
                    case "NearbySights":
                        GeolocationAccessStatus accessStatus;
                        try
                        {
                            // If we call this before the app has granted access, we get an exception
                            accessStatus = await Geolocator.RequestAccessAsync();
                        }
                        catch
                        {
                            // ensure we have a value
                            accessStatus = GeolocationAccessStatus.Unspecified;
                        }
                        if (accessStatus == GeolocationAccessStatus.Allowed)
                        {
                            var geolocator = new Geolocator();
#if DEBUG
                            // For testing, fake a location in San Francisco
                            Geopoint point = new Geopoint(new BasicGeoposition {
                                Latitude = 37.774930, Longitude = -122.419416
                            });
                            if (true)
                            {
#else
                            var pos = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(5));

                            if (pos != null)
                            {
                                Geocoordinate coordinate = pos.Coordinate;
#endif

                                var nearest = await GetNearestSights(point);

                                if (nearest != null && nearest.Any())
                                {
                                    await ShowNearestResults(nearest);
                                }
                                else
                                {
                                    await ReportFailureToGetSights();
                                }
                            }
                            else
                            {
                                await ReportFailureToGetCurrentLocation();
                            }
                        }
                        else
                        {
                            await ReportFailureToGetCurrentLocation();
                        }
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    var userMessage = new VoiceCommandUserMessage();
                    userMessage.SpokenMessage = "Sorry, I can't do that right now - something went wrong.";
                    // useful for debugging
                    userMessage.DisplayMessage = ex.Message;

                    var response = VoiceCommandResponse.CreateResponse(userMessage);

                    response.AppLaunchArgument = "LaunchApp";
                    await _voiceServiceConnection.ReportFailureAsync(response);
                }
            }
        }
示例#18
0
        /// <summary>
        /// Solves the current operation if possible, saving the operation in the user's history
        /// and setting the result as the first value of a new operation with no operator.
        /// If not possible, displayes DNE, and resets all operation values/operators.
        /// </summary>
        private async void EqualsButton_Click(object sender, RoutedEventArgs e)
        {
            // If there is an equation to solve
            if (usingValue1 && usingValue2 && operators.Length != 0)
            {
                double result = 0.0;
                // If the equation isn't a number divided by 0
                Boolean exists = true;
                if (operators == "+")
                {
                    result = value1 + value2;
                }
                else if (operators == "-")
                {
                    result = value1 - value2;
                }
                else if (operators == "*")
                {
                    result = value1 * value2;
                }
                else
                {
                    if (value2 == 0)
                    {
                        exists = false;
                    }
                    else
                    {
                        result = value1 / value2;
                    }
                }

                // Attempt at recording the user's location for thier history
                // External source: https://www.dotnetperls.com/switch
                // Currently does not work / cannot get permissions to allow location access
                var accessStatus = await Geolocator.RequestAccessAsync();

                // If device location is allowed
                bool allowed = true;
                switch (accessStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    allowed = true;
                    break;

                case GeolocationAccessStatus.Denied:
                    allowed = false;
                    break;
                }
                string longitude = "Not Availible";
                string latitude  = "Not Availible";
                if (allowed)
                {
                    // External source:
                    // https://docs.microsoft.com/en-us/windows/uwp/maps-and-location/get-location
                    Geolocator  geolocator  = new Geolocator();
                    Geoposition geoposition = await geolocator.GetGeopositionAsync();

                    latitude  = "" + geoposition.Coordinate.Point.Position.Latitude;
                    longitude = "" + geoposition.Coordinate.Point.Position.Longitude;
                }

                if (exists)
                {
                    await historyManager.AddHistory(value1, operators, value2, "" + result,
                                                    longitude, latitude);

                    DisplayResult(result);
                }
                else
                {
                    await historyManager.AddHistory(value1, operators, value2, "Does Not Exist", longitude, latitude);

                    CalculatorResultTextBlock.Text = "DNE";
                    value1      = 0;
                    value2      = 0;
                    usingValue1 = false;
                    usingValue2 = false;
                    CalculatorPreviousNumberTextBlock.Text = "";
                    operators = "";
                    CalculatorOperatorTextBox.Text = "";
                }
            }
        }
示例#19
0
        private async void FollowGPS_Toggled(object sender, RoutedEventArgs e)
        {
            ToggleSwitch sw = sender as ToggleSwitch;

            if (sw.IsOn)
            {
                var geoStatus = GeolocationAccessStatus.Unspecified;

                try
                {
                    // Catch error in case dialog is dismissed
                    geoStatus = await Geolocator.RequestAccessAsync();
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Error, ex, "SettingsPage: error getting location permission");
                }

                // Setup error just in case
                MessageDialog error = null;

                switch (geoStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    // Reset home location data
                    //Settings.SaveLastGPSLocData(new WeatherData.LocationData());
                    break;

                case GeolocationAccessStatus.Denied:
                    error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied"));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) =>
                    {
                        await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                    }, 0));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1));
                    error.DefaultCommandIndex = 0;
                    error.CancelCommandIndex  = 1;
                    await error.ShowAsync();

                    sw.IsOn = false;
                    break;

                case GeolocationAccessStatus.Unspecified:
                    error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                    await error.ShowAsync();

                    sw.IsOn = false;
                    break;

                default:
                    break;
                }
            }

            // Update ids when switching GPS feature
            if (sw.IsOn)
            {
                var prevLoc = (await Settings.GetFavorites()).FirstOrDefault();
                if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query))
                {
                    var gpsLoc = await Settings.GetLastGPSLocData();

                    if (gpsLoc?.query == null)
                    {
                        Settings.SaveLastGPSLocData(prevLoc);
                    }
                    else
                    {
                        await SecondaryTileUtils.UpdateTileId(prevLoc.query, gpsLoc.query);
                    }
                }
            }
            else
            {
                var prevLoc = await Settings.GetLastGPSLocData();

                if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query))
                {
                    var favLoc = (await Settings.GetFavorites()).FirstOrDefault();
                    if (favLoc?.query != null)
                    {
                        await SecondaryTileUtils.UpdateTileId(prevLoc.query, favLoc.query);
                    }
                }
            }

            Settings.FollowGPS = sw.IsOn;
            RequestAppTrigger  = true;
        }
示例#20
0
        public async Task LoadTripAsync(Guid tripId, bool animateMap = true)
        {
            // As we need to have requested this permission for our background task, ask here
            await Geolocator.RequestAccessAsync();

            CurrentTrip = await _dataModelService.LoadTripAsync(tripId);

            Sights =
                new ObservableCollection <Sight>(
                    CurrentTrip.Sights.OrderBy(s => s.RankInDestination));

            BuildSightGroups();

            if (Map != null)
            {
                var boundingBox = GeoboundingBox.TryCompute(GetSightsPositions());
                if (animateMap)
                {
                    // Delay to allow the Map to finish loading - on faster machines, animation fails
                    await Task.Delay(500);

                    // We actually don't want to wait for the map to stop animating
                    // so we assign the task to a variable to remove the warning about await
                    var task = Map.TrySetViewBoundsAsync(boundingBox,
                                                         new Thickness {
                        Left = 48, Top = 48, Right = 48, Bottom = 48
                    },
                                                         MapAnimationKind.Bow);
                }
                else
                {
                    // We actually don't want to wait for the map to stop animating
                    // so we assign the task to a variable to remove the warning about await
                    var task = Map.TrySetViewBoundsAsync(boundingBox,
                                                         new Thickness {
                        Left = 48, Top = 48, Right = 48, Bottom = 48
                    },
                                                         MapAnimationKind.None);
                }
            }

            EatsControlViewModel = new EatsControlViewModel {
                CenterLocation = CurrentTrip.Location, Trip = CurrentTrip
            };
            try
            {
                EatsControlViewModel.IsLoadingEats = true;
                EatsControlViewModel.Eats          =
                    new ObservableCollection <Restaurant>(await RestaurantDataService.Current.GetRestaurantsForTripAsync(CurrentTrip));
            }
            finally
            {
                EatsControlViewModel.IsLoadingEats = false;
            }


            // Set interactive tiles on load
            TileHelper.SetInteractiveTilesForTrip(CurrentTrip);
            // Also whenever the MySights collection changes
            Sights.CollectionChanged += (s, a) =>
                                        TileHelper.SetInteractiveTilesForTrip(CurrentTrip);
        }
示例#21
0
        public HomePage()
        {
            this.InitializeComponent();
            var accesStatus = Geolocator.RequestAccessAsync();

            ObservableCollection <RestaurantSpec> ocRestaurantSpecs = new ObservableCollection <RestaurantSpec>();

            var matches = DatabaseModel.RestaurantTable.Where(pair => true).Select(pair => pair.Value);

            foreach (var it in matches)
            {
                ocRestaurantSpecs.Add(it);
            }

            ObservableCollection <Meal> ocMeals = new ObservableCollection <Meal>();

            var matches2 = DatabaseModel.MealsTable.Where(pair => true).Select(pair => pair.Value);

            foreach (var it in matches2)
            {
                ocMeals.Add(it);
            }

            ObservableCollection <Order> ocOrders = new ObservableCollection <Order>();

            var matches3 = DatabaseModel.OrdersTable.Where(pair => true).Select(pair => pair.Value);

            foreach (var it in matches3)
            {
                ocOrders.Add(it);
            }


            DateTime       dateTime = new DateTime(2001, 1, 1);
            DateTimeOffset offset   = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);

            DatePickerFrom.Date = offset;

            this.viewModel = new RestaurantViewModel(ocRestaurantSpecs, ocMeals, ocOrders);
            ShellModel shellModel = Navigation.Shell.Model;

            ViewModel.IsDeliverer    = shellModel.IsDeliverer;
            ViewModel.IsOrderer      = shellModel.IsOrderer;
            ViewModel.IsUnregistered = !shellModel.IsRegistered;
            FilterOrders();
            if (ViewModel.IsDeliverer)
            {
                PivotGlobal.Items.Clear();
                PivotGlobal.Items.Add(PivotItemOrder);
                PivotGlobal.Items.Add(PivotItemRestaurant);
            }
            else if (ViewModel.IsOrderer)
            {
                PivotGlobal.Items.Clear();
                PivotGlobal.Items.Add(PivotItemMeal);
                PivotGlobal.Items.Add(PivotItemRestaurant);
                PivotGlobal.Items.Add(PivotItemOrder);
            }
            else
            {
                PivotGlobal.Items.Clear();
                PivotGlobal.Items.Add(PivotItemRestaurant);
                PivotGlobal.Items.Add(PivotItemMeal);
            }
        }
 public async static Task <bool> HasLocation()
 {
     return(await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed || Geolocator.DefaultGeoposition.HasValue);
 }
示例#23
0
        private async Task <bool> CheckLocationAsync()
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            return(accessStatus == GeolocationAccessStatus.Allowed);
        }
示例#24
0
        // set starttime based on user location
        public async void ActivateLocationMode()
        {
            //ui
            StackPanelTimePicker.Visibility   = Visibility.Collapsed;
            TextBlockDark.Visibility          = Visibility.Collapsed;
            TextBlockLight.Visibility         = Visibility.Collapsed;
            StackPanelLocationTime.Visibility = Visibility.Visible;
            SetOffsetVisibility(Visibility.Visible);
            locationBlock.Visibility = Visibility.Visible;
            locationBlock.Text       = Properties.Resources.msgSearchLoc;//Searching your location...
            userFeedback.Text        = Properties.Resources.msgSearchLoc;

            if (!init)
            {
                try
                {
                    builder.Save();
                }
                catch (Exception ex)
                {
                    ShowErrorMessage(ex);
                }
            }

            int  timeout = 2;
            bool loaded  = false;

            for (int i = 0; i < timeout; i++)
            {
                if (builder.LocationData.LastUpdate == DateTime.MinValue)
                {
                    try
                    {
                        var result = await messagingClient.SendMessageAndGetReplyAsync(Command.Location);

                        if (result == Response.NoLocAccess)
                        {
                            NoLocationAccess();
                            break;
                        }
                        builder.LoadLocationData();
                    }
                    catch (Exception ex)
                    {
                        ShowErrorMessage(ex);
                        loaded = true;
                        break;
                    }
                    await Task.Delay(1000);
                }
                else
                {
                    loaded = true;
                    break;
                }
            }

            LocationHandler locationHandler = new LocationHandler();
            var             accesStatus     = await Geolocator.RequestAccessAsync();

            switch (accesStatus)
            {
            case GeolocationAccessStatus.Allowed:
                //locate user + get sunrise & sunset times
                locationBlock.Text = Properties.Resources.lblCity + ": " + await locationHandler.GetCityName();

                break;

            case GeolocationAccessStatus.Denied:
                NoLocationAccess();
                loaded = false;
                break;

            case GeolocationAccessStatus.Unspecified:
                NoLocationAccess();
                loaded = false;
                break;
            }

            if (!loaded)
            {
                ShowErrorMessage(new TimeoutException("waiting for location data timed out"));
            }

            UpdateSuntimes();

            // ui controls
            lightStartBox.IsEnabled        = false;
            LightStartMinutesBox.IsEnabled = false;
            darkStartBox.IsEnabled         = false;
            DarkStartMinutesBox.IsEnabled  = false;
            userFeedback.Text = Properties.Resources.msgChangesSaved;

            return;
        }
示例#25
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS = false;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(false);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    location        = lastGPSLocData;
                    geoPos          = newGeoPos;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
        /// <summary>
        /// 获取地址
        /// </summary>
        /// <returns>KeyValuePair类型,键名为GeocationAccessStatus,值为城市全称。注意:当GeolocationAccessStatus为Denied时,应请求用户给予权限</returns>
        public async Task <KeyValuePair <GeolocationAccessStatus, string> > GetLoacationAsync()
        {
            try
            {
                // Request permission to access location
                var accessStatus = await Geolocator.RequestAccessAsync();

                switch (accessStatus)
                {
                case GeolocationAccessStatus.Allowed:

                    // Get cancellation token
                    _cts = new CancellationTokenSource();
                    CancellationToken token = _cts.Token;

                    // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                    Geolocator geolocator = new Geolocator {
                        DesiredAccuracyInMeters = _desireAccuracyInMetersValue
                    };

                    // Carry out the operation
                    Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);

                    string fomattedAddress = await UpdateLocationData(pos);

                    return(new KeyValuePair <GeolocationAccessStatus, string>(GeolocationAccessStatus.Allowed, fomattedAddress));

                //tbMessage.Text += "\nLocation updated.";

                case GeolocationAccessStatus.Denied:
                    //tbMessage.Text = "Access to location is denied.";
                    await UpdateLocationData(null);

                    return(new KeyValuePair <GeolocationAccessStatus, string>(GeolocationAccessStatus.Denied, string.Empty));

                //没有权限,应该向用户申请权限
                //参考资料:https://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/mt219698.aspx
                //bool result = await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                //                < TextBlock x: Name = "LocationDisabledMessage" FontStyle = "Italic"
                //         Visibility = "Collapsed" Margin = "0,15,0,0" TextWrapping = "Wrap" >

                //      < Run Text = "This app is not able to access Location. Go to " />

                //           < Hyperlink NavigateUri = "ms-settings:privacy-location" >

                //                < Run Text = "Settings" />

                //             </ Hyperlink >

                //         < Run Text = " to check the location privacy settings." />
                //</ TextBlock >

                case GeolocationAccessStatus.Unspecified:
                    //tbMessage.Text = "Unspecified error.";
                    await UpdateLocationData(null);

                    return(new KeyValuePair <GeolocationAccessStatus, string>(GeolocationAccessStatus.Unspecified, string.Empty));
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _cts = null;
            }

            return(new KeyValuePair <GeolocationAccessStatus, string>(GeolocationAccessStatus.Unspecified, string.Empty));
        }
示例#27
0
 public async void RequestAccess()
 {
     AccessStatus = await Geolocator.RequestAccessAsync();
 }
示例#28
0
        /// <summary>
        /// This is the click handler for the 'getGeolocation' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void GetGeolocationButtonClicked(object sender, RoutedEventArgs e)
        {
            GetGeolocationButton.IsEnabled       = false;
            CancelGetGeolocationButton.IsEnabled = true;
            LocationDisabledMessage.Visibility   = Visibility.Collapsed;

            try
            {
                // Request permission to access location
                var accessStatus = await Geolocator.RequestAccessAsync();

                switch (accessStatus)
                {
                case GeolocationAccessStatus.Allowed:

                    // Get cancellation token
                    _cts = new CancellationTokenSource();
                    CancellationToken token = _cts.Token;

                    //_rootPage.NotifyUser("Waiting for update...", NotifyType.StatusMessage);
                    LocationMessage.Text   = "Waiting for update...";   // + MainPage.NotifyType.StatusMessage;
                    ShowMessage.Background = new SolidColorBrush(Windows.UI.Colors.Green);

                    // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                    Geolocator geolocator = new Geolocator {
                        DesiredAccuracyInMeters = _desireAccuracyInMetersValue
                    };

                    // Carry out the operation
                    Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);

                    UpdateLocationData(pos);
                    //_rootPage.NotifyUser("Location updated.", NotifyType.StatusMessage);
                    LocationMessage.Text   = "Location updated.";   // + MainPage.NotifyType.StatusMessage;
                    ShowMessage.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    break;

                case GeolocationAccessStatus.Denied:
                    // _rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
                    LocationMessage.Text               = "Access to location is denied."; // + MainPage.NotifyType.ErrorMessage;
                    ShowMessage.Background             = new SolidColorBrush(Windows.UI.Colors.Red);
                    LocationDisabledMessage.Visibility = Visibility.Visible;
                    UpdateLocationData(null);
                    break;

                case GeolocationAccessStatus.Unspecified:
                    //_rootPage.NotifyUser("Unspecified error.", NotifyType.ErrorMessage);
                    LocationMessage.Text   = "Unspecified error.";   // + MainPage.NotifyType.ErrorMessage;
                    ShowMessage.Background = new SolidColorBrush(Windows.UI.Colors.Red);
                    UpdateLocationData(null);
                    break;
                }
            }
            catch (TaskCanceledException)
            {
                //_rootPage.NotifyUser("Canceled.", NotifyType.StatusMessage);
                LocationMessage.Text   = "Canceled"; //+ MainPage.NotifyType.StatusMessage;
                ShowMessage.Background = new SolidColorBrush(Windows.UI.Colors.Green);
            }
            catch (Exception ex)
            {
                //_rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                LocationMessage.Text   = "Unspecified error."; // + MainPage.NotifyType.ErrorMessage;
                ShowMessage.Background = new SolidColorBrush(Windows.UI.Colors.Red);
            }
            finally
            {
                _cts = null;
            }

            GetGeolocationButton.IsEnabled       = true;
            CancelGetGeolocationButton.IsEnabled = false;
        }
示例#29
0
 /// <summary>
 ///     Method for checking if the GPS receiver in the windows phone is reachable
 /// </summary>
 /// <returns>returns boolean which represents the accessibility</returns>
 private static async Task <bool> CheckGpsAccessibility()
 {
     return(await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed &&
            new Geolocator().LocationStatus != PositionStatus.NotAvailable);
 }
示例#30
0
        private async void ShowRouteOnMap(Trip trip)
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                Geolocator geolocator = new Geolocator {
                    DesiredAccuracy = PositionAccuracy.High
                };
                Geoposition geoposition = await geolocator.GetGeopositionAsync();

                BasicGeoposition startLocation = new BasicGeoposition()
                {
                    Latitude  = geoposition.Coordinate.Point.Position.Latitude,
                    Longitude = geoposition.Coordinate.Point.Position.Longitude
                };

                BasicGeoposition endLocation;

                MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(trip.Location, null, 1);

                endLocation = result.Status == MapLocationFinderStatus.Success
                        ? new BasicGeoposition()
                {
                    Latitude  = result.Locations[0].Point.Position.Latitude,
                    Longitude = result.Locations[0].Point.Position.Longitude
                }
                        : new BasicGeoposition()
                {
                    Latitude  = 51.0543422,
                    Longitude = 3.7174243
                };

                MapRouteFinderResult routeResult =
                    await MapRouteFinder.GetDrivingRouteAsync(
                        new Geopoint(startLocation),
                        new Geopoint(endLocation),
                        MapRouteOptimization.Time,
                        MapRouteRestrictions.None);

                if (routeResult.Status == MapRouteFinderStatus.Success)
                {
                    MapRouteView viewOfRoute = new MapRouteView(routeResult.Route)
                    {
                        RouteColor   = Colors.Yellow,
                        OutlineColor = Colors.Black
                    };
                    TravelMap.Routes.Add(viewOfRoute);
                    await TravelMap.TrySetViewBoundsAsync(
                        routeResult.Route.BoundingBox,
                        null,
                        MapAnimationKind.Bow);
                }
                break;

            case GeolocationAccessStatus.Denied:
                await ShowContentDialog();

                break;

            case GeolocationAccessStatus.Unspecified:
                await ShowContentDialog();

                break;

            default:
                break;
            }
        }