private async Task SetupPin(RideStates state, Geoposition position = null, LatLng latLng = null) { if (position == null && latLng == null) { position = await geolocator.GetGeopositionAsync(); } if (state == RideStates.Pickup) { if (startLocation != null && map.MapElements.Contains(startLocation)) { map.MapElements.Remove(startLocation); } startLocation = new MapIcon(); if (latLng == null) { startLocation.Location = position.Coordinate.Point; } else { SetPinLocation(startLocation, latLng); } startLocation.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible; startLocation.Title = "Pickup location"; map.MapElements.Add(startLocation); } else if (state == RideStates.Dropoff) { RemoveEndLocationPin(); endLocation = new MapIcon(); if (latLng == null) { endLocation.Location = position.Coordinate.Point; } else { SetPinLocation(endLocation, latLng); } endLocation.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible; endLocation.Title = "Dropoff location"; map.MapElements.Add(endLocation); } }
async void getGeoLocation() { this.busyIndicator.IsRunning = true; //Declare and Inizialize a Geolocator object Geolocator geolocator = new Geolocator(); //Set his accuracy level geolocator.DesiredAccuracy = PositionAccuracy.High; //Let's get the position of the user. Since there is the possibility of getting an Exception, this method is called inside a try block try { //The await guarantee the calls to be returned on the thread from which they were called //Since it is call directly from the UI thread, the code is able to access and modify the UI directly when the call returns. currentGeoposition = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10) ); currentLatitude = currentGeoposition.Coordinate.Latitude; currentLongitude = currentGeoposition.Coordinate.Longitude; currentGeoCoordinate = new GeoCoordinate(currentLatitude, currentLongitude); //this.busyIndicator.IsRunning = false; populateStationList(20); } //If an error is catch 2 are the main causes: the first is that you forgot to includ ID_CAP_LOCATION in your app manifest. //The second is that the user doesn't turned on the Location Services catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { showErrorMessage(); this.busyIndicator.IsRunning = false; } //else { // something else happened during the acquisition of the location } } }
private async void getLocationButton_Click(object sender, RoutedEventArgs e) { loading.Visibility = Visibility.Visible; String error = null; try { // Create new instance of Geolocator and define accuracy. // Inorder for geolocator to work you will need to enable 'Locations' inside the // app's manifest file. Look for 'Package.appxmanifest' inside your 'Solution Explorer' // and open it. Locate the 'Capabilities' tab along the top and check the 'Location' box // to enable locations. The user will also need to enable location on their machine from // the 'Privacy' section in settings. Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 100; // Get the Geoposition asynchronously. Geoposition geoposition = await geolocator.GetGeopositionAsync( // Define maximumAge to make sure data is not too old. maximumAge : TimeSpan.FromMinutes(5), // Define timeout to prevent wastage of CPU cycles and battery. timeout : TimeSpan.FromSeconds(10) ); // Get latitude and longitude values (2 dp) as strings. string lat = geoposition.Coordinate.Point.Position.Latitude.ToString("0.00"); string lng = geoposition.Coordinate.Point.Position.Longitude.ToString("0.00"); // Pass geolocation data to the executeWeather method. executeWeather(lat, lng); } catch (Exception ex) { error = ex.Message; } if (error != null) { var messageDialog = new Windows.UI.Popups.MessageDialog("Error: " + error); await messageDialog.ShowAsync(); } loading.Visibility = Visibility.Collapsed; }
private void SetReportingMode(ReportingMode mode) { FSLog.Debug(CurrentMode, "=>", mode); if (Timer == null) { FSLog.Info("Not running"); return; } Timer.Stop(); if (mode == ReportingMode.Reporting) { CreateLocator(accuracyInMeters: 10, movementThreshold: 10, reportInterval: 2000); // Wait for 10 secs to get good position // Location updates checks if new position has better accuracy // and stores it if it does as best position. // When timer triggers, the best position is sent via LocationChanged event Timer.Interval = ReportingDuration; } else { // Destroy high accuracy locator if (Locator != null) { Locator.PositionChanged -= Locator_PositionChanged; Locator = null; } // The time we stay in idle mode Timer.Interval = IdleDuration; BestPosition = null; } CurrentMode = mode; Timer.Start(); }
private async void RefreshLocation() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 100; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromSeconds(60), timeout : TimeSpan.FromSeconds(10) ); var latitude = geoposition.Coordinate.Latitude; var longitude = geoposition.Coordinate.Longitude; var api = new ArgosAPI(); var result = await api.GetStores(longitude, latitude); radListStores.DataContext = result; var settingsHelper = new SettingsHelper(); settingsHelper.SaveStores(result); var currentApp = ((IArgosApp)(App.Current)); currentApp.StoresChanged(); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // todo: say blocked stackNoLocation.Visibility = Visibility.Visible; radListStores.Visibility = Visibility.Collapsed; } else { // something else happened acquring the location } } }
private Geopoint GeopositionToGeoPoint(Geoposition point) { double wgLon = point.Coordinate.Point.Position.Longitude; double wgLat = point.Coordinate.Point.Position.Latitude; double dLat = transformLat(wgLon - 105.0, wgLat - 35.0); double dLon = transformLon(wgLon - 105.0, wgLat - 35.0); double radLat = wgLat / 180.0 * pi; double magic = Math.Sin(radLat); magic = 1 - ee * magic * magic; double sqrtMagic = Math.Sqrt(magic); dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); dLon = (dLon * 180.0) / (a / sqrtMagic * Math.Cos(radLat) * pi); return(new Geopoint(new BasicGeoposition { Latitude = wgLat + dLat + 0.000355, Longitude = wgLon + dLon - 0.000067 })); //加减数仅是因为mapcontrol没有针对中国的火星坐标系进行纠偏,粗略调整 }
private async void Start_GetLocation() { LayoutAdjustment(true); position = await App.GetLocation(this.Dispatcher, true); if (position != null) { coordenadas = "{" + position.Coordinate.Latitude.ToString(CultureInfo.InvariantCulture) + ", " + position.Coordinate.Longitude.ToString(CultureInfo.InvariantCulture) + "}"; bt_Position.Background = new SolidColorBrush(Colors.Green); } SystemTray.ProgressIndicator.IsVisible = false; LayoutAdjustment(false); PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled; }
public async void getCords() { try { Geolocator locator = new Geolocator(); Geoposition position = await locator.GetGeopositionAsync(); Geocoordinate coordinate = position.Coordinate; lll = coordinate.Latitude.ToString(); loo = coordinate.Longitude.ToString(); tbx_latitude.Text = lll; tbx_longitude.Text = loo; RefreshMyList(); } catch (Exception ex) { MessageBox.Show("Check Your Connection please!"); } }
private async Task <Geoposition> getLocation() { Geolocator gl = new Geolocator { DesiredAccuracy = PositionAccuracy.High, MovementThreshold = 10 }; try { Geoposition gp = await gl.GetGeopositionAsync(); return(gp); } catch (Exception e) { message(e.Message, "ERROR!"); return(null); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var id = (string)e.Parameter; var accessStatusTask = Geolocator.RequestAccessAsync().AsTask(); accessStatusTask.Wait(); Geoposition pos = null; if (accessStatusTask.Result == GeolocationAccessStatus.Allowed) { Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 1 }; var task = geolocator.GetGeopositionAsync().AsTask(); task.Wait(); pos = task.Result; } ViewModel = new TravelListDetailViewModel(id, pos); }
private async void UpdateLocationData(Geoposition position) { if (position == null) { Latitude = 0; Longitude = 0; } else { Latitude = position.Coordinate.Point.Position.Latitude; Longitude = position.Coordinate.Point.Position.Longitude; DisplayStatus(string.Format("Update Location Lat {0}, Long {1}, Source {2}", Latitude, Longitude, position.Coordinate.PositionSource.ToString())); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["Latitude"] = Latitude; reportedProperties["Longitude"] = Longitude; reportedProperties["LocationSource"] = position.Coordinate.PositionSource.ToString(); reportedProperties["LocationAccuracy"] = position.Coordinate.Accuracy; await _deviceClient.UpdateReportedPropertiesAsync(reportedProperties); } }
private async Task getCoordinates() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 5; geolocator.MovementThreshold = 5; geolocator.ReportInterval = 500; try { output.Text = "Locating"; pos = await geolocator.GetGeopositionAsync(maximumAge : TimeSpan.FromMinutes(1), timeout : TimeSpan.FromSeconds(5)); // crashes sometimes???? get an idea !!! } catch (Exception ex) { //exception output.Text = "Error Locating"; MessageBox.Show("Error " + ex); } }
/// <summary> /// get location if access is permitted /// </summary> /// <returns></returns> public async Task <string> GetLocation() { string coords = ""; switch (accessStatus) { case GeolocationAccessStatus.Allowed: Geolocator gl = new Geolocator(); gl.DesiredAccuracy = PositionAccuracy.High; Geoposition pos = await gl.GetGeopositionAsync(); coords = pos.Coordinate.Point.Position.Latitude + ", " + pos.Coordinate.Point.Position.Longitude; break; default: coords = "Access to location is denied. Please enable location in your device settings."; break; } return(coords); }
public void DrawPlayer(Geoposition drawLocation) { DeletePlayerFromMapList(_myMap); Color fillColor = Colors.Blue; Color strokeColor = Colors.Black; fillColor.A = 255; strokeColor.A = 255; _playerCircle = new MapPolygon { StrokeThickness = 2, FillColor = fillColor, StrokeColor = strokeColor, Path = new Geopath(CalculateCircle(drawLocation.Coordinate.Point.Position, 10)), ZIndex = 5 }; _myMap.MapElements.Add(_playerCircle); centerMap(drawLocation); }
public async Task <Coordinate> GetLocationAsync(CancellationToken cancellationToken) { if (this.lastPosition == null) { try { this.lastPosition = await geolocator .GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(45)) .AsTask(cancellationToken); } catch (TaskCanceledException) { return(null); } } return(new Coordinate( this.lastPosition.Coordinate.Point.Position.Latitude, this.lastPosition.Coordinate.Point.Position.Longitude)); }
private async void GeolocationPositionUpdated(Geoposition position, GeolocationService.PositionUpdateReasons reason) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { if (position != null) { await CanberraMap.TrySetViewAsync(position.Coordinate.Point, 18); if (_locationPin == null) { _locationPin = new MapIcon(); _locationPin.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/me.png")); // _locationPin.NormalizedAnchorPoint = new Point(0.5, 1.0); _locationPin.ZIndex = 0; CanberraMap.MapElements.Add(_locationPin); } _locationPin.Location = position.Coordinate.Point; } }); }
public void PostSpeedWarning(Geoposition pos) { string location = string.Empty; Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "CoversationMessagesView::PostSpeedWarning", "start")); pos = (Application.Current as App).Currentlocation; if (pos != null) { double speed = pos.Coordinate.Speed.HasValue ? pos.Coordinate.Speed.Value : 0; speed = speed * 2.24; if (speed > 15.0) { MessageBox.Show(string.Format(Strings.DontTextAndDrive, speed)); } } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "CoversationMessagesView::PostSpeedWarning", "end")); }
public async Task setCurrentGeo() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.High; geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1)); latitude = geoposition.Coordinate.Point.Position.Latitude.ToString("0.0000000000"); longitude = geoposition.Coordinate.Point.Position.Longitude.ToString("0.0000000000"); } catch { Geoposition geoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1)); latitude = geoposition.Coordinate.Point.Position.Latitude.ToString("0.0000000000"); longitude = geoposition.Coordinate.Point.Position.Longitude.ToString("0.0000000000"); } }
private async void GeoLocatorHelper_LocationFetched(object sender, Geoposition e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async delegate { var pos = e; if (pos == null || pos.Coordinate == null || pos.Coordinate.Point == null) { return; } BasicGeoposition snPosition = new BasicGeoposition { Latitude = pos.Coordinate.Point.Position.Latitude, Longitude = pos.Coordinate.Point.Position.Longitude }; Geopoint snPoint = new Geopoint(snPosition); await Task.Delay(10); var Map = MapView.MapControl; Map.Center = snPoint; await MapView.MapControl.TryZoomToAsync(16); MapViewVM.UserLocation.Location = snPoint; }); }
async void GdzieJaNaMapie() { Geolocator mojGPS = new Geolocator { DesiredAccuracy = PositionAccuracy.High }; Geoposition mojeZGPS = await mojGPS.GetGeopositionAsync(); double dlg = mojeZGPS.Coordinate.Point.Position.Longitude; double szer = mojeZGPS.Coordinate.Point.Position.Latitude; tbGPS.Text = $"dlg.: {dlg:F4} szer.: {szer:F4}"; BasicGeoposition geoposition = new BasicGeoposition { Latitude = szer, Longitude = dlg }; daneGeograficzne.pktStartowy = geoposition; }
public async Task <GeoPosition> GetLocationAsync() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10) ); if (geoposition == null) { return(null); } this.LastKnowPosition = new GeoPosition(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); return(this.LastKnowPosition); }
public static async Task <string> GetPostalCode() { var geo = new Geolocator(); Geoposition pos = await geo.GetGeopositionAsync().AsTask(); var postCode = pos.CivicAddress.PostalCode ?? string.Empty; if (postCode.Length <= 0 && pos.Coordinate.Latitude != 0) { var reverseRequest = GeocodeServiceHelper.GetReverseRequest(pos.Coordinate.Latitude, pos.Coordinate.Longitude); var client = GeocodeServiceHelper.GetClient(); var geocodeResponse = await Task.Run(() => client.ReverseGeocodeAsync(reverseRequest)); if (geocodeResponse.Results != null) { postCode = geocodeResponse.Results[0].Address.PostalCode; } } return(postCode); }
public void OnPhoneGeopositionReading(PositionChangedEventArgs args) { Geoposition geo = args.Position; double lat = geo.Coordinate.Point.Position.Latitude; double lng = geo.Coordinate.Point.Position.Longitude; DateTimeOffset ts = geo.Coordinate.Timestamp; EventItem latEvent = new EventItem { Stream = StreamsEnum.GeopositionLatitude, Timestamp = ts, Value = lat }; EventItem lngEvent = new EventItem { Stream = StreamsEnum.GeopositionLongitude, Timestamp = ts, Value = lng }; IList <EventItem> events = new[] { latEvent, lngEvent }; //SendToQueue(events); }
private void OnLocationChanged(Geoposition position, bool isForced = false) { if (LocationChanged == null) { return; } if (position == LastPosition) { FSLog.Debug("Skip, position is same as previously"); return; } LastPosition = position; LocationChanged(this, new LocationChangeEventArgs { IsForced = isForced, Position = position }); }
async void GdzieJaNaMapie() { Geolocator mojGPS = new Geolocator { DesiredAccuracy = PositionAccuracy.High }; Geoposition mojeZGPS = await mojGPS.GetGeopositionAsync(); double dlugosc = mojeZGPS.Coordinate.Point.Position.Longitude; double szerokosc = mojeZGPS.Coordinate.Point.Position.Latitude; tbGPS.Text = $"długość: {dlugosc:F4} | szerokość: {szerokosc:F4}"; DaneGeograficzne.pktStartowy = mojeZGPS.Coordinate.Point.Position; DaneGeograficzne.opisCelu = ""; BasicGeoposition geoposition = new BasicGeoposition { Latitude = dlugosc, Longitude = szerokosc }; }
private async void MyLocation_But_Click(object sender, RoutedEventArgs e) { MyLocation_But.IsEnabled = false; map1.MapElements.Clear(); Status_Text.Text = "SCANNING..."; try { Geolocator geolocator = new Geolocator(); Geoposition geoposition = await geolocator.GetGeopositionAsync(); setPositionIcon(MyLocationIcon, geoposition.Coordinate.Point, "ms-appx:///Pic_Sources/MyLocation_Pin.png", "You here"); string search = geoposition.Coordinate.Point.Position.Latitude.ToString() + "," + geoposition.Coordinate.Point.Position.Longitude.ToString(); ShowTraffic(search, geoposition.Coordinate.Point); } catch (UnauthorizedAccessException) { Status_Text.Text = "LOCATION OFF"; } MyLocation_But.IsEnabled = true; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { GeolocationAccessStatus status = await Geolocator.RequestAccessAsync(); if (status == GeolocationAccessStatus.Allowed) { Geolocator geolocator = new Geolocator(); Geoposition position = await geolocator.GetGeopositionAsync(); Map.Center = position.Coordinate.Point; Map.ZoomLevel = 15; Image marker = new Image(); marker.Source = new BitmapImage(new Uri("ms-appx:///Assets/Marker.png", UriKind.Absolute)); marker.Height = 64; Map.Children.Add(marker); MapControl.SetLocation(marker, position.Coordinate.Point); MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 1.0)); } }
private async void FindLocation() { var accessStatus = await Geolocator.RequestAccessAsync(); if (accessStatus == GeolocationAccessStatus.Allowed) { //case GeolocationAccessStatus.Allowed: var geolocator = new Geolocator { DesiredAccuracy = PositionAccuracy.Default }; // Subscribe to the StatusChanged event to get updates of location status changes. //_geolocator.StatusChanged += OnStatusChanged; // Carry out the operation. var pos = await geolocator.GetGeopositionAsync(); mMap.Center = new Geopoint(new BasicGeoposition { Latitude = pos.Coordinate.Point.Position.Latitude, Longitude = pos.Coordinate.Point.Position.Longitude }); mMap.ZoomLevel = 15; userPos.Location = mMap.Center; userPos.Visible = true; mMap.MapElements.Remove(userPos); mMap.MapElements.Add(userPos); _lastPosition = pos; // Get address for current location await UpdateLocationAsync(mMap.Center); // Other cases // TODO: When shit gets serious // // case GeolocationAccessStatus.Denied: // case GeolocationAccessStatus.Allowed: // case GeolocationAccessStatus.Unspecified: } }
private async void UpdateMap(Geoposition position) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (lockObject) { // Set player icon's position MapControl.SetLocation(PlayerImage, position.Coordinate.Point); // Update angle and center only if map is not being manipulated if (lastAutoPosition == null) { lastAutoPosition = GameMapControl.Center; GameMapControl.Heading = 0; } //Small Trick: I'm not testing lastAutoPosition == GameMapControl.Center because MapControl is not taking exact location when setting center!! string currentCoord = $"{GameMapControl.Center.Position.Latitude: 000.0000} ; {GameMapControl.Center.Position.Longitude: 000.0000}"; string previousCoord = $"{lastAutoPosition.Position.Latitude: 000.0000} ; {lastAutoPosition.Position.Longitude: 000.0000}"; if (currentCoord == previousCoord) { //Previous position was set automatically, continue! ReactivateMapAutoUpdateButton.Visibility = Visibility.Collapsed; GameMapControl.Center = position.Coordinate.Point; lastAutoPosition = GameMapControl.Center; if (SettingsService.Instance.MapAutomaticOrientationMode == MapAutomaticOrientationModes.GPS && position.Coordinate.Heading != null) { GameMapControl.Heading = position.Coordinate.Heading.Value; } if (SettingsService.Instance.IsRememberMapZoomEnabled == true) { GameMapControl.ZoomLevel = SettingsService.Instance.Zoomlevel; } } } }); }
public async Task <bool> LoadChildPlacesData() { this.Loading = true; try { ChildPlacesItems = await ChildPlacesTable.ToCollectionAsync(999); try { Geolocator _geolocator = new Geolocator(); Geoposition pos = await _geolocator.GetGeopositionAsync(); Geocoordinate posGeo = pos.Coordinate; //MyCoordinate = pos; Longitude = pos.Coordinate.Longitude; Latitude = pos.Coordinate.Latitude; } catch { } //ChildPlaceItems = new ObservableCollection<ChildPlaceItem>(); //Location mylocation = new Location(pos.Coordinate.Point.Position.Latitude, pos.Coordinate.Point.Position.Longitude); foreach (var item in ChildPlacesItems) { item.Latitude = Double.Parse(item.Y); item.Longitude = Double.Parse(item.X); Items.Add(item); item.CalculateDistance(Latitude, Longitude); ChildPlaceItems.Add(item); } } catch { } RaisePropertyChanged("ChildPlaceItems"); RaisePropertyChanged("BestChildPlaceItems"); this.Loading = false; return(true); }
internal PositionChangedEventArgs(Geoposition position) { Position = position; }
internal GeofenceStateChangeReport(Geofence geofence, Geoposition geoposition, GeofenceState newstate) { _geofence = geofence; _geoposition = geoposition; _newState = newstate; }