/// <summary> /// Stops the location service so it's no longer retrieving data. /// </summary> protected override void StopSensor() { _geoLocator.PositionChanged -= OnGeolocatorPositionChanged; _geoLocator.StatusChanged -= OnGeolocatorStatusChanged; _geoLocator = null; }
/// <summary> /// Starts the sensor. /// </summary> /// <returns><c>true</c> if the service started successfully; otherwise <c>false</c>.</returns> protected override bool StartSensor() { _geoLocator = new Geolocator(); _geoLocator.DesiredAccuracy = PositionAccuracy.High; _geoLocator.MovementThreshold = 1d; _geoLocator.PositionChanged += OnGeolocatorPositionChanged; _geoLocator.StatusChanged += OnGeolocatorStatusChanged; return _geoLocator.LocationStatus != PositionStatus.Disabled; }
private void OnGeolocatorPositionChanged(Geolocator sender, PositionChangedEventArgs e) { #if WIN80 var coordinate = e.Position.Coordinate; _lastKnownPosition = new Location(coordinate.Latitude, coordinate.Longitude, coordinate.Altitude ?? 0d); #else var position = e.Position.Coordinate.Point.Position; _lastKnownPosition = new Location(position.Latitude, position.Longitude, position.Altitude); #endif RaiseLocationChanged(); }
public void StopTracking() { if (!IsTracking) return; CurrentLocation.IsEnabled = false; CurrentLocation.IsResolved = false; _geolocator.PositionError -= OnListeningError; _geolocator.PositionChanged -= OnPositionChanged; _geolocator.StopListening(); IsTracking = false; _geolocator = null; }
public TripPage(MbtaRoutePrediction selectedRoute, MbtaPrediction singlePrediction, Geolocator.Plugin.Abstractions.Position currentLocation) { this.selectedRoute = selectedRoute; this.singlePrediction = singlePrediction; this.currentLocation = currentLocation; var mapPosition = new Position (currentLocation.Latitude, currentLocation.Longitude); currentSpan = MapSpan.FromCenterAndRadius(mapPosition, Distance.FromMiles(0.3)); map = new Map (currentSpan) { IsShowingUser = true, HeightRequest = 100, VerticalOptions = LayoutOptions.FillAndExpand }; var stack = new StackLayout { Spacing = 0 }; stack.Children.Add(map); Content = stack; FetchPredictions (); }
/// <summary> /// This is the click handler for the 'StartMonitoring' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void StartMonitoring(object sender, RoutedEventArgs e) { // Request permission to access location var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: _visitMonitor = new GeovisitMonitor(); // Add visit state changed event handler. _visitMonitor.VisitStateChanged += OnVisitStateChanged; // Start monitoring with the desired scope. // For higher granularity such as building/venue level changes, choose venue. // For lower granularity more or less in the range of zipcode level changes, choose city. // Choosing Venue here as an example. _visitMonitor.Start(VisitMonitoringScope.Venue); LocationDisabledMessage.Visibility = Visibility.Collapsed; _rootPage.NotifyUser("Waiting for update...", NotifyType.StatusMessage); StartMonitoringButton.IsEnabled = false; StopMonitoringButton.IsEnabled = true; break; case GeolocationAccessStatus.Denied: _rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage); LocationDisabledMessage.Visibility = Visibility.Visible; break; default: case GeolocationAccessStatus.Unspecified: _rootPage.NotifyUser("Unspecificed error!", NotifyType.ErrorMessage); LocationDisabledMessage.Visibility = Visibility.Collapsed; break; } }
private async Task LocateDevice() { try { var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: // Create Geolocator and define perodic-based tracking (2 minute interval). _geolocator = new Geolocator { MovementThreshold = 100 }; // Subscribe to the PositionChanged event to get location updates. _geolocator.PositionChanged += OnPositionChanged; // Subscribe to StatusChanged event to get updates of location status changes. _geolocator.StatusChanged += OnStatusChanged; break; case GeolocationAccessStatus.Denied: DisplayStatus("Access to location is denied."); break; case GeolocationAccessStatus.Unspecified: DisplayStatus("Location Unspecificed error!"); break; } } catch (TaskCanceledException) { DisplayStatus("Location Canceled."); } catch (Exception ex) { DisplayStatus(ex.Message); } }
private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e) { var geoCoordinate = new GeoCoordinate(e.Position.Coordinate.Latitude, e.Position.Coordinate.Longitude); double accuracy = e.Position.Coordinate.Accuracy; Dispatcher.BeginInvoke(() => { pbLoading.Visibility = Visibility.Collapsed; spFields.Visibility = Visibility.Visible; mLocation.SetView(geoCoordinate, App.MAP_ZOOM, MapAnimationKind.None); mLocation.Visibility = Visibility.Visible; if (mLocation.Layers.Count > 0) { var layer = mLocation.Layers[0]; var dot = layer[0]; var accuracyLayer = layer[1]; var radius = layer[2]; dot.GeoCoordinate = geoCoordinate; accuracyLayer.GeoCoordinate = geoCoordinate; radius.GeoCoordinate = geoCoordinate; var pointEllipse = (Ellipse)accuracyLayer.Content; pointEllipse.Width = accuracy; pointEllipse.Height = accuracy; } else { MapLayer pinLayer = CreateMapLayer(geoCoordinate, accuracy); mLocation.Layers.Add(pinLayer); } sRadius.Minimum = accuracy; }); }
public ExtendedStart() { this.InitializeComponent(); Loaded += async(s, e) => { if (InfoHub.AppHubViewModel.Strings.IncludeAdvertising) { try { var _Geo = new Geolocator(); await _Geo.GetGeopositionAsync(); } catch { // this breakpoint may be reached if the user BLOCKS location services Debug.WriteLine("Error reading location; user may have BLOCKED"); System.Diagnostics.Debugger.Break(); } } this.Frame.Navigate(typeof(AppHub)); }; }
private void UpdateReportInterval(uint reportInterval) { _skipNextPosition = true; // Windows Phone suspends the app when all eventhandlers of all GeoLocator objects are removed (only in background mode) // Wire up a temporary Geolocator to prevent the app from closing var tempGeolocator = new Geolocator { MovementThreshold = 1, ReportInterval = 1 }; TypedEventHandler <Geolocator, PositionChangedEventArgs> dummyHandler = (sender, positionChangesEventArgs2) => { }; tempGeolocator.PositionChanged += dummyHandler; // It is not allowed to change properties of Geolocator when eventhandlers are attached Geolocator.PositionChanged -= OnGeolocatorPositionChanged; Geolocator.ReportInterval = reportInterval; Geolocator.PositionChanged += OnGeolocatorPositionChanged; tempGeolocator.PositionChanged -= dummyHandler; }
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { if (!App.RunningInBackground) { Outils.PostGeolocToJeedom(args.Position.Coordinate); Dispatcher.BeginInvoke(() => { // LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00"); // LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00"); }); } else { /*Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast(); * toast.Content = args.Position.Coordinate.Point.Position.Latitude.ToString("0.00"); * toast.Title = "Location: "; * //toast.NavigationUri = new Uri("/Page2.xaml", UriKind.Relative); * toast.Show();*/ Outils.PostGeolocToJeedom(args.Position.Coordinate); } }
public void Init() { IsGPSStarted = false; try { _geolocator = new Geolocator(); _geolocator.ReportInterval = (uint)TimeUpdates; _geolocator.PositionChanged += Geolocator_PositionChanged; IsGPSStarted = true; } catch { if (Geolocator.DefaultGeoposition.HasValue) { _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(5); _timer.Tick += Timer_Tick; _timer.Start(); IsGPSStarted = true; } } }
/* * GEOLOCATOR METHODS */ private void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args) { String status = ""; switch (args.Status) { case PositionStatus.Disabled: // the application does not have the right capability or the location master switch is off status = "ubicación deshabilitada"; break; case PositionStatus.Initializing: // the geolocator started the tracking operation status = "inicializando"; break; case PositionStatus.NoData: // the location service was not able to acquire the location status = "sin datos"; break; case PositionStatus.Ready: // the location service is generating geopositions as specified by the tracking parameters status = "listo"; break; case PositionStatus.NotAvailable: status = "no disponible"; // not used in WindowsPhone, Windows desktop uses this value to signal that there is no hardware capable to acquire location information break; case PositionStatus.NotInitialized: // the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state break; } Dispatcher.BeginInvoke(() => geoStatusTB.Text = "Estado: " + status); }
private static async Task <bool> getLocationByGeolocatorAsync() { if (geolocator == null) { geolocator = new Geolocator(); } bool boSuccess = false; //some preflight checks here if (geolocator.LocationStatus != PositionStatus.Disabled && geolocator.LocationStatus != PositionStatus.NotAvailable) { try { // Get cancellation token _geolocationCancelationTokenSource = new CancellationTokenSource(); CancellationToken token = _geolocationCancelationTokenSource.Token; //start internal timer to cancel geolocation before geolocator timeout will throw the uncatchable exception cancelGeolocationTimerAsync(); Geoposition position = await geolocator.GetGeopositionAsync().AsTask(token); //do some stuff with the result boSuccess = true; } catch (Exception e) //<= that catch-bloack will only catch exceptions thrown on every code which is NOT the "await GetGeolocationAsync()" { //do your exception handling here } finally { _geolocationCancelationTokenSource = null; } } return(boSuccess); }
private async void UploadLocation(object sender, RoutedEventArgs e) { Geolocator geolocator = new Geolocator(); // 期望的精度级别(PositionAccuracy.Default 或 PositionAccuracy.High) geolocator.DesiredAccuracy = PositionAccuracy.High; // 期望的数据精度(米) geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync(); Dictionary <string, string> locationPair = new Dictionary <string, string>(); locationPair.Add("ID", StaticObj.user.ID); locationPair.Add("LONGITUDE", geoposition.Coordinate.Point.Position.Longitude.ToString("0.000")); locationPair.Add("LATITUDE", geoposition.Coordinate.Point.Position.Latitude.ToString("0.000")); locationPair.Add("ALTITUDE", geoposition.Coordinate.Point.Position.Altitude.ToString("0.000")); locationPair.Add("TIME", DateTime.Now.ToString()); locationPair.Add("POSITIONSOURCE", geoposition.Coordinate.PositionSource.ToString()); StaticObj.SendPackets(DataParser.Str2Packets(Convert.ToInt32(CommandCode.SendLocation), JsonParser.SerializeObject(locationPair))); Packet[] incomming = await StaticObj.ReceivePackets(); if (DataParser.GetPacketCommandCode(incomming[0]) == Convert.ToInt32(CommandCode.ReturnLocation)) { if (Convert.ToInt32(DataParser.Packets2Str(incomming)) != 0) { await(new MessageDialog(String.Format("发送成功!\n时间:{0}\n经度:{1}\n纬度:{2}海拔:{3}\n位置信息来源:{4}", locationPair["TIME"], locationPair["LONGITUDE"], locationPair["LATITUDE"], locationPair["ALTITUDE"], locationPair["POSITIONSOURCE"]))).ShowAsync(); } } else { await(new MessageDialog("上传失败!")).ShowAsync(); } } catch { } }
private async void LoadData() { try { if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent")) { //User already gave us his agreement for using his position if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] == true) { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10)); var wc = new WebClient(); wc.DownloadStringCompleted += wc_DownloadStringCompleted; wc.DownloadStringAsync(new Uri(string.Format("{0}{1},{2}.json", WEATHER_PATH, geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude))); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { MessageBox.Show("Geolocation is disabled in the Settings."); } } } } // 37.8,-122.4 } catch (Exception ex) { throw; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { if (geo == null) { geo = new Geolocator(); } Geoposition pos = await geo.GetGeopositionAsync(); sss.Center = new Geopoint(new BasicGeoposition() { Latitude = 54.989995, Longitude = 82.901572 }); JObject obj = JObject.Parse(await GetJSON(pos)); JArray jarr = (JArray)obj["results"]; for (int i = 0; i < jarr.Count; i++) { MapIcon icon = new MapIcon(); JObject geom = (JObject)jarr.ElementAt(i)["geometry"]; JObject loc = (JObject)geom["location"]; icon.Location = new Geopoint(new BasicGeoposition() { Latitude = Convert.ToDouble(Convert.ToDouble(loc["lat"]).ToString("000.000000")), Longitude = Convert.ToDouble(Convert.ToDouble(loc["lng"]).ToString("000.000000")) }); icon.NormalizedAnchorPoint = new Point(0.5, 1.0); icon.Title = (string)jarr[i]["name"]; icon.Visible = true; //icon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/othericons/mapiconsmall.png")); sss.MapElements.Add(icon); } sss.ZoomLevel = 12; sss.LandmarksVisible = true; }
public override void ViewDidLoad() { base.ViewDidLoad(); buttonLocation.TouchUpInside += (sender, e) => { var locator = new Geolocator { DesiredAccuracy = 50 }; locator.GetPositionAsync(timeout: 10000).ContinueWith(t => { var text = String.Format("Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude); InvokeOnMainThread(() => LabelLocation.Text = text); }); }; buttonPicture.TouchUpInside += (sender, e) => { var camera = new MediaPicker(); if (!camera.IsCameraAvailable) { Console.WriteLine("Camera unavailable!"); return; } var opts = new StoreCameraMediaOptions { Name = "test.jpg", Directory = "MiniHackDemo" }; camera.TakePhotoAsync(opts).ContinueWith(t => { if (t.IsCanceled) { return; } InvokeOnMainThread(() => imagePhoto.Image = UIImage.FromFile(t.Result.Path)); }); }; }
public async void Run(IBackgroundTaskInstance taskInstance) { serviceDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled; var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails; // This should match the uap:AppService and VoiceCommandService references from the // package manifest and VCD files, respectively. Make sure we've been launched by // a Cortana Voice Command. if (triggerDetails != null && triggerDetails.Name == "Cortana") { try { voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted; // GetVoiceCommandAsync establishes initial connection to Cortana, and must // be called prior to any // messages sent to Cortana. Attempting to use // ReportSuccessAsync, ReportProgressAsync, etc // prior to calling this will produce undefined behavior. var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync(); var text = voiceCommand.SpeechRecognitionResult.Text; var loc = await Geolocator.RequestAccessAsync(); if (loc == GeolocationAccessStatus.Allowed) { Geolocator geolocator = new Geolocator(); var myloc = await geolocator.GetGeopositionAsync(); RespondTouser("Here is your location", myloc.Coordinate.Point); } else { RespondTouser("I can't access to your location! Where are you?"); } } catch { } } }
private async Task getCoordinates() { loadingBar.Visibility = Visibility.Visible; if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true) { // The user has opted out of Location. return; } Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMilliseconds(5), TimeSpan.FromSeconds(10)); Helper.latitude = geoposition.Coordinate.Latitude.ToString("0.00"); Helper.longitude = geoposition.Coordinate.Longitude.ToString("0.00"); //string location = "Longitude: " + Helper.longitude + ", Latitude: " + Helper.latitude; //MessageBox.Show(location); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { throw new Exception("NoLocationException"); // the application does not have the right capability or the location master switch is off //MessageBox.Show("This app requires your location to search for perks nearby. Please enable location in phone setting.", "Location Service Required", MessageBoxButton.OKCancel); } //else //{ // // something else happened acquring the location //} } }
/*Method gets the users Current location and passes the Long/Lat to the Bing Map showing you your current location */ private async void GetUserLocation() { var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: try { Geolocator _geolocator = new Geolocator { DesiredAccuracyInMeters = 10 }; Geoposition pos = await _geolocator.GetGeopositionAsync(); BasicGeoposition geo = new BasicGeoposition(); geo.Latitude = pos.Coordinate.Point.Position.Latitude; geo.Longitude = pos.Coordinate.Point.Position.Longitude; BingMap.Center = new Geopoint(geo); //Center Map on geolocation BingMap.ZoomLevel = 7; //Sets the zoom level on the map } catch (Exception) { } BingMap.Height = SpMap.ActualHeight; //important, sets height to stackpannels height break; case GeolocationAccessStatus.Denied: //Please turn your location on break; case GeolocationAccessStatus.Unspecified: GetUserLocation(); break; } }
public async Task GetAccess() { 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(); //{ ReportInterval = 1000 * 60 * 5 }; // 5 min -> 1000 milisec * 60 sec * 5 min // Subscribe to the StatusChanged event to get updates of location status changes. // Carry out the operation. Geoposition = await geolocator.GetGeopositionAsync(); try { var cont = App.Container.Resolve <ApplicationDataContainer>(); await _apiService.UpdateLocation(new LocationDto { Latitude = Geoposition.Coordinate.Point.Position.Latitude, Longitude = Geoposition.Coordinate.Point.Position.Longitude }, cont.Values["AuthToken"] as string); } catch (Exception) { } break; case GeolocationAccessStatus.Denied: break; case GeolocationAccessStatus.Unspecified: break; } }
private async void weatherButton_Click(object sender, RoutedEventArgs e) { progressRing.IsActive = true; //activate the progress ring while data loads // adapted from-http://stackoverflow.com/questions/24238373/geolocation-in-c-sharp var geoLocator = new Geolocator(); //Create object geoLocator.DesiredAccuracy = PositionAccuracy.High; //Add accuracy Geoposition pos = await geoLocator.GetGeopositionAsync(); //async operation to get current location Lat = pos.Coordinate.Point.Position.Latitude.ToString(); //getting location for lat Lng = pos.Coordinate.Point.Position.Longitude.ToString(); //getting location for lng var data = await Helper.Helper.GetWeather(Lat, Lng); //getting data from the http client if (data != null) { txtCity.Text = $"{data.name},{data.sys.country}"; //location name = area txtLastUpdate.Text = $"Last updated : {DateTime.Now.ToString("dd MMMM yyyy HH:mm")}"; // last updated //adapted https://msdn.microsoft.com/en-us/library/aa970269(v=vs.110).aspx BitmapImage image = new BitmapImage(new Uri($"http://openweathermap.org/img/w/10d.png", UriKind.Absolute)); //Initializes a new instance of the BitmapImage class by using the supplied Uri. imgWeather.Source = image; //this is passed to the grid on XAML //"XAML Page text block name".Text = the WeatherAttributes txtDescription.Text = $"{data.weather[0].description}"; txtHumidity.Text = $"Humidity : {data.main.humidity}%"; //getting the time of the sunrise and sunset txtTime.Text = $"Sunrise/Sunset: {Common.APIclass.ConvertUnixTimeToDateTime(data.sys.sunrise).ToString("HH:mm")}/ {Common.APIclass.ConvertUnixTimeToDateTime(data.sys.sunset).ToString("HH:mm")}"; txtCel.Text = $"Temperature: {data.main.temp} °C"; // temperature windSpeed.Text = $"Wind: {data.wind.speed} km/h"; // speed of wind windDeg.Text = $"{data.wind.deg} degree direction"; //direction of wind } progressRing.IsActive = false; // deactivate the progress ring when close }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args) { Dispatcher.BeginInvoke(() => { switch (args.Status) { case PositionStatus.Disabled: if (_miscFunctions.ShowMessage("Location in settings is off.", "Location Services")) { Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); } break; case PositionStatus.Initializing: // the geolocator started the tracking operation SetProgressIndicator(true, "Acquiring position from location services"); if (App.MyMap.ZoomLevel < 12) { App.Zoom = 12; } App.Geolocator.PositionChanged += Geolocator_PositionChanged; break; case PositionStatus.NoData: // the location service was not able to acquire the location break; case PositionStatus.Ready: // the location service is generating geopositions as specified by the tracking parameters if (_prog.IsVisible) { SetProgressIndicator(false, ""); } break; case PositionStatus.NotInitialized: // the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state //MessageBox.Show("Not Initialized"); break; } }); }
//TODO //public Bing.Maps.Location CenterLocation //{ // get // { // if (CurrentLocation == null) // return null; // return new Bing.Maps.Location(CurrentLocation.Latitude, CurrentLocation.Longitude); // } //} async void _instance_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { try { try { CurrentLocation = args.Position.Coordinate; } catch { } var stationList = StationService.GetStations(); var list = await Task.Run(() => { foreach (var item in stationList) { CalcDistance(item); } return(stationList.OrderBy(x => x.Distance).Take(10)); }); DispatcherHelper.UIDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Stations = list; CurrentLocation = _currentLocation; }); //DispatcherHelper.UIDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // CurrentLocation = args.Position.Coordinate; //}); } catch { } }
async void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { // Associate a cancellation handler with the background task. taskInstance.Canceled += OnCanceled; // Get cancellation token _cts = new CancellationTokenSource(); CancellationToken token = _cts.Token; // Create geolocator object Geolocator geolocator = new Geolocator(); // Make the request for the current position Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token); WriteStatusToAppData($"Time: {DateTime.Now:G}"); WriteGeolocToAppData(pos); } catch (UnauthorizedAccessException) { WriteStatusToAppData("Disabled"); WipeGeolocDataFromAppData(); } catch (Exception ex) { WriteStatusToAppData(ex.ToString()); WipeGeolocDataFromAppData(); } finally { _cts = null; deferral.Complete(); } }
private async Task getLivelocation() { var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: ProgressDialog progressDialog = new ProgressDialog(); progressDialog.Owner = this; Application.Current.Dispatcher.Invoke(new Action(() => this.IsEnabled = false)); _ = progressDialog.Dispatcher.BeginInvoke(new Action(() => progressDialog.ShowDialog())); // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used. Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 0 }; // Carry out the operation Geoposition pos = await geolocator.GetGeopositionAsync(); myCurrLocation = new Microsoft.Maps.MapControl.WPF.Location(pos.Coordinate.Point.Position.Latitude, pos.Coordinate.Point.Position.Longitude); Application.Current.Dispatcher.Invoke(new Action(() => this.IsEnabled = true)); progressDialog.Close(); break; default: MessageBox.Show("We can't reach your location. Please check that the following location privacy are turned on:\n" + "Location for this device... is turned on (not applicable in Windows 10 Mobile\n" + "The location services setting, Location, is turned on\n" + "Under Choose apps that can use your location, your app is set to on\n "); break; } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); try { await StartCamera(); _orientationSensor = SimpleOrientationSensor.GetDefault(); if (_orientationSensor != null) { _orientationSensor.OrientationChanged += SimpleOrientationSensorReadingChanged; UpdateOrientation(_orientationSensor.GetCurrentOrientation()); } _compass = Compass.GetDefault(); if (_compass != null) { _compass.ReadingChanged += CompassReadingChanged; CompassChanged(_compass.GetCurrentReading()); } _gps = new Geolocator(); _gps.MovementThreshold = _movementThreshold; _gps.PositionChanged += GpsPositionChanged; if (_gps.LocationStatus == PositionStatus.Ready) { var pos = await _gps.GetGeopositionAsync(); if (pos != null && pos.Coordinate != null && pos.Coordinate.Point != null) { GpsChanged(pos.Coordinate.Point.Position); } } } catch { } }
async Task <int> reqLocAccessAsync() { try { m.locAccStat = await Geolocator.RequestAccessAsync(); } catch (Exception ex) { StatusText = ex.Message; } switch (m.locAccStat) { case GeolocationAccessStatus.Allowed: m.localSettings.Values["AutoPos"] = true; break; default: var cd = new ContentDialog { Title = m.resLoader.GetString("enableGpsFail") }; var txt = new TextBlock { Text = m.resLoader.GetString("enableGpsFailMsg"), TextWrapping = TextWrapping.Wrap }; cd.Content = txt; cd.PrimaryButtonText = "OK"; cd.PrimaryButtonClick += async(sender, e) => { await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location")); }; await cd.ShowAsync(); m.localSettings.Values["AutoPos"] = false; break; } OnPropertyChanged("AutoPos"); return(0); }
/// <summary> /// Checks for current location when navigated from secondary tile /// </summary> /// <returns></returns> private async void GetCurrentLocation() { this.Dispatcher.BeginInvoke(async() => { try { if (NetworkInterface.GetIsNetworkAvailable()) { Geolocator geolocator = new Geolocator(); Geoposition geoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30)); Geocoordinate geocoordinate = geoposition.Coordinate; App.ViewModel.CityDetailsViewModel.CurrentLocationCoordinates = new Altitude() { Latitude = geocoordinate.Latitude, Longitude = geocoordinate.Longitude }; LoadTileData(App.ViewModel.CityDetailsViewModel.CurrentLocationCoordinates); } else { MessageBox.Show(AppResources.NoInternetConnectionMessage, AppResources.NoInternetMessageTitle, MessageBoxButton.OK); } } catch (Exception) { var messageResult = MessageBox.Show(AppResources.LocationServiceOffMessage, AppResources.LocationServiceText, MessageBoxButton.OKCancel); if (messageResult == MessageBoxResult.OK) { var op = Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); LoadTileData(App.ViewModel.CityDetailsViewModel.CurrentLocationCoordinates); } else { LoadTileData(App.ViewModel.CityDetailsViewModel.CurrentLocationCoordinates); } } }); }
private async void doRegister() { if (checkRegister()) { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; float[] coord = new float[2]; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10) ); coord[0] = float.Parse(geoposition.Coordinate.Latitude.ToString("0.00")); coord[1] = float.Parse(geoposition.Coordinate.Longitude.ToString("0.00")); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { System.Diagnostics.Debug.WriteLine("Cant get location"); coord[0] = 50.0f; coord[1] = 50.0f; } else { } } char[] delimiters = { '/', ' ' }; string[] parsedBirthday = BoxBirthday.Value.ToString().Split(delimiters); string birthday = parsedBirthday[2] + ',' + parsedBirthday[1] + ',' + parsedBirthday[0]; await WeBallAPI.register(BoxPassword.Password, BoxEmail.Text, BoxNom_Complet.Text, birthday, imageInput.Source, coord); NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative)); } }
/// <summary> /// Updates the user position. /// </summary> private void UpdateUserPosition() { // If showing the current user position var map = (MapEx)this.Element; if (map.ShowUserPosition) { // Create a new location service if none if (this.geolocator == null) { this.geolocator = new Geolocator(); } // If GPS service is available if ((this.geolocator.LocationStatus != PositionStatus.NotAvailable) && (this.geolocator.LocationStatus != PositionStatus.Disabled)) { // Subscribe to position updates this.geolocator.ReportInterval = 30000; // Half minute this.geolocator.DesiredAccuracy = PositionAccuracy.High; this.geolocator.PositionChanged += this.GeolocatorOnPositionChanged; } } else { // Remove the location service this.geolocator.PositionChanged -= this.GeolocatorOnPositionChanged; this.geolocator = null; // Remove the user mark control if ((this.userPositionCircle != null) && this.Control.Children.Contains(this.userPositionCircle)) { // Remove the user position circle this.Control.Children.Remove(this.userPositionCircle); this.userPositionCircle = null; } } }
private async void btBatDau_Click(object sender, RoutedEventArgs e) { if (!tracking) { txtDistance.Text = ""; StartLocationExtensionSession(); txtStatus.Text = "Getting your location"; distance = 0; await GetPositionAndShowPoint(); geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.High; geolocator.MovementThreshold = 100; geolocator.StatusChanged += geolocator_StatusChanged; geolocator.PositionChanged += geolocator_PositionChanged; tracking = true; btBatDau.Content = "Stop"; btLuu.IsEnabled = false; txtKetQua.Text = ""; SelectItem(); } else { StopLocationExtensionSession(); geolocator.StatusChanged -= geolocator_StatusChanged; geolocator.PositionChanged -= geolocator_PositionChanged; geolocator = null; tracking = false; btBatDau.Content = "Start"; txtStatus.Text = ""; btLuu.IsEnabled = true; if (txtDistance.Text == "") { btLuu.IsEnabled = false; } } }
private async Task InitializeGeolocation() { //Get permission to use location var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: var geofences = GeofenceMonitor.Current.Geofences; SetGeofenceList(geofences); // register for status change events GeofenceMonitor.Current.StatusChanged += Current_StatusChanged;; // set my current position Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 10 }; geolocator.PositionChanged += OnPositionChanged; // Carry out the operation. Geoposition pos = await geolocator.GetGeopositionAsync(); UpdateLocationData(pos); break; case GeolocationAccessStatus.Denied: Debug.WriteLine("Access denied."); UpdateLocationData(null); break; case GeolocationAccessStatus.Unspecified: Debug.WriteLine("Unspecified error."); UpdateLocationData(null); break; } }
public async void getCurrentPosition( JObject options, ICallback success, ICallback error) { var locationOptions = LocationOptions.FromJson(options); var geolocator = new Geolocator { DesiredAccuracy = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default, MovementThreshold = locationOptions.DistanceFilter, }; try { // TODO: Enable retrieval from position history using `MaximumAge` filter var task = geolocator.GetGeopositionAsync().AsTask(); var completedTask = await Task.WhenAny( task, Task.Delay(TimeSpan.FromMilliseconds(locationOptions.Timeout))).ConfigureAwait(false); if (completedTask == task) { var geoposition = await task.ConfigureAwait(false); success.Invoke(ConvertGeoposition(geoposition)); } else { error.Invoke("Location request timed out"); } } catch (Exception ex) { error.Invoke($"Location request failed with exception: {ex}"); } }
protected override async void OnResume () { base.OnResume (); int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0); if(itemId > 0) { shareItem = App.Database.GetItem(itemId); fileName = shareItem.ImagePath; System.Console.WriteLine("Image path: " + fileName); Bitmap b = BitmapFactory.DecodeFile (fileName); // Display the bitmap photoImageView.SetImageBitmap (b); locationText.Text = shareItem.Location; return; } if (fileName == "") { fileName = "in-progress"; var picker = new MediaPicker (this); // new MediaPicker (); on iOS if (!picker.IsCameraAvailable) System.Console.WriteLine ("No camera!"); else { var options = new StoreCameraMediaOptions { Name = DateTime.Now.ToString("yyyyMMddHHmmss"), Directory = "MediaPickerSample" }; #if !VISUALSTUDIO #region new style if (!picker.IsCameraAvailable || !picker.PhotosSupported) { ShowUnsupported(); return; } Intent intent = picker.GetTakePhotoUI (options); StartActivityForResult (intent, 1); #endregion #else #region old style (deprecated) var t = picker.TakePhotoAsync (options); await t; if (t.IsCanceled) { System.Console.WriteLine ("User canceled"); fileName = "cancelled"; // TODO: return to main screen StartActivity(typeof(MainScreen)); return; } System.Console.WriteLine (t.Result.Path); fileName = t.Result.Path; fileNameThumb = fileName.Replace(".jpg", "_thumb.jpg"); Bitmap b = BitmapFactory.DecodeFile (fileName); RunOnUiThread (() => { // Display the bitmap photoImageView.SetImageBitmap (b); // Cleanup any resources held by the MediaFile instance t.Result.Dispose(); }); var boptions = new BitmapFactory.Options {OutHeight = 128, OutWidth = 128}; var newBitmap = await BitmapFactory.DecodeFileAsync (fileName, boptions); var @out = new System.IO.FileStream(fileNameThumb, System.IO.FileMode.Create); newBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, @out); //}); #endregion #endif } } try { var locator = new Geolocator (this) { DesiredAccuracy = 50 }; // new Geolocator () { ... }; on iOS var position = await locator.GetPositionAsync (timeout: 10000); System.Console.WriteLine ("Position Latitude: {0}", position.Latitude); System.Console.WriteLine ("Position Longitude: {0}", position.Longitude); location = string.Format("{0},{1}", position.Latitude, position.Longitude); locationText.Text = location; } catch (Exception e) { System.Console.WriteLine ("Position Exception: " + e.Message); } }
private void OnGeolocatorStatusChanged(Geolocator sender, StatusChangedEventArgs e) { Log.Info("Changed status to '{0}'", e.Status); RaiseLocationChanged(); }
protected override async void OnResume () { base.OnResume (); int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0); if(itemId > 0) { shareItem = App.Database.GetItem(itemId); fileName = shareItem.ImagePath; Console.WriteLine ("Image path: {0}", fileName); Bitmap b = BitmapFactory.DecodeFile (fileName); // Display the bitmap photoImageView.SetImageBitmap (b); locationText.Text = shareItem.Location; return; } if (string.IsNullOrEmpty (fileName)) { fileName = "in-progress"; var picker = new MediaPicker (this); if (!picker.IsCameraAvailable) { Console.WriteLine ("No camera!"); } else { var options = new StoreCameraMediaOptions { Name = DateTime.Now.ToString ("yyyyMMddHHmmss"), Directory = "MediaPickerSample" }; if (!picker.IsCameraAvailable || !picker.PhotosSupported) { ShowUnsupported(); return; } Intent intent = picker.GetTakePhotoUI (options); StartActivityForResult (intent, 1); } } else { SetImage (); } try { var locator = new Geolocator (this) { DesiredAccuracy = 50 }; var position = await locator.GetPositionAsync (10000); Console.WriteLine ("Position Latitude: {0}", position.Latitude); Console.WriteLine ("Position Longitude: {0}", position.Longitude); location = string.Format ("{0},{1}", position.Latitude, position.Longitude); locationText.Text = location; } catch (Exception e) { Console.WriteLine ("Position Exception: {0}", e.Message); } }
private void Setup() { if (_geolocator != null) return; _geolocator = new Geolocator {DesiredAccuracy = 10}; _geolocator.PositionError += OnListeningError; _geolocator.PositionChanged += OnPositionChanged; }