/// <summary> /// Calculates distance between two locations. /// </summary> /// <returns>The <see cref="System.Double"/>The distance in meters</returns> /// <param name="a">Location a</param> /// <param name="b">Location b</param> public static double DistanceFrom(this Position a, Position b) { double distance = Math.Acos( (Math.Sin(a.Latitude) * Math.Sin(b.Latitude)) + (Math.Cos(a.Latitude) * Math.Cos(b.Latitude)) * Math.Cos(b.Longitude - a.Longitude)); return EquatorRadius * distance; }
/// <summary> /// Calculates bearing between start and stop. /// </summary> /// <returns>The <see cref="System.Double"/>.</returns> /// <param name="start">Start coordinates.</param> /// <param name="stop">Stop coordinates.</param> public static double BearingFrom(this Position start, Position stop) { var deltaLon = stop.Longitude - start.Longitude; var cosStop = Math.Cos(stop.Latitude); return Math.Atan2( (Math.Cos(start.Latitude) * Math.Sin(stop.Latitude)) - (Math.Sin(start.Latitude) * cosStop * Math.Cos(deltaLon)), Math.Sin(deltaLon) * cosStop); }
public async void GetOpenWeatherForecast_ShouldReturnTheWeatherForecast () { var openWeatherMapService = new OpenWeatherMapService (new HttpClient ()); var location = new Position { Latitude = 41.890969, Longitude = -87.676392 }; var resultTask = openWeatherMapService.Get7DayForecastAsync (location); resultTask.Wait (); Assert.IsNotNull (resultTask.Result); }
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 void GetForecast_ShouldReturnA7DayForecast() { //TODO supply mock instance var openWeatherMapService = new OpenWeatherMapService (new HttpClient ()); var forecastService = new ForecastService (openWeatherMapService); var location = new Position { Latitude = 41.890969, Longitude = -87.676392 }; var resultTask = forecastService.GetForecastAsync (location); resultTask.Wait (); Assert.IsNotNull (resultTask.Result); Assert.AreEqual (resultTask.Result.WeatherList.Count, 7); }
public async Task<Forecast> GetForecastAsync (Position location) { var openGroupForecast = await _openGroupMapService.Get7DayForecastAsync (location); var forecast = new Forecast () { Location = location }; var daysClean = 0; var dtf = new DateTimeFormatInfo (); foreach (var forecastItem in openGroupForecast.Forecasts) { var weather = forecastItem.WeatherList.FirstOrDefault (); var date = new DateTime (1970, 1, 1).AddSeconds (forecastItem.Dt); forecast.GroupList.Add (new GroupViewTemplate { GroupCondition = weather.Description, DayAbbreviation = dtf.GetAbbreviatedDayName (date.DayOfWeek), EventStart = Convert.ToInt32(forecastItem.Temperature.Max) + "º", EventEnd = Convert.ToInt32(forecastItem.Temperature.Min) + "º", Icon = GetWeatherIcon (weather.Main) }); } foreach (var forecastItem in openGroupForecast.Forecasts) { var date = new DateTime (1970, 1, 1).AddSeconds (forecastItem.Dt); if (date.Date.Date < DateTime.Now.Date.Date) continue; var weatherForToday = forecastItem.WeatherList [0]; forecast.BadWeatherDay = date; forecast.Reason = ConvertReason (weatherForToday.Main); forecast.ReasonDescription = weatherForToday.Description; if (WeatherIsBad (weatherForToday)) break; daysClean++; } forecast.ScheduledGroupsCount = daysClean; return forecast; }
public void OnLocationChanged (Location location) { if (location.Provider != this.activeProvider) { if (this.activeProvider != null && this.manager.IsProviderEnabled (this.activeProvider)) { LocationProvider pr = this.manager.GetProvider (location.Provider); TimeSpan lapsed = GetTimeSpan (location.Time) - GetTimeSpan (this.lastLocation.Time); if (pr.Accuracy > this.manager.GetProvider (this.activeProvider).Accuracy && lapsed < timePeriod.Add (timePeriod)) { location.Dispose(); return; } } this.activeProvider = location.Provider; } var previous = Interlocked.Exchange (ref this.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)); }
public void OnLocationChanged(Android.Locations.Location location) { Log.Debug (tag, "Location changed"); var lat = location.Latitude; var lng = location.Longitude; var geo = new Geocoder (this); List<Address> getAddress = new List<Address>(geo.GetFromLocation(lat,lng,1)); Address returnedAddress = getAddress.FirstOrDefault(); if (returnedAddress != null) { System.Text.StringBuilder strReturnedAddress = new StringBuilder (); for (int i = 0; i < returnedAddress.MaxAddressLineIndex; i++) { strReturnedAddress.Append (returnedAddress.GetAddressLine (i)).AppendLine (" "); } loc.Text = strReturnedAddress.ToString (); getLoc.Text = "My Location"; pos1 = new Xamarin.Forms.Labs.Services.Geolocation.Position() { Latitude = location.Latitude, Longitude = location.Longitude }; //determine whether closer to los gatos or palo alto if (loc.Text.Contains("Palo Alto")) { town = false; getSpot.Enabled = true; } else if (loc.Text.Contains("Los Gatos")) { town = true; getSpot.Enabled = true; } else { //set alert for executing the task AlertDialog.Builder alert = new AlertDialog.Builder (this); alert.SetTitle ("Sorry, you are too far from Palo Alto or Los Gatos"); alert.SetNeutralButton ("OK", (senderAlert, args) => {} ); //run the alert in UI thread to display in the screen RunOnUiThread (() => { alert.Show(); }); } } }
public async Task <double> GetDistancia(string posUno, string posDos) { var positionsUno = (await(new Geocoder()).GetPositionsForAddressAsync(posUno)).ToList(); if (!positionsUno.Any()) { return(-1.0); } var positionsDos = (await(new Geocoder()).GetPositionsForAddressAsync(posDos)).ToList(); if (!positionsDos.Any()) { return(-1.0); } var pos1 = new Xamarin.Forms.Labs.Services.Geolocation.Position() { Latitude = positionsUno.First().Latitude, Longitude = positionsUno.First().Longitude //Latitude = 48.4568664, //Longitude = 35.0352648 }; var pos2 = new Xamarin.Forms.Labs.Services.Geolocation.Position() { Latitude = positionsDos.First().Latitude, Longitude = positionsDos.First().Longitude //Latitude = 48.3837615903, //Longitude = 35.0011338294 }; var distance = Xamarin.Forms.Labs.Services.Geolocation.PositionExtensions.DistanceFrom(pos1, pos2); return(distance); //System.Diagnostics.Debug.WriteLine(distance); }
public async Task<double> GetDistancia(string posUno, string posDos) { var positionsUno = (await (new Geocoder()).GetPositionsForAddressAsync(posUno)).ToList(); if (!positionsUno.Any()) { return -1.0; } var positionsDos = (await (new Geocoder()).GetPositionsForAddressAsync(posDos)).ToList(); if (!positionsDos.Any()) { return -1.0; } var pos1 = new Xamarin.Forms.Labs.Services.Geolocation.Position() { Latitude = positionsUno.First().Latitude, Longitude = positionsUno.First().Longitude //Latitude = 48.4568664, //Longitude = 35.0352648 }; var pos2 = new Xamarin.Forms.Labs.Services.Geolocation.Position() { Latitude = positionsDos.First().Latitude, Longitude = positionsDos.First().Longitude //Latitude = 48.3837615903, //Longitude = 35.0011338294 }; var distance = Xamarin.Forms.Labs.Services.Geolocation.PositionExtensions.DistanceFrom(pos1, pos2); return distance; //System.Diagnostics.Debug.WriteLine(distance); }
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 (this.finishedCallback != null) this.finishedCallback(); this.completionSource.TrySetResult (p); }
private void OnListenerPositionChanged(object sender, PositionEventArgs e) { if (!IsListening) // ignore anything that might come in afterwards return; lock (positionSync) { lastPosition = e.Position; EventHandler<PositionEventArgs> changed = PositionChanged; if (changed != null) changed(this, e); } }
public PositionEventArgs(Position position) { if (position == null) throw new ArgumentNullException("position"); Position = position; }
public static Task<bool> DriveTo(this IDevice device, Position position) { return device.LaunchUriAsync(position.DriveToLink()); }
protected void SensorData(double rad, Position pos, int count, Dictionary<string, string> sensorInfo, Dictionary<string, string> sensorCoord, bool city) { string place = (!city) ? "pa" : "lg"; string zone = "1"; var request1 = HttpWebRequest.Create (string.Format (@"http://api.landscape-computing.com/nboxws/rest/v1/site/" + place + "/query/summary/?key=" + api_KEY)); request1.ContentType = "application/json"; request1.Method = "GET"; using (HttpWebResponse response1 = request1.GetResponse () as HttpWebResponse) { if (response1.StatusCode != HttpStatusCode.OK) Log.Debug (tag, "Error fetching data. Server returned status code: {0}", response1.StatusCode); using (StreamReader reader1 = new StreamReader (response1.GetResponseStream ())) { var content1 = reader1.ReadToEnd (); if (string.IsNullOrWhiteSpace (content1)) { Log.Debug (tag, "Response contained empty body..."); } else { var occ = content1.Split('|'); for (int i = 0; i < occ.Length; i++) { var sensorId = occ[i].Split(':')[0]; if (!string.IsNullOrWhiteSpace(sensorId)) { var occupied = Char.ToString(occ[i].Split(':')[1][1]); if (occupied == "0") { count++; } sensorInfo.Add(sensorId, occupied); } else { continue; } } } } } var request = HttpWebRequest.Create (string.Format (@"http://api.landscape-computing.com/nboxws/rest/v1/zone/" + place + "_" + zone + "/?key=" + api_KEY)); request.ContentType = "application/json"; request.Method = "GET"; using (HttpWebResponse response = request.GetResponse () as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) Log.Debug (tag, "Error getting data. Server returned status code: {0}", response.StatusCode); using (StreamReader reader = new StreamReader (response.GetResponseStream ())) { string content = reader.ReadToEnd (); if (string.IsNullOrWhiteSpace (content)) { Log.Debug (tag, "Response contained empty body..."); } else { var test = content.Split(new string[] { "sensorId" }, StringSplitOptions.None); for (int i = 1; i < test.Length - 1; i++) { string temp = test[i]; if (temp.Contains("guid")) { int sFrom = temp.IndexOf("<guid>") + "<guid>".Length; int sTo = temp.LastIndexOf("</guid>"); string senseId = temp.Substring(sFrom, sTo - sFrom); int gFrom = temp.IndexOf("<gpsCoord>") + "<gpsCoord>".Length; int gTo = temp.IndexOf("</gpsCoord>"); string coordinates = temp.Substring (gFrom, gTo - gFrom); sensorCoord.Add (senseId, coordinates); } } } } } Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>(); foreach (var sensor in sensorCoord) { if (sensorInfo.ContainsKey (sensor.Key)) { List<double> vals = new List<double>(); double occ = Double.Parse(sensorInfo [sensor.Key]); if (occ == 0) { string latSt = sensor.Value.Split (',') [0]; string lngSt = sensor.Value.Split (',') [1]; double lat = 0; double lng = 0; Double.TryParse (latSt, out lat); Double.TryParse (lngSt, out lng); float[] distance = new float[1]; Location.DistanceBetween(pos.Latitude, pos.Longitude, lat, lng, distance); double dist = System.Convert.ToDouble(distance[0]) / 1609.344; if (dist <= rad) { Log.Debug (tag, "{0}", dist); vals.Add (occ); vals.Add (lat); vals.Add (lng); dict.Add (sensor.Key, vals); } else Log.Debug (tag, "Not {0}", dist); } else continue; } else Log.Debug (tag, "what"); } foreach (var sensor in dict) { Log.Debug (tag, "{0}, {1}", sensor.Key, sensor.Value [0]); /*foreach (var value in sensor.Value) { Log.Debug (tag, "{0}: {1}", sensor.Key, value); }*/ } getSpot.Text = "Refresh"; total.Text = sensorInfo.Count().ToString(); open.Text = dict.Count.ToString(); }
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 (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)); }