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; }
/// <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 void WriteGeolocToAppData( Geoposition pos ) { var settings = ApplicationData.Current.LocalSettings; settings.Values[ "Latitude" ] = pos.Coordinate.Point.Position.Latitude.ToString(); settings.Values[ "Longitude" ] = pos.Coordinate.Point.Position.Longitude.ToString(); settings.Values[ "Accuracy" ] = pos.Coordinate.Accuracy.ToString(); }
public async void getOwnLocation() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); AfterGetLocationEvent(); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off //StatusTextBlock.Text = "location is disabled in phone settings."; } //else { // something else happened acquring the location } } }
/// <summary> /// Single location request /// </summary> /// <returns></returns> public async Task GetGeoLocation() { try { // Get cancellation token _cts = new CancellationTokenSource(); CancellationToken token = _cts.Token; // Get position currentPosition = await _geolocator.GetGeopositionAsync().AsTask(token); longitude = currentPosition.Coordinate.Longitude.ToString(); latitude = currentPosition.Coordinate.Latitude.ToString(); } catch (System.UnauthorizedAccessException e) { errorMessage = e.Message; } catch(TaskCanceledException e) { errorMessage = e.Message; } finally { _cts = null; } }
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); }
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 }; }
private async Task<string> GetCurrentCityAsync() { this.position = await locator.GetGeopositionAsync(); string city = this.position.CivicAddress.City; return city; }
/// <summary> /// Add geometory information to given image as Exif data. /// </summary> /// <param name="image">Raw data of Jpeg file</param> /// <param name="position">Geometory information</param> /// <param name="overwrite">In case geotag is already exists, it throws GpsInformationAlreadyExistsException by default. /// To overwrite current one, set true here.</param> /// <returns>Jpeg data with geometory information.</returns> public static byte[] AddGeoposition(byte[] image, Geoposition position, bool overwrite = false) { #if WINDOWS_APP Debug.WriteLine("Longitude : " + position.Coordinate.Point.Position.Longitude + " Latitude: " + position.Coordinate.Point.Position.Latitude); #elif WINDOWS_PHONE Debug.WriteLine("Longitude : " + position.Coordinate.Longitude + " Latitude: " + position.Coordinate.Latitude); #endif // parse given image first var exif = JpegMetaDataParser.ParseImage(image); if (!overwrite && exif.IsGeotagExist) { Debug.WriteLine("This image contains GPS information."); throw new GpsInformationAlreadyExistsException("This image contains GPS information."); } exif = RemoveGeoinfo(exif); // Create IFD structure from given GPS info var gpsIfdData = GpsIfdDataCreator.CreateGpsIfdData(position); // Add GPS info to exif structure exif.GpsIfd = gpsIfdData; return JpegMetaDataProcessor.SetMetaData(image, exif); }
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { if (!isTracking) return; else lastKnownPosition = args.Position; }
async public Task WriteGeolocToAppData(Geoposition pos) { var settings = ApplicationData.Current.LocalSettings; settings.Values["Latitude"] = pos.Coordinate.Point.Position.Latitude.ToString(); settings.Values["Longitude"] = pos.Coordinate.Point.Position.Longitude.ToString(); settings.Values["Accuracy"] = pos.Coordinate.Accuracy.ToString(); await Jeedom.RequestViewModel.Instance.SendPosition(pos.Coordinate.Point.Position.Latitude.ToString().Replace(',', '.') + ',' + pos.Coordinate.Point.Position.Longitude.ToString().Replace(',', '.')); double HomeMobile = 0; var HomeObjectId = settings.Values["HomeObjectId"]; if (HomeObjectId != null) { foreach (Jeedom.Model.Command Commande in Jeedom.RequestViewModel.Instance.CommandList.Where(w => w.id.Equals(HomeObjectId))) { var coordonee = Commande.Value.Split(','); HomeMobile = Math.Round(Distance(Convert.ToDouble(coordonee[0].Replace('.', ',')), Convert.ToDouble(coordonee[1].Replace('.', ',')), pos.Coordinate.Point.Position.Latitude, pos.Coordinate.Point.Position.Longitude, 'K'), 2); } } if (config.GeoFenceActivation && Convert.ToDouble(config.GeoFenceActivationDistance) >= HomeMobile) { RegisterGeoFence(); } else { UnregisterGeoFence(); } }
/// <summary> /// Write the location metadata to the image file /// </summary> public async static Task WriteSurveyPhotoMetaData(StorageFile file, Geoposition pos, string surveyId = "") { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(stream); var encoder = await BitmapEncoder.CreateForTranscodingAsync(stream, decoder); // Write the gps data var propertySet = new BitmapPropertySet(); var latitudeNumerator = new BitmapTypedValue(CoordDoubleToIntArray(pos.Coordinate.Latitude), PropertyType.Int32Array); var latitudeRef = new BitmapTypedValue("N", PropertyType.String); var longitudeNumerator = new BitmapTypedValue(CoordDoubleToIntArray(pos.Coordinate.Longitude), PropertyType.Int32Array); var longitudeRef = new BitmapTypedValue("W", PropertyType.String); propertySet.Add("System.GPS.LatitudeNumerator", latitudeNumerator); propertySet.Add("System.GPS.LatitudeRef", latitudeRef); propertySet.Add("System.GPS.LatitudeDenominator", new BitmapTypedValue(new [] { 1, 1, 10000 }, PropertyType.Int32Array)); propertySet.Add("System.GPS.LongitudeNumerator", longitudeNumerator); propertySet.Add("System.GPS.LongitudeRef", longitudeRef); propertySet.Add("System.GPS.LongitudeDenominator", new BitmapTypedValue(new[] { 1, 1, 10000 }, PropertyType.Int32Array)); // Write the surveyId data if (!string.IsNullOrEmpty(surveyId)) { var surveyIdTyped = new BitmapTypedValue(surveyId, Windows.Foundation.PropertyType.String); propertySet.Add("System.Comment", surveyIdTyped); } await encoder.BitmapProperties.SetPropertiesAsync(propertySet); await encoder.FlushAsync(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { comboplaces.ItemsSource = loctypes; gp = await gl.GetGeopositionAsync(); l1 = new Location(); l1.Latitude = gp.Coordinate.Point.Position.Latitude; l1.Longitude = gp.Coordinate.Point.Position.Longitude; map1.SetView(l1, 15); MapLayer.SetPosition(pp1, l1); //if(session.Values["page"] !=null) //{ // Frame.Navigate(typeof(MainPage)); //} //localsettings.Values["sessionsettings"] = task27_10_15.App.LoadComponent(this, System.Uri(task27-10-15\BlankPage1.xaml)); ////localsettings.Values["sessionsetting"] = "task27-10-15"; MainPage m = new MainPage(); //Object value = localsettings.Values["sessionsetting"]; //Windows.Storage.ApplicationData.Current.LocalSettings.Values["MainPage"] = sessionsettings; //string sessionsettings = Windows.Storage.ApplicationData.Current.LocalSettings.Values[""]; // StorageFile sf = await ApplicationData.Current.LocalSettings.Values[MainPage]; }
private static async Task<bool> Initialize() { bool initializedSuccessfully = false; accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location); try { if (geolocator == null) { geolocator = new Geolocator(); } // Get cancellation token cts = new CancellationTokenSource(); CancellationToken token = cts.Token; currentLocation = await geolocator.GetGeopositionAsync().AsTask(token); // other initialization for your app could go here accessInfo.AccessChanged += OnAccessChanged; GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged; initializedSuccessfully = true; } catch (UnauthorizedAccessException) { if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus) { MessageBox.Show("Location has been disabled by the user. Enable access through the settings charm."); } else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus) { MessageBox.Show("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel."); } else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus) { MessageBox.Show("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm."); } } catch (TaskCanceledException) { // task cancelled } catch (Exception) { if (geolocator.LocationStatus == PositionStatus.Disabled) { // On Windows Phone, this exception will be thrown when you call // GetGeopositionAsync if the user has disabled locaton in Settings. MessageBox.Show("Location has been disabled in Settings."); } } finally { cts = null; } return initializedSuccessfully; }
/// <summary> /// Add geometory information to given image as Exif data asynchronously. /// </summary> /// <param name="image">Raw data of Jpeg file as a stream. /// Given stream will be disposed after adding location info.</param> /// <param name="position">Geometory information</param> /// /// <param name="overwrite">In case geotag is already exists, it throws GpsInformationAlreadyExistsException by default. /// To overwrite current one, set true here.</param> /// <returns>Jpeg data with geometory information.</returns> public static async Task<Stream> AddGeopositionAsync(Stream image, Geoposition position, bool overwrite = false) { // It seems thrown exceptions will be raised by this "async" ... return await Task<Stream>.Run(async () => { return AddGeoposition(image, position, overwrite); }).ConfigureAwait(false); }
async void watcher_PositionChanged(Geolocator sender, PositionChangedEventArgs e) { lastPosition = await sender.GetGeopositionAsync(); if (lastPosition != null && lastPosition.Coordinate.AltitudeAccuracy.HasValue) { getLocationListener().locationUpdated(convert(lastPosition)); } }
/// <summary> /// All-encompassing constructor /// </summary> /// <param name="dateTimeParameter"></param> /// <param name="details"></param> /// <param name="Position"></param> public TaskItem(DateTime dateTimeParameter, string details, Geoposition Position) { this.dateTime = dateTimeParameter; this.Details = details; createUniqueIdentity(); }
private void My_OnLocationChange(Windows.Devices.Geolocation.Geoposition obj) { var msg = BuddyRunInfo.FromGeoposition(obj, DateTime.UtcNow); msg.SourceUserId = eBuddyApp.Services.Azure.MobileService.Instance.UserData.FacebookId; msg.DestUserId = "sid:af7d6ae6d4abbcb585bc46ab45d42c05"; //todo change to real usrid RunnersHubProxy.Invoke("SendLocation", msg); }
public static GeoLocation GetLocationFromDeviceGeoPositionObject(Geoposition location) { return location.Coordinate == null ? new GeoLocation() : new GeoLocation() { Latitude = location.Coordinate == null ? -12 : location.Coordinate.Latitude, Longitude = location.Coordinate == null? -24 : location.Coordinate.Longitude, City = location.CivicAddress ==null ? "":location.CivicAddress.City }; }
public static DeviceLocationModel GetLocationModel(Geoposition Position) { return Position != null ? new DeviceLocationModel { Latitude = Position.Coordinate.Latitude, Longitude = Position.Coordinate.Longitude, City = string.Empty, Country = string.Empty } : null; }
private async Task<Point> GetCurrentPositionAsync() { Point currentCoordinates = new Point(); this.position = await locator.GetGeopositionAsync(); currentCoordinates.Latitude = this.position.Coordinate.Latitude; currentCoordinates.Longitude = this.position.Coordinate.Longitude; return currentCoordinates; }
/// <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) { geoposition = await geolocator.GetGeopositionAsync(); MapControl1.Center = geoposition.Coordinate.Point; MapControl1.ZoomLevel = 18; // zoom level ReverseGeocode(); }
private static LocationData ConvertPositionData(Geoposition position) { var latitude = position.Coordinate.Latitude; var longtitude = position.Coordinate.Longitude; var heading = position.Coordinate.Heading; var accuracy = position.Coordinate.Accuracy; var timestamp = position.Coordinate.Timestamp; return new LocationData(latitude, longtitude, heading ?? 0, accuracy, timestamp.LocalDateTime); }
private async void Location(object sender, RoutedEventArgs e) { Message = "Error"; Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 10; geoposition = await geolocator.GetGeopositionAsync(); Message = String.Format("lat= {0}; lon= {1}", geoposition.Coordinate.Point.Position.Latitude, geoposition.Coordinate.Point.Position.Longitude); PropertyChanged(this, new PropertyChangedEventArgs("Message")); result.Visibility = Visibility.Visible; }
async Task<MapLocationFinderResult> GetAddressFromCoordinatesAsync(Geoposition geoposition) { var mapLocationFinderResult = await MapLocationFinder.FindLocationsAtAsync(geoposition.Coordinate.Point); if (mapLocationFinderResult.Status == MapLocationFinderStatus.Success) { // hard-coding to only view the first returned possible address ([0]). You might get more than one result, in which case check them against your requirements. return mapLocationFinderResult; //.Locations[0].Address.Region + " " + // mapLocationFinderResult.Locations[0].Address.Country; } return null; }
private async void AddMapIcon(Geoposition geo) { MapIcon MapIcon1 = new MapIcon(); MapIcon1.Location = new Geopoint(new BasicGeoposition() { Latitude = geo.Coordinate.Latitude, Longitude = geo.Coordinate.Longitude }); MapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0); MapIcon1.Title = "My Position"; MapControl1.MapElements.Add(MapIcon1); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var accessStatus = await Geolocator.RequestAccessAsync(); if(accessStatus == GeolocationAccessStatus.Allowed) { Geolocator geolocator = new Geolocator { }; currentLocation = await geolocator.GetGeopositionAsync(); } MapView.Visibility = Visibility.Collapsed; MyMap.Visibility = Visibility.Collapsed; await StartCamera(); UpdateARView(); }
void PositionChanged_Locator(Geolocator sender, PositionChangedEventArgs args) { try { m_lastKnownPosition = args.Position; Services.App.Async_Invoke( AsyncGroup.LocatorService_UpdateMyPosition, LocatorService_UpdateMyPosition ); } catch (Exception exc) { Log.Exception ("Failed to update my position", exc); } }
//Bingmaps API: //Aq5iV1oO3-YjhxwTyGv0W6_hATShyfuhYI2LaJqak7a4UjTfC9zMv5YLTW7eMiFc public MapController() { //Creating the Bing maps bingMap = new Map(); bingMap.Credentials = "Aq5iV1oO3-YjhxwTyGv0W6_hATShyfuhYI2LaJqak7a4UjTfC9zMv5YLTW7eMiFc"; //Set our own GeoLocator geolocator = new Geolocator(); geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High; //For get location; pos = null; this.updateLocation(); //One time get Location. }
async void updateLocationText(Geoposition pos) { HttpClient Client = new HttpClient(); string Result = await Client.GetStringAsync(string.Format("http://nominatim.openstreetmap.org/reverse?format=xml&zoom=18&lat={0}&lon={1}&application={2}", pos.Coordinate.Latitude.ToString(CultureInfo.InvariantCulture), pos.Coordinate.Longitude.ToString(CultureInfo.InvariantCulture), "Clothe")); XDocument ResultDocument = XDocument.Parse(Result); XElement AddressElement = ResultDocument.Root.Element("addressparts"); string road = AddressElement.Element("road").Value; string city = AddressElement.Element("city").Value; txtLocation.Text = String.Format("Using location: {0}, {1}", road, city); }
private void showData(Geoposition position) { LatitudeValue.Text = position.Coordinate.Latitude.ToString(); LongitudeValue.Text = position.Coordinate.Longitude.ToString(); AccuracyValue.Text = position.Coordinate.Accuracy.ToString(); TimestampValue.Text = position.Coordinate.Timestamp.ToString(); if (position.Coordinate.Altitude != null) AltitudeValue.Text = position.Coordinate.Altitude.ToString() + "(+- " + position.Coordinate.AltitudeAccuracy.ToString() + ")"; if (position.Coordinate.Heading != null) HeadingValue.Text = position.Coordinate.Heading.ToString(); if (position.Coordinate.Speed != null) SpeedValue.Text = position.Coordinate.Speed.ToString(); }
private async void UpdateMap(Geoposition position) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Set player icon's position MapControl.SetLocation(PlayerImage, position.Coordinate.Point); // Update angle and center only if map is not being manipulated // TODO: set this to false on gesture if (!_canUpdateMap) return; GameMapControl.Center = position.Coordinate.Point; if (position.Coordinate.Heading != null && !double.IsNaN(position.Coordinate.Heading.Value)) { GameMapControl.Heading = position.Coordinate.Heading.Value; } }); }
/// <summary> /// Get the current position of device /// </summary> private async void GetCurrentLocation() { MyGeolocator = new Geolocator(); MyGeolocator.DesiredAccuracyInMeters = 50; if (MyGeolocator.LocationStatus == PositionStatus.Disabled) { MessageBoxResult result = MessageBox.Show("Would you like to Enable GPS?", "Enable GPS", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { var res = Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); } if (result == MessageBoxResult.Cancel) { MessageBox.Show("Unable to track your location. Make sure your location service is turned ON."); progress.Visibility = Visibility.Collapsed; } } else { try { MyGeoPosition = await MyGeolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); latitude = MyGeoPosition.Coordinate.Latitude; longitude = MyGeoPosition.Coordinate.Longitude; myRouteCoordinates.Add(new GeoCoordinate(latitude, longitude)); myMap.Center = new GeoCoordinate(latitude, longitude); myMap.ZoomLevel = 13; GetDirections(); } catch (Exception) { MessageBox.Show("Sorry. Unable to retrieve your current location."); progress.Visibility = Visibility.Collapsed; } } }
public static Location ToLocation(this Geoposition g) { return(new Location(g.Coordinate.Point.Position.Latitude, g.Coordinate.Point.Position.Longitude)); }