/// <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) { //Wait for the data to be loaded from the HSL webservice try { await App.VehicleViewModel.LoadVehicleDetails(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } //Get the geolocation of the phone to display in the map Geolocator geolocator = new Geolocator(); Geoposition geoposition = null; try { geoposition = await geolocator.GetGeopositionAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } hslMapControl.Center = geoposition.Coordinate.Point; hslMapControl.ZoomLevel = 15; InitiateRefreshTimer(); }
private async void ShowMyLocationOnTheMap() { // Get my current location. Geolocator myGeolocator = new Geolocator(); Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(); Geocoordinate myGeocoordinate = myGeoposition.Coordinate; GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate); // Make my current location the center of the Map. this.mapWithMyLocation.Center = myGeoCoordinate; this.mapWithMyLocation.ZoomLevel = 13; // Create a small circle to mark the current location. Ellipse myCircle = new Ellipse(); myCircle.Fill = new SolidColorBrush(Colors.Red); myCircle.Height = 20; myCircle.Width = 20; myCircle.Opacity = 50; // Create a MapOverlay to contain the circle. MapOverlay myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = myCircle; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = myGeoCoordinate; // Create a MapLayer to contain the MapOverlay. MapLayer myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); // Add the MapLayer to the Map. mapWithMyLocation.Layers.Add(myLocationLayer); txTop.Text = ("My Location - Lat " + myGeoCoordinate.Latitude.ToString("0.0000") + " Lon " + myGeoCoordinate.Longitude.ToString("0.0000")); }
public async void obtenerposactual() // Metodo que ebtiene la posicion actual del usuario { Geolocator migeolocalizador = new Geolocator(); //Geoposition migeoposicion = await migeolocalizador.GetGeopositionAsync(); Geoposition migeoposicion = null; try { migeoposicion = await migeolocalizador.GetGeopositionAsync(); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the locatiokn master switch is off //feedback.Text = "location is disabled in phone settings."; MessageBox.Show("location is disabled in phone settings."); } else { // something else happened acquring the location //feedback.Text = "Something wrong happened"; MessageBox.Show("Something wrong happened"); } } Geocoordinate migeocoordenada = migeoposicion.Coordinate; GeoCoordinate migeoCoordenada = convertidirGeocoordinate(migeocoordenada); dibujaru(migeoCoordenada); mimapa.Center = migeoCoordenada; mimapa.ZoomLevel =11; cargarlista(); }
private async void GetCoordinates() { // Get the phone's current location. Geolocator MyGeolocator = new Geolocator(); MyGeolocator.DesiredAccuracyInMeters = 5; Geoposition MyGeoPosition = null; try { MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); MyCoordinates.Add(new GeoCoordinate(MyGeoPosition.Coordinate.Latitude, MyGeoPosition.Coordinate.Longitude)); Debug.WriteLine(MyGeoPosition.Coordinate.Latitude + " " + MyGeoPosition.Coordinate.Longitude); Mygeocodequery = new GeocodeQuery(); Mygeocodequery.SearchTerm = "Hanoi, VN"; Mygeocodequery.GeoCoordinate = new GeoCoordinate(MyGeoPosition.Coordinate.Latitude, MyGeoPosition.Coordinate.Longitude); Mygeocodequery.QueryCompleted += Mygeocodequery_QueryCompleted; Mygeocodequery.QueryAsync(); } catch (UnauthorizedAccessException) { MessageBox.Show("Location is disabled in phone settings or capabilities are not checked."); } catch (Exception ex) { // Something else happened while acquiring the location. MessageBox.Show(ex.Message); } }
private async void GetMyMapLocationAsync() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); Map.Center = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); Map.ZoomLevel = ZoomLevel; myGeoCoordinate = geoposition.Coordinate.ToGeoCoordinate(); myMapOverlay.GeoCoordinate = myGeoCoordinate; myMapOverlay.Content = new Pushpin() {Content = "You"}; CalculateDistanceBetweenMeAndUser(); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off Debug.WriteLine("Geoposition not allowed or hadrware disabled"); } //else { // something else happened acquring the location Debug.WriteLine("Geoposition is not available. Failure."); } } }
public async Task <Windows.Devices.Geolocation.Geocoordinate> GetSinglePositionAsync() { Windows.Devices.Geolocation.Geolocator geolocator = new Windows.Devices.Geolocation.Geolocator(); Windows.Devices.Geolocation.Geoposition geoposition = await geolocator.GetGeopositionAsync(); return(geoposition.Coordinate); }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // Allow saved page state to override the initial item to display if (pageState != null && pageState.ContainsKey("SelectedItem")) { navigationParameter = pageState["SelectedItem"]; } Geolocator locator = new Geolocator(); Geoposition geoPos = await locator.GetGeopositionAsync(); Geocoordinate geoCoord = geoPos.Coordinate; String YWSID = "Bi9Fsbfon92vmD4DkkO4Fg"; String url; if (navigationParameter != "") { url = "http://api.yelp.com/business_review_search?term=food&location=" + navigationParameter + "&ywsid=" + YWSID; } else { url = "http://api.yelp.com/business_review_search?term=food&lat=" + geoCoord.Latitude + "&long=" + geoCoord.Longitude + "&ywsid=" + YWSID; } var httpClient = new HttpClient(); String content = await httpClient.GetStringAsync(url); response = JsonObject.Parse(content); this.Frame.Navigate(typeof(MainPage),response); }
private async void ShowMyLocationOnTheMap() { Geolocator myGeolocator = new Geolocator(); Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(); Geocoordinate myGeocoordinate = myGeoposition.Coordinate; GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate); this.BettingMap.Center = myGeoCoordinate; this.BettingMap.ZoomLevel = 15; Ellipse myCircle = new Ellipse(); myCircle.Fill = new SolidColorBrush(Colors.Blue); myCircle.Height = 20; myCircle.Width = 20; myCircle.Opacity = 50; MapOverlay myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = myCircle; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = myGeoCoordinate; MapLayer myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); BettingMap.Layers.Add(myLocationLayer); }
public async void getLocationAddress() { Geolocator geolocator = new Geolocator(); Geoposition currentPosition = await geolocator.GetGeopositionAsync(); string address = "pretoria"; MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync( address, currentPosition.Coordinate.Point, 5); if (result.Status == MapLocationFinderStatus.Success) { List<string> locations = new List<string>(); foreach (MapLocation mapLocation in result.Locations) { // create a display string of the map location string display = mapLocation.Address.StreetNumber + " " + mapLocation.Address.Street + Environment.NewLine + mapLocation.Address.Town + ", " + mapLocation.Address.RegionCode + " " + mapLocation.Address.PostCode + Environment.NewLine + mapLocation.Address.CountryCode; // Add the display string to the location list. locations.Add(display); address = display; lstView.Items.Add("location " + display); } } }
public async Task<LocationResult> GetCurrentPosition() { try { var geolocator = new Geolocator() { DesiredAccuracyInMeters = 500 }; Geoposition pos = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); return new LocationResult(new GeoCoordinate(pos.Coordinate.Latitude, pos.Coordinate.Longitude)); } catch (UnauthorizedAccessException) { return new LocationResult("Die aktuelle Position ist zur Berechnung der Distanz zur Messstation notwendig, Zugriff wurde verweigert."); } catch (Exception) { } return new LocationResult("Aktuelle Position konnte nicht ermittelt werden"); }
private void Context_LocationUpdate(object sender, ViewModels.Events.LocationUpdateEventArgs e) { var ui = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, new Windows.UI.Core.DispatchedHandler(async () => { if (Context.EnableLocate) { var accessStatus = await Geolocator.RequestAccessAsync(); if (accessStatus == GeolocationAccessStatus.Allowed) { try { var _geolocator = new Geolocator(); var pos = await _geolocator.GetGeopositionAsync(); if ((_geolocator.LocationStatus != PositionStatus.NoData) && (_geolocator.LocationStatus != PositionStatus.NotAvailable) && (_geolocator.LocationStatus != PositionStatus.Disabled)) await CalcPosition(pos, Context.cities); else { FailtoPos(); } } catch (Exception) { FailtoPos(); } } else { DeniePos(); } } CityPanel.Navigate(typeof(CitiesSetting), Context.cities); })); }
async void ZoomMap() { var geoloc = new Geolocator(); resultsMap.Center = (await geoloc.GetGeopositionAsync()).Coordinate.Point; resultsMap.ZoomLevel = 15; }
//view your location //get geopostion public async Task<Geoposition> GetGeoPosition() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; Geoposition position = await geolocator.GetGeopositionAsync(); return position; }
/// <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 override async void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. Geolocator geolocator = new Geolocator(); var geo = await geolocator.GetGeopositionAsync(); MapControl1.ZoomLevel = 16; MapControl1.Center = new Geopoint(new BasicGeoposition() { Latitude = geo.Coordinate.Latitude, Longitude = geo.Coordinate.Longitude }); List<Locations> locations = await locationsController.GetLocations(); PopulateMap(locations); AddMapIcon(geo); }
private async void GetGpsLocation() { // Get the location try { // Get the point Geolocator m_geoLocator = new Geolocator(); await Geolocator.RequestAccessAsync(); Geoposition position = await m_geoLocator.GetGeopositionAsync(); // Get the address MapLocationFinderResult mapLocationFinderResult = await MapLocationFinder.FindLocationsAtAsync(position.Coordinate.Point); if (mapLocationFinderResult.Status != MapLocationFinderStatus.Success) { throw new Exception(); } WeatherSettings.Location loc = new WeatherSettings.Location { City = mapLocationFinderResult.Locations[0].Address.Town, State = mapLocationFinderResult.Locations[0].Address.Region }; m_settings.CurrentLocation = loc; ui_locationText.Text = "Your Location: " + mapLocationFinderResult.Locations[0].Address.Town; // Send the location to the pie await SendNewSettings(m_settings); } catch(Exception) { ui_locationText.Text = "Failed to get your location!"; } }
/// <summary> /// Initializes the map. /// </summary> private async void InitializeMap() { _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High) { MovementThreshold = 10 }; _watcher.PositionChanged += this.OnPositionChanged; _watcher.Start(); var geoLocator = new Geolocator { DesiredAccuracyInMeters = 10 }; try { Geoposition geoposition = await geoLocator.GetGeopositionAsync(TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(10)); var coordinate = geoposition.Coordinate; var currentLocation = new GeoCoordinate( coordinate.Latitude, coordinate.Longitude, coordinate.Altitude ?? double.NaN, coordinate.Accuracy, coordinate.AltitudeAccuracy ?? double.NaN, coordinate.Speed ?? double.NaN, coordinate.Heading ?? double.NaN); Pushpin pushpin = (Pushpin)this.FindName("UserLocation"); pushpin.GeoCoordinate = currentLocation; } catch (Exception) { // Inform the user that the location cannot be determined. App.ViewModel.CurrentLocation = null; } }
private async void findMe() { Windows.Devices.Geolocation.Geolocator geolocator = new Windows.Devices.Geolocation.Geolocator(); Windows.Devices.Geolocation.Geoposition geoposition = await geolocator.GetGeopositionAsync(); myMap.SetView(new Bing.Maps.Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude }, 13); Bing.Maps.MapLayer.SetPosition(pin, new Bing.Maps.Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude }); myMap.SetView(new Bing.Maps.Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude }); myMap.Children.Clear(); myMap.ShapeLayers.Clear(); Bing.Maps.MapLayer.SetPosition(pin, new Bing.Maps.Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude }); myMap.Children.Add(pin); sourseLocation = new Bing.Maps.Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude }; }
public async Task<Position> GetLocation() { if (!Settings.AskedForPermission) { var asyncResult = Guide.BeginShowMessageBox("May I get your location from GPS?", "This application uses your location (GPS) to get the most accurate weather reading", new[] { "Allow", "Deny" }, 0, MessageBoxIcon.Alert, null, null); var allowed = await Task.Factory.FromAsync(asyncResult, r => Guide.EndShowMessageBox(r)); Settings.AskedForPermission = true; Settings.AllowGPS = (allowed.Value != 1); } if (!Settings.AllowGPS) return defaultPosition; var geolocator = new Geolocator { DesiredAccuracyInMeters = 50 }; var result = new Position(); try { Geoposition geoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(10)); result.Lat = geoposition.Coordinate.Latitude; result.Long = geoposition.Coordinate.Longitude; } catch (Exception ex) { return defaultPosition; } return result; }
public static async Task<List<WeatherDataModel>> GetWeatherData() { Geolocator geolocator = new Geolocator(); Geoposition geoposition = null; geoposition = await geolocator.GetGeopositionAsync(); var points = geoposition.Coordinate.Point; var lati = geoposition.Coordinate.Point.Position.Latitude; var la = lati.GetType(); var longi = geoposition.Coordinate.Point.Position.Longitude; var lo = longi.GetType(); string url = "http://api.openweathermap.org/data/2.5/weather?lat="+lati+"&lon="+longi; //List<WeatherDataModel> cricketDataModel = new List<WeatherDataModel>(); var httpClient = new HttpClient(new HttpClientHandler()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); List<WeatherDataModel> dataModel=null; var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); string obj = "[" + responseString + "]"; dataModel = JsonConvert.DeserializeObject<List<WeatherDataModel>>(obj); } return dataModel; }
public static async Task<Geoposition> GetGeoPosition() { 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 _position = await geolocator.GetGeopositionAsync().AsTask(token); break; case GeolocationAccessStatus.Denied: break; case GeolocationAccessStatus.Unspecified: break; } } catch (TaskCanceledException) { } catch (Exception) { } finally { _cts = null; } return _position; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Status.Text = "Status: " + "App started"; //compass var compass = Windows.Devices.Sensors.Compass.GetDefault(); compass.ReportInterval = 10; //compass.ReadingChanged += compass_ReadingChanged; Status.Text = "Status: " + "Compass started"; //geo var gloc = new Geolocator(); gloc.GetGeopositionAsync(); gloc.ReportInterval = 60000; gloc.PositionChanged += gloc_PositionChanged; Status.Text = "Status: " + "Geo started"; //Accelerometer var aclom = Accelerometer.GetDefault(); aclom.ReportInterval = 1; aclom.ReadingChanged += aclom_ReadingChanged; //foursquare await GetEstablishmentsfromWed(); //camera var mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); CaptureElement.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); Status.Text = "Status: " + "Camera feed running"; }
public static async Task GetPosition(PositionAccuracy accuracy, int timeout) { if (App.Settings.LocationServiceEnabled) { var geolocater = new Geolocator { DesiredAccuracy = accuracy }; try { var geoposition = await geolocater.GetGeopositionAsync(TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(timeout) ); App.ViewModel.CurrentPosition = new Position { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude, Accuracy = geoposition.Coordinate.Accuracy, Timestamp = geoposition.Coordinate.Timestamp.DateTime }; } catch (TimeoutException ex) { BugSenseHandler.Instance.LogException(ex); } catch (Exception ex) { MessageBox.Show(AppResources.ErrorLocationTitle, AppResources.ErrorTitle, MessageBoxButton.OK); } } }
public async override Task<Location> GetLocation() { var ret = new Location(); // create the locator Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); // THIS IS THE ONLY DIFFERENCE ret.Latitude = geoposition.Coordinate.Point.Position.Latitude; ret.Longitude = geoposition.Coordinate.Point.Position.Longitude; } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off } else { // something else happened acquring the location } } // return the location return ret; }
/// <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) { Geopoint myPoint; if (e.Parameter == null) { //Add isViewing = false; var locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; // MUST ENABLE THE LOCATION CAPABILITY!! var position = await locator.GetGeopositionAsync(); myPoint = position.Coordinate.Point; } else { //View or Delete isViewing = true; lifeThread = (LifeThread)e.Parameter; titleTextBox.Text = lifeThread.Title; noteTextBox.Text = lifeThread.Thread; addButton.Content = "Delete"; var myPosition = new Windows.Devices.Geolocation.BasicGeoposition(); myPosition.Latitude = lifeThread.Latitude; myPosition.Longitude = lifeThread.Longitude; myPoint = new Geopoint(myPosition); } await MyMap.TrySetViewAsync(myPoint, 16d); }
private async void PegaLocal () { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); dLatitude = geoposition.Coordinate.Latitude; dLongetude = geoposition.Coordinate.Longitude; } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off dLatitude = 0; dLongetude = 0; } //else { // something else happened acquring the location } } }
public static async void GetGeolocation() { bool launchLocationSettings = false; GeoLocation = new Geolocator(); // Desired Accuracy needs to be set // before polling for desired accuracy. GeoLocation.DesiredAccuracyInMeters = 50; GeoLocation.MovementThreshold = 5; GeoLocation.ReportInterval = 500; try { // Carry out the operation Geoposition pos = GeoPosition = await GeoLocation.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10)); } catch { /*Operation aborted Your App does not have permission to access location data. Make sure you have defined ID_CAP_LOCATION in the application manifest and that on your phone, you have turned on location by checking Settings > Location.*/ //if the location service is turned off then you can take the user to the location setting with the below code launchLocationSettings = true; } if (launchLocationSettings) { await Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); launchLocationSettings = false; } }
public async Task<Geoposition> HandeleAccessStatus(GeolocationAccessStatus accessStatus) { Geoposition geoposition = null; var message = ""; switch (accessStatus) { case GeolocationAccessStatus.Allowed: Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 1000 }; geoposition = await geolocator.GetGeopositionAsync(); break; case GeolocationAccessStatus.Denied: message = "Access to location is denied!"; break; case GeolocationAccessStatus.Unspecified: message = "Unspecified error!"; break; } if (message != "") { this.notificator.ShowErrorToastWithDismissButton(message); } return geoposition; }
private async void GetCoordinates() { Geolocator MyGeolocator = new Geolocator(); MyGeolocator.DesiredAccuracyInMeters = 5; Geoposition MyGeoPosition = null; try { MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); currentGeoCoordinate = ConvertGeocoordinate(MyGeoPosition.Coordinate); myMap.Center = currentGeoCoordinate; myMap.ZoomLevel = 15; if (!comeinGeoCoordinate.IsUnknown) { List<GeoCoordinate> geoCoordinates = new List<GeoCoordinate>(); geoCoordinates.Add(currentGeoCoordinate); geoCoordinates.Add(comeinGeoCoordinate); RouteQuery routeQuery = new RouteQuery(); routeQuery.Waypoints = geoCoordinates; routeQuery.QueryCompleted += routeQuery_QueryCompleted; routeQuery.QueryAsync(); } } catch (UnauthorizedAccessException) { MessageBox.Show("Location is disabled in phone settings"); } catch (Exception ex) { } }
public async Task<LocationResult> GetCurrentPosition() { try { if (!CheckConsentAskIfNotSet()) { return new LocationResult("No consent for location"); } var geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; Geoposition pos = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(1), timeout: TimeSpan.FromSeconds(10) ); return new LocationResult(pos); } catch (UnauthorizedAccessException) { // We were not allowed the proper right for geolocation return new LocationResult("Location turned off / denied"); } catch (Exception) { } return new LocationResult("Location could not be obtained"); }
/// <summary> /// This gets the last known location or gets a new one if the last one has expired. /// </summary> /// <param name="forceUpdate">Force updates even if the location has not expired.</param> /// <returns>The last good location.</returns> public static async Task<Geoposition> GetLocation(bool forceUpdate = false) { if (GetConfirmation()) { var geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.High; try { if (CachedLocation == null || forceUpdate || lastUpdateTime - DateTime.Now < TimeSpan.FromMinutes(5)) { CachedLocation = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(10)); } return CachedLocation; } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { MessageBox.Show("Location is disabled in phone settings."); } else { return null; } } } return null; }
private async void ShowMyLocationOnTheMap() { Geolocator myGeolocator = new Geolocator(); Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(); Geocoordinate myGeocoordinate = myGeoposition.Coordinate; GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate); // Make my current location the center of the Map. this.mapWithMyLocation.Center = myGeoCoordinate; this.mapWithMyLocation.ZoomLevel = 13; // Create a small circle to mark the current location. BitmapImage bmi = new BitmapImage(new Uri("/Assets/pushpinRood.png", UriKind.Relative)); Image img = new Image(); img.Source = bmi; // Create a MapOverlay to contain the circle. MapOverlay myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = img; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = myGeoCoordinate; // Create a MapLayer to contain the MapOverlay. MapLayer myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); // Add the MapLayer to the Map. mapWithMyLocation.Layers.Add(myLocationLayer); }
/// <summary> /// Centers the map on current location at application launch. /// Subsequently only makes the map visible. /// </summary> /// <param name="sender">This page</param> /// <param name="e">Event arguments</param> private async void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e) { // Make Map visible again after returning from about page. Map.Visibility = Visibility.Visible; if (geoLocator == null) { geoLocator = new Geolocator(); try { Geoposition pos = await geoLocator.GetGeopositionAsync(); if (pos != null && pos.Coordinate != null) { Map.SetView(new GeoCoordinate(pos.Coordinate.Latitude, pos.Coordinate.Longitude), 10); GetNearbyArtists(); } } catch (Exception /*ex*/) { // Couldn't get current location. Location may be disabled. MessageBox.Show("Current location cannot be obtained. It is " + "recommended that location service is turned " + "on in phone settings when using Bands Around.\n" + "\nNow centering on London."); Map.Center = new GeoCoordinate(51.51, -0.12); Map.SetView(new GeoCoordinate(51.51, -0.12), 10); GetNearbyArtists(); } } }
async static void InitialPosition(Sensor sensor) { try { var geopos = await sensor.GetGeopositionAsync(); position = geopos.Coordinate; } catch { } }
/// <summary> /// Initialize Geolocation and get position /// </summary> private async void InitializeGeolocation() { try { var locator = new Windows.Devices.Geolocation.Geolocator(); locator.DesiredAccuracy = PositionAccuracy.High; locator.DesiredAccuracyInMeters = 10; var task = locator.GetGeopositionAsync(); while (task.Status == Windows.Foundation.AsyncStatus.Started) { await Task.Delay(300); } Geoposition position = null; if (task.Status == Windows.Foundation.AsyncStatus.Completed) { position = task.GetResults(); } else { StatusLbl.Text = task.Status.ToString(); if (task.Status == Windows.Foundation.AsyncStatus.Error) { StatusLbl.Text = StatusLbl.Text + ": " + task.ErrorCode.Message; } return; } StatusLbl.Text = LocRM.GetString("Status") + ": " + locator.LocationStatus.ToString(); if (position != null) { StatusLbl.Text += " [" + position.Coordinate.PositionSource.ToString() + "]"; AccuracyLbl.Text = LocRM.GetString("GeolocationAccuracy") + ": " + position.Coordinate.Accuracy.ToString(); LatitudeLbl.Text = LocRM.GetString("GeolocationLatitude") + ": " + position.Coordinate.Point.Position.Latitude.ToString(); LongitudeLbl.Text = LocRM.GetString("GeolocationLongitude") + ": " + position.Coordinate.Point.Position.Longitude.ToString(); } } catch (Exception e) { Log.LogError(e.ToString()); AccuracyLbl.Text = LocRM.GetString("Error"); } }
public async Task <GeoLocation> FindAsync() { if (locator.LocationStatus == PositionStatus.Disabled || locator.LocationStatus == PositionStatus.NotAvailable) { return(null); } try { var location = await locator.GetGeopositionAsync(); return(new GeoLocation { Altitude = location.Coordinate.Point.Position.Altitude, Latitude = location.Coordinate.Point.Position.Latitude, Longitude = location.Coordinate.Point.Position.Longitude, }); } catch (UnauthorizedAccessException) { return(null); } }
/// <summary> /// get position as an asynchronous operation. /// </summary> /// <param name="timeout">The timeout.</param> /// <returns>Task<Position>.</returns> public async Task <Position> GetPositionAsync(int timeout) { var position = await _locator.GetGeopositionAsync(TimeSpan.MaxValue, TimeSpan.FromMilliseconds(timeout)); return(position.Coordinate.GetPosition()); }