public static double CalculateSpeedKPH(Position previousPosition, Position currentPosition, out double distanceKM, out double timeHours) { distanceKM = CalculateDistanceKM(previousPosition, currentPosition); timeHours = new TimeSpan(currentPosition.Timestamp.Ticks - previousPosition.Timestamp.Ticks).TotalHours; return distanceKM / timeHours; }
public PointOfInterest(string name, string type, Position position) : this() { _name = name ?? ""; _type = type ?? ""; _position = position; }
public override void Stop() { lock (_locker) { base.Stop(); _previousPosition = null; // reset previous location so it doesn't get used when this probe is restarted. } }
public override void Start() { lock (_locker) { _previousPosition = null; // do this before starting the base-class poller so it doesn't race to grab a stale previous location. base.Start(); } }
private GpsReceiver() { _desiredAccuracyMeters = 10; _readingIsComing = false; _readingWait = new ManualResetEvent(false); _reading = null; _readingTimeoutMS = 120000; _minimumTimeHintMS = 5000; }
private GpsReceiver() { _desiredAccuracyMeters = 50; // setting this too low appears to result in very delayed GPS fixes. _readingIsComing = false; _readingWait = new ManualResetEvent(false); _reading = null; _readingTimeoutMS = 120000; _minimumTimeHintMS = 5000; }
public ProductsMapScreen(Position position, IEnumerable<Product> products) : base("ProductsMapScreen", null) { this.position = position; this.products = products; TabBarItem = new UITabBarItem { Title = "Map", Image = UIImage.FromFile("Images/globe_64.png") }; }
public void OnLocationChanged( Location location ) { if(location.Provider != activeProvider) { if(activeProvider != null && manager.IsProviderEnabled( activeProvider )) { LocationProvider pr = manager.GetProvider( location.Provider ); TimeSpan lapsed = GetTimeSpan( location.Time ) - GetTimeSpan( lastLocation.Time ); if(pr.Accuracy > manager.GetProvider( activeProvider ).Accuracy && lapsed < timePeriod.Add( timePeriod )) { location.Dispose(); return; } } activeProvider = location.Provider; } var previous = Interlocked.Exchange( ref lastLocation, location ); if(previous != null) { previous.Dispose(); } var p = new Position(); if(location.HasAccuracy) { p.Accuracy = location.Accuracy; } if(location.HasAltitude) { p.Altitude = location.Altitude; } if(location.HasBearing) { p.Heading = location.Bearing; } if(location.HasSpeed) { p.Speed = location.Speed; } p.Longitude = location.Longitude; p.Latitude = location.Latitude; p.Timestamp = Geolocator.GetTimestamp( location ); var changed = PositionChanged; if(changed != null) { changed( this, new PositionEventArgs( p ) ); } }
private static Position ToFormsPosition(Xamarin.Geolocation.Position pos) { return(new Position { Accuracy = pos.Accuracy, Altitude = pos.Altitude, AltitudeAccuracy = pos.AltitudeAccuracy, Heading = pos.Heading, Latitude = pos.Latitude, Longitude = pos.Longitude, Speed = pos.Speed, Timestamp = pos.Timestamp }); }
public List<SpotViewModel> FindMiningSpots(Position position) { List<SpotViewModel> spots = new List<SpotViewModel>(); foreach (var item in GetSpots()) { var spotVM = new SpotViewModel(item, position.Latitude, position.Longitude); if (spotVM.Distance < 0.25) { spots.Add(spotVM); } } return spots; }
public Position (Position position) { if (position == null) throw new ArgumentNullException ("position"); Timestamp = position.Timestamp; Latitude = position.Latitude; Longitude = position.Longitude; Altitude = position.Altitude; AltitudeAccuracy = position.AltitudeAccuracy; Accuracy = position.Accuracy; Heading = position.Heading; Speed = position.Speed; }
public SpeedDatum(DateTimeOffset timestamp, Position previousPosition, Position currentPosition) : base(timestamp, 0) { double distanceKM; double timeHours; _kph = SpeedDatum.CalculateSpeedKPH(previousPosition, currentPosition, out distanceKM, out timeHours); if (previousPosition.Accuracy >= 0 && currentPosition.Accuracy >= 0) { double maximumDistanceKM = distanceKM + previousPosition.Accuracy / 1000f + currentPosition.Accuracy / 1000f; double maximumSpeedKPH = maximumDistanceKM / timeHours; Accuracy = (float)(maximumSpeedKPH - _kph); } }
async void GetPosition() { try { locator = new Geolocator{DesiredAccuracy =50}; if ( locator.IsListening != true ) locator.StartListening(minTime: 1000, minDistance: 0); position = await locator.GetPositionAsync (timeout: 20000); } catch ( Exception e) { } }
/// <summary> /// Calculates distance (KM) given two lat-lon positions (http://www.movable-type.co.uk/scripts/latlong.html) /// </summary> /// <returns>Distance in KM.</returns> /// <param name="previousPosition">Previous position.</param> /// <param name="currentPosition">Current position.</param> public static double CalculateDistanceKM(Position previousPosition, Position currentPosition) { double φ1 = DegreesToRadians(previousPosition.Latitude); double φ2 = DegreesToRadians(currentPosition.Latitude); double Δφ = DegreesToRadians(currentPosition.Latitude - previousPosition.Latitude); double Δλ = DegreesToRadians(currentPosition.Longitude - previousPosition.Longitude); double a = Math.Pow(Math.Sin(Δφ / 2), 2) + Math.Cos(φ1) * Math.Cos(φ2) * Math.Pow(Math.Sin(Δλ / 2), 2); double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); return 6371 * c; }
public ListeningSpeedProbe() { _positionChangedHandler = (o, e) => { lock (_locker) { SensusServiceHelper.Get().Logger.Log("Received position change notification.", LoggingLevel.Verbose, GetType()); if (_previousPosition != null && e.Position != null && e.Position.Timestamp != _previousPosition.Timestamp) StoreDatum(new SpeedDatum(e.Position.Timestamp, _previousPosition, e.Position)); if (e.Position != null) _previousPosition = e.Position; } }; }
private async void GetPositionHandler (object state) { try { Position p = await this.geolocator.GetPositionAsync (10000); CurrentPosition = p; } catch (GeolocationException ex) { Status = "Error: (" + ex.Error + ") " + ex.Message; } catch (TaskCanceledException cex) { Status = "Canceled"; } }
public IEnumerable<Product> GetProductsNear(Position position) { var products = Enumerable.Empty<Product>(); Console.WriteLine("Fetching products near: {0} lat, {1} long", position.Latitude, position.Longitude); var request = WebRequest.Create(CoordinatesUrl.FormatWith(position.Latitude, position.Longitude)); using (var response = request.GetResponse()) { //BUG: MT 5.3.2 see http://docs.xamarin.com/ios/troubleshooting#System.ExecutionEngineException.3a_Attempting_to_JIT_compile_method_(wrapper_managed-to-managed)_Foo.5b.5d.3aSystem.Collections.Generic.ICollection.601.get_Count_() JsonReader<CLLocationCoordinate2D>.GetParseFn(); try{ products = JsonSerializer.DeserializeFromStream<Product[]>(response.GetResponseStream()); } catch{ } } return products.Where(x => !string.IsNullOrWhiteSpace(x.Url)); }
public ListeningSpeedProbe() { _positionChangedHandler = (o, e) => { if (e.Position == null) return; lock (_locker) { SensusServiceHelper.Get().Logger.Log("Received position change notification.", LoggingLevel.Verbose, GetType()); if (_previousPosition == null) _previousPosition = e.Position; else if (e.Position.Timestamp > _previousPosition.Timestamp) // it has happened (rarely) that positions come in out of order...drop any such positions. { StoreDatum(new SpeedDatum(e.Position.Timestamp, _previousPosition, e.Position)); _previousPosition = e.Position; } } }; }
double distForPos(Position lhs, Position rhs) { return Math.Sqrt( Math.Pow(rhs.Latitude - lhs.Latitude, 2.0) + Math.Pow(rhs.Longitude - lhs.Longitude, 2.0)); }
private async void GetPositionHandler (object state) { ShowProgress = true; Status = "Getting location.."; if (!this.geolocator.IsGeolocationEnabled) { Status = "Location disabled"; return; } try { Position p = await this.geolocator.GetPositionAsync (10000, includeHeading: true); CurrentPosition = p; Status = "Success"; } catch (GeolocationException ex) { Status = "Error: (" + ex.Error + ") " + ex.Message; } catch (TaskCanceledException cex) { Status = "Canceled"; } ShowProgress = false; }
private void GeolocatorOnPositionChanged (object sender, PositionEventArgs e) { CurrentPosition = e.Position; }
public ProductSearchController(Position position, IEnumerable<Product> products) { this.position = position; this.products = products; }
void geo_PositionChanged(object sender, PositionEventArgs e) { lock (geo) { currentPosition = e.Position; System.Diagnostics.Debug.WriteLine("CURRENT POSITION: " + currentPosition.Latitude.ToString() + ", " + currentPosition.Longitude.ToString()); } }
private void UpdateLocation() { locationManager = new Geolocator (this); locationManager.PositionChanged += (sender, e) => { location = e.Position; locationManager.StopListening (); }; locationManager.StartListening (0, 0); }
private void Finish( Location location ) { var p = new Position(); if(location.HasAccuracy) { p.Accuracy = location.Accuracy; } if(location.HasAltitude) { p.Altitude = location.Altitude; } if(location.HasBearing) { p.Heading = location.Bearing; } if(location.HasSpeed) { p.Speed = location.Speed; } p.Longitude = location.Longitude; p.Latitude = location.Latitude; p.Timestamp = Geolocator.GetTimestamp( location ); if(finishedCallback != null) { finishedCallback(); } completionSource.TrySetResult( p ); }
private void UpdatePosition (CLLocation location) { Position p = (this.position == null) ? new Position () : new Position (this.position); if (location.HorizontalAccuracy > -1) { p.Accuracy = location.HorizontalAccuracy; p.Latitude = location.Coordinate.Latitude; p.Longitude = location.Coordinate.Longitude; } if (location.VerticalAccuracy > -1) { p.Altitude = location.Altitude; p.AltitudeAccuracy = location.VerticalAccuracy; } if (location.Speed > -1) p.Speed = location.Speed; p.Timestamp = new DateTimeOffset ((DateTime)location.Timestamp); this.position = p; OnPositionChanged (new PositionEventArgs (p)); location.Dispose(); }
private void OnUpdatedHeading (object sender, CLHeadingUpdatedEventArgs e) { if (e.NewHeading.TrueHeading == -1) return; Position p = (this.position == null) ? new Position () : new Position (this.position); p.Heading = e.NewHeading.TrueHeading; this.position = p; OnPositionChanged (new PositionEventArgs (p)); }
public async Task UpdateSpots(Position newPosition){ await Task.Run(() => { NearSpots = FindMiningSpots(newPosition); }); }
protected override IEnumerable<Datum> Poll(CancellationToken cancellationToken) { lock (_locker) { Position currentPosition = GpsReceiver.Get().GetReading(cancellationToken); Datum[] data = null; if (_previousPosition == null || currentPosition == null || currentPosition.Timestamp == _previousPosition.Timestamp) data = new Datum[] { }; else data = new SpeedDatum[] { new SpeedDatum(currentPosition.Timestamp, _previousPosition, currentPosition) }; if (currentPosition != null) _previousPosition = currentPosition; return data; } }
/// <summary> /// Gets a GPS reading, reusing an old one if it isn't too old. Will block the current thread while waiting for a GPS reading. Should not /// be called from the main / UI thread, since GPS runs on main thread (will deadlock). /// </summary> /// <returns>The reading.</returns> /// <param name="maxReadingAgeForReuseMS">Maximum age of old reading to reuse (milliseconds).</param> /// <param name="cancellationToken">Cancellation token.</param> public Position GetReading(int maxReadingAgeForReuseMS, CancellationToken cancellationToken) { lock (_locker) { // reuse existing reading if it isn't too old if (_reading != null && maxReadingAgeForReuseMS > 0) { double readingAgeMS = (DateTimeOffset.UtcNow - _reading.Timestamp).TotalMilliseconds; if (readingAgeMS <= maxReadingAgeForReuseMS) { SensusServiceHelper.Get().Logger.Log("Reusing previous GPS reading, which is " + readingAgeMS + "ms old (maximum = " + maxReadingAgeForReuseMS + "ms).", LoggingLevel.Verbose, GetType()); return _reading; } } if (_readingIsComing) SensusServiceHelper.Get().Logger.Log("A GPS reading is coming. Will wait for it.", LoggingLevel.Debug, GetType()); else { _readingIsComing = true; // tell any subsequent, concurrent callers that we're taking a reading _readingWait.Reset(); // make them wait new Thread(async () => { try { SensusServiceHelper.Get().Logger.Log("Taking GPS reading.", LoggingLevel.Debug, GetType()); DateTimeOffset readingStart = DateTimeOffset.UtcNow; Position newReading = await _locator.GetPositionAsync(timeout: _readingTimeoutMS, cancelToken: cancellationToken); DateTimeOffset readingEnd = DateTimeOffset.UtcNow; if (newReading != null) { // create copy of new position to keep return references separate, since the same Position object is returned multiple times when a change listener is attached. _reading = new Position(newReading); SensusServiceHelper.Get().Logger.Log("GPS reading obtained in " + (readingEnd - readingStart).TotalSeconds + " seconds.", LoggingLevel.Verbose, GetType()); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("GPS reading failed: " + ex.Message, LoggingLevel.Normal, GetType()); _reading = null; } _readingWait.Set(); // tell anyone waiting on the shared reading that it is ready _readingIsComing = false; // direct any future calls to this method to get their own reading }).Start(); } } _readingWait.WaitOne(_readingTimeoutMS); if (_reading == null) SensusServiceHelper.Get().Logger.Log("GPS reading is null.", LoggingLevel.Normal, GetType()); return _reading; }
private void OnListenerPositionChanged( object sender, PositionEventArgs e ) { if(!IsListening) // ignore anything that might come in afterwards { return; } lock(positionSync) { lastPosition = e.Position; var changed = PositionChanged; if(changed != null) { changed( this, e ); } } }