/// <summary> /// Initializes a new instance of the <see cref="SimpleLineSubdivisionOperation"/> class /// </summary> /// <param name="splitLine">The line to split.</param> /// <param name="dist">The distance to the split point.</param> /// <param name="isFromEnd">Is the distance observed from the end of the line?</param> internal SimpleLineSubdivisionOperation(LineFeature splitLine, Distance dist, bool isFromEnd) : base() { m_Line = splitLine; m_Distance = dist; m_IsFromEnd = isFromEnd; }
public void TestConstructorValue() { Distance dist = new Distance("5 m"); Assert.AreEqual(5, dist.Value); Assert.AreEqual(DistanceUnit.Meters, dist.Units); }
public void TestConstructorValueCulture() { Distance dist = new Distance("5 m", CultureInfo.CurrentCulture); Assert.AreEqual(5, dist.Value); Assert.AreEqual(DistanceUnit.Meters, dist.Units); }
public void CanCreate() { Distance distance = new Distance(5.7, DistanceUnits.Miles); Assert.Equal(5.7, distance.Value); Assert.Equal(DistanceUnits.Miles, distance.Units); }
public Position(Coordinate coordinate, Accuracy accuracy, Distance altitide, DateTimeOffset timestamp) { Coordinate = coordinate; Accuracy = accuracy; Altitude = altitide; Timestamp = timestamp; }
public void ConvertToSi(Distance s, string dimension) { if (dimension != "m") { if (dimension == "km") { s.Value *= 1000; } else if (dimension == "dm") { s.Value /=10; } else if (dimension == "cm") { s.Value /= 100; } else if (dimension == "mm") { s.Value /= 1000; } else if (dimension == "mm") { s.Value /= 1000; } else { throw new IncorrectDimensionOfDistanceException(); } } }
public ActionResult CalcCalories(WeightData weightData, Distance distanceData) { if (!ModelState.IsValid) return new JsonResult { Data = new { Result = false } }; return new JsonResult { Data = new { Result = true, Calories = caloriesCalc.Calculate(distanceData, weightData) } }; }
/// <summary> /// Shifts the point to the specified distance. /// </summary> /// <param name="point">The point.</param> /// <param name="distance">The distance.</param> /// <returns>Point shifted to the specified distance.</returns> public static Point Add(this Point point, Distance distance) { return new Point() { X = distance.X.IsNotSet() ? point.X : point.X + distance.X, Y = distance.Y.IsNotSet() ? point.Y : point.Y + distance.Y }; }
//public ICoordinate Coordinate //{ // get { return _loc; } // set { _loc = value; } //} public Distance GreatCircleDistance(Point pt2) { double distance = Math.Acos((Math.Sin(this.LatRad) * Math.Sin(pt2.LatRad)) + (Math.Cos(this.LatRad) * Math.Cos(pt2.LatRad) * Math.Cos(pt2.LonRad - this.LonRad))); distance = distance * 3963.0; // Statute Miles distance = distance * 1.609344; // to Km Distance d = new Distance(distance, DistanceUnits.KILOMETERS); return d; }
/// <summary> /// Creates a new <c>CircularLeg</c> with no spans. /// </summary> /// <param name="radius">The radius of the circular leg.</param> /// <param name="clockwise">True if the curve is clockwise.</param> /// <param name="span">The number of spans on the curve.</param> internal CircularLeg(Distance radius, bool clockwise, int nspan) : base(nspan) { m_Metrics = new CircularLegMetrics(radius, clockwise); // The circle for this leg won't be known till we create a span. m_Circle = null; }
/// <summary> /// Inserts an extra distance into the path. /// </summary> /// <param name="newdist">The new distance to insert.</param> /// <param name="curdist">A distance that this leg already knows about.</param> /// <param name="isBefore">Should the new distance go before the existing one?</param> internal void InsertSpan(int legIndex, Distance newdist, Distance curdist, bool isBefore) { /* Leg leg = m_Legs[legIndex]; int spanIndex = leg.GetIndex(curdist); var edit = new SpanInsert((uint)legIndex, */ }
public void CanCompareForEquality() { Distance distance1 = new Distance(5, DistanceUnits.Miles); Distance distance2 = new Distance(5, DistanceUnits.Miles); Assert.True(distance1.Equals(distance2)); Assert.Equal(distance1.GetHashCode(), distance2.GetHashCode()); }
public static Distance CalcDistance(double x1, double y1, double x2, double y2) { bool isHorizontal = y1 == y2; bool isVertical = x1 == x2; double calculatedDistance = Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); Distance distance = new Distance(calculatedDistance, isHorizontal, isVertical); return distance; }
public void TestConstructorValueCultureException() { Distance dist; Assert.Throws<ArgumentException>(() => dist = new Distance("5", CultureInfo.CurrentCulture)); //Assert.AreEqual(5, dist.Value); //Assert.AreEqual(SpeedUnit.MetersPerSecond, dist.Units); }
public void GetDistance_From130x450yToOwn_130f() { var point = new Position(130, 450); var act = Goal.Own.GetDistance(point); var exp = new Distance(130); Assert.AreEqual(exp, act); }
/// <summary> /// Default constructor defines a blank dialog /// </summary> internal CulDeSacForm() { InitializeComponent(); m_Radians = 0.0; m_Radius = null; m_IsClockwise = true; m_IsDefined = false; }
/// <summary> /// Initializes a new instance of the <see cref="CircularLegMetrics"/> class with /// undefined angles (both set to zero). /// </summary> /// <param name="radius">The observed radius.</param> /// <param name="isClockwise">Is the leg directed clockwise?</param> internal CircularLegMetrics(Distance radius, bool isClockwise) { m_Angle1 = m_Angle2 = 0.0; m_Radius = radius; // Remember if its NOT a clockwise arc. if (!isClockwise) m_Flag |= CircularLegFlag.CounterClockwise; }
public LocationVector(Distance dist, double? bearing) { Distance = dist; // No bearing above 360.0 Bearing = bearing % 360.0; // No negativ bearings if (Bearing < 0) Bearing = 360.0 + Bearing; }
/// <summary> /// Initializes a new instance of the <see cref="LineExtensionOperation"/> class /// </summary> /// <param name="extendLine">The line that's being extended.</param> /// <param name="isFromEnd">True if extending from the end | False from the start.</param> /// <param name="length">The length of the extension.</param> internal LineExtensionOperation(LineFeature extendLine, bool isFromEnd, Distance length) : base() { m_ExtendLine = extendLine; m_IsExtendFromEnd = isFromEnd; m_Length = length; m_NewLine = null; m_NewPoint = null; }
/// <summary> /// Default constructor defines a blank dialog /// </summary> internal ArcForm() { InitializeComponent(); m_Angle1 = MathConstants.PIDIV2; m_Angle2 = MathConstants.PIDIV2; m_Radius = null; m_IsClockwise = true; m_IsDefined = false; }
public void NotEqualsReturnsFalseIfItemsAreEqual() { // Arrange const long Distance = 123; var distance1 = new Distance(Distance); var distance2 = new Distance(Distance); // Assert Assert.IsFalse(distance1 != distance2); }
/// <summary> /// Constructor for use when editing a connection path /// </summary> /// <param name="leg">The leg that's being edited</param> internal CulDeSacForm(CircularLeg leg) { InitializeComponent(); CircularLegMetrics metrics = leg.Metrics; m_Radians = metrics.CentralAngle; m_Radius = new Distance(metrics.ObservedRadius); m_IsClockwise = metrics.IsClockwise; m_IsDefined = true; }
public void EqualsReturnsTrueIfItemsAreEqual() { // Arrange const int Distance = 123; var distance1 = new Distance(Distance); var distance2 = new Distance(Distance); // Assert Assert.IsTrue(distance1 == distance2); }
/// <summary> /// Initializes a new instance of the <see cref="LegFace"/> class. /// <param name="leg">The leg this face relates to.</param> /// <param name="dists">The observed distances for this face.</param> /// </summary> internal LegFace(Leg leg, Distance[] dists) { this.Leg = leg; m_Spans = new SpanInfo[dists.Length]; for (int i=0; i<m_Spans.Length; i++) { m_Spans[i] = new SpanInfo(); m_Spans[i].ObservedDistance = dists[i]; } }
public ActionResult AutoCalcCalories(string date, int? route, double? distance) { WeightData weight = null; if (ControllerContext.HasValidUserAccount() && date != null) { var userAccount = ControllerContext.UserAccount(); DateTime onDate; if (!DateTime.TryParseExact(date, "ddd, d MMM yyyy HH':'mm':'ss 'UTC'", null, DateTimeStyles.AssumeUniversal, out onDate)) onDate = DateTime.UtcNow; weight = ProfileModel.DefaultWeightData(); var userPref = ((object)userAccount).UserPrefs().Latest(onDate); if (userPref != null) { weight.Units = userPref.WeightUnits; switch (weight.Units) { case "kg": weight.Kg = userPref.Weight; break; case "lbs": case "st": weight.Lbs = userPref.Weight; weight.Units = "lbs"; break; } weight.UpdateFromUnits(); if (userPref.WeightUnits == "st") weight.Units = "st"; } } if (weight == null || weight.UnitWeight == 0 || (!route.HasValue && !distance.HasValue)) return new JsonResult { Data = new { Result = false } }; Distance actualDistance = null; if (route.HasValue && route.Value > 0) { var dbRoute = MassiveDB.Current.FindRoute(route.Value); if (dbRoute != null) actualDistance = new Distance(dbRoute.Distance, (DistanceUnits)dbRoute.DistanceUnits).ConvertTo(ControllerContext.UserDistanceUnits()); } if (distance.HasValue && distance.Value > 0) actualDistance = new Distance(distance.Value, ControllerContext.UserDistanceUnits()); if (actualDistance == null) return new JsonResult { Data = new { Result = false } }; return new JsonResult { Data = new { Result = true, Calories = caloriesCalc.Calculate(actualDistance, weight) } }; }
public void EqualsReturnsFalseIfItemsAreNotEqual() { // Arrange const int Distance1 = 123; const int Distance2 = 321; var distance1 = new Distance(Distance1); var distance2 = new Distance(Distance2); // Assert Assert.IsFalse(distance1 == distance2); }
public static LumberClass.Lumber CreateLumberFromDB(string materialID) { DataSet data = SelectFromDB("SELECT * FROM MaterialMgmt.Rectangular WHERE MaterialsID = '" + materialID + "'"); Distance thickness = new Distance(DistanceType.Inch, Convert.ToDouble(data.Tables[0].Rows[0]["Depth"].ToString())); Distance width = new Distance(DistanceType.Inch, Convert.ToDouble(data.Tables[0].Rows[0]["Width"].ToString())); Distance length = new Distance(DistanceType.Foot, 12); string grade = data.Tables[0].Rows[0]["Grade"].ToString(); string species = data.Tables[0].Rows[0]["SpeciesShortName"].ToString(); return new LumberClass.Lumber(thickness, width, length, grade, species); }
public Lumber(Distance thickness, Distance width, Distance length, string grade = "", string species = "", string treatmentType = "", string mill = "", string passedBundle = "", string other = "") { this.Thickness = thickness; this.Width = width; this.Length = length; this.Grade = grade; this.Species = species; this.TreatmentType = treatmentType; this.Mill = mill; this.Other = other; }
private void DrawDistancePosition(SpriteBatch spriteBatch, Vector2 levelPosition, float squaredDistance, Distance distanceGrade ) { DestinationRectangle = new Rectangle(Camera.TransformX(levelPosition.X), Camera.TransformY(levelPosition.Y) , Camera.TransformSizeX(1) , Camera.TransformSizeY(1)); Rectangle? sourceRectangle = new Rectangle(GetSourceXValue(distanceGrade), 0, GameObjectTexture.Height, GameObjectTexture.Height); spriteBatch.Draw(GameObjectTexture, DestinationRectangle, sourceRectangle, Color.White); // spriteBatch.DrawString(_font, Math.Ceiling(Math.Sqrt(squaredDistance)).ToString(), new Vector2(DestinationRectangle.X + 1, DestinationRectangle.Y + 1), // Color.Black); }
public void ConvertToFeetWorksCorrectly() { // Arrange const double Millimeters = 112345d; const double Feet = 368.585958d; // Act var distance = new Distance(Millimeters); // Assert Assert.IsNotNull(distance); Assert.AreEqual(Feet, Math.Round(distance.ToFeet(), 6)); }
static void Distance_Initialization_Tests() { //Conversions should be equal to these numbers within .0001 tolerance double m = 1000; //meters double km = 1; //Kilometers double ft = 3280.84; //Feet double sm = 0.6213712; //Nautical Miles double nm = 0.5399565; //Statute Miles double[] distances = new double[] { m, km, ft, nm, sm }; Distance d = new Distance(km); Write_Pass("Distance(double km)", Check_Distance(d, distances)); d = new Distance(distances[0], DistanceType.Meters); Console.WriteLine(); Write_Pass("Distance(double distance, DistanceType Meters)", Check_Distance(d, distances)); d = new Distance(distances[1], DistanceType.Kilometers); Write_Pass("Distance(double distance, DistanceType Kilometers)", Check_Distance(d, distances)); d = new Distance(distances[2], DistanceType.Feet); Write_Pass("Distance(double distance, DistanceType Feet)", Check_Distance(d, distances)); d = new Distance(distances[3], DistanceType.NauticalMiles); Write_Pass("Distance(double distance, DistanceType Nautical Miles)", Check_Distance(d, distances)); d = new Distance(distances[4], DistanceType.Miles); Write_Pass("Distance(double distance, DistanceType Statute Miles)", Check_Distance(d, distances)); Console.WriteLine(); Coordinate c1 = new Coordinate(45, 72); Coordinate c2 = new Coordinate(42, 75); //KILOMETERS Between specified points above should be as follows in defined tolerance .000001 double kmSphere = 412.0367538058125; double kmWGS84 = 412.1977393206501; //Default datum WGS84 d = new Distance(c1, c2); if (System.Math.Abs(d.Kilometers - kmSphere) > .000001) { Write_Pass("Distance(Coordinate c1, Coordinate c2)", false); Debug.WriteLine("...Mismatch: " + d.Kilometers + " - " + kmSphere); } else { Write_Pass("Distance(Coordinate c1, Coordinate c2)", true); } d = new Distance(c1, c2, Shape.Sphere); if (System.Math.Abs(d.Kilometers - kmSphere) > .000001) { Write_Pass("Distance(Coordinate c1, Coordinate c2, Shape.Sphere)", false); Debug.WriteLine("...Mismatch: " + d.Kilometers + " - " + kmSphere); } else { Write_Pass("Distance(Coordinate c1, Coordinate c2, Shape.Sphere)", true); } d = new Distance(c1, c2, Shape.Ellipsoid); if (System.Math.Abs(d.Kilometers - kmWGS84) > .000001) { Write_Pass("Distance(Coordinate c1, Coordinate c2, Shape.Ellipsoid)", false); Debug.WriteLine("...Mismatch: " + d.Kilometers + " - " + kmWGS84); } else { Write_Pass("Distance(Coordinate c1, Coordinate c2, Shape.Ellipsoid)", true); } }
/// <summary> /// Constructor. /// </summary> /// <param name="type">The spread mechanics to use for source values.</param> /// <param name="positionX"> /// The X-value of the position on a map that the source is located at. /// </param> /// <param name="positionY"> /// The Y-value of the position on a map that the source is located at. /// </param> /// <param name="radius"> /// The maximum radius of the source -- this is the maximum distance the source values will /// emanate, provided the area is completely unobstructed. /// </param> /// <param name="distanceCalc"> /// The distance calculation used to determine what shape the radius has (or a type /// implicitly convertible to <see cref="Distance"/>, such as <see cref="Radius"/>). /// </param> /// <param name="intensity">The starting intensity value of the source. Defaults to 1.0.</param> public SenseSource(SourceType type, int positionX, int positionY, double radius, Distance distanceCalc, double intensity = 1.0) : this(type, new Coord(positionX, positionY), radius, distanceCalc, intensity) { }
private static int run(Ice.Communicator communicator) { var station = MeasurementStationPrxHelper.checkedCast(communicator.propertyToProxy("MeasurementStation.Proxy")); if (station == null) { Console.Error.WriteLine("invalid proxy"); return(1); } // // Get a random measurement. // var distance = station.getDistance(); // // Using the properties defined in the partial struct Distance we can access // the value represented by this object in a more convenient way. // Console.WriteLine("distance: {0} meters equal {1} yards", Math.Round(distance.Meters, 4), Math.Round(distance.Yards, 4)); // // This works equally well for types created locally. // distance = new Distance(1); Console.WriteLine("distance: {0} meters equal {1} yards", Math.Round(distance.Meters, 4), Math.Round(distance.Yards, 4)); // // The same apply for generated class types like Speed. // var speed = station.getSpeed(); Console.WriteLine("speed: {0} m/s is equal {1} km/h {2} mph", Math.Round(speed.MetersPerSecond, 4), Math.Round(speed.KilometersPerHour, 4), Math.Round(speed.MilesPerHour, 4)); // // Again this works equally well for objects created locally. // speed = new Speed(1); Console.WriteLine("speed: {0} m/s is equal {1} km/h {2} mph", Math.Round(speed.MetersPerSecond, 4), Math.Round(speed.KilometersPerHour, 4), Math.Round(speed.MilesPerHour, 4)); speed.KilometersPerHour = 1; Console.WriteLine("speed: {0} m/s is equal {1} km/h {2} mph", Math.Round(speed.MetersPerSecond, 4), Math.Round(speed.KilometersPerHour, 4), Math.Round(speed.MilesPerHour, 4)); speed.MilesPerHour = 1; Console.WriteLine("speed: {0} m/s is equal {1} km/h {2} mph", Math.Round(speed.MetersPerSecond, 4), Math.Round(speed.KilometersPerHour, 4), Math.Round(speed.MilesPerHour, 4)); station.shutdown(); return(0); }
private async void loadCurrentPosition(bool fromButton) { //if (fromButton) //{ await Task.Delay(1500); //} if (!this.IsVisible) { return; } try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { await DisplayAlert("Need location", "Gunna need that location", "OK"); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location); //Best practice to always check that the key exists if (results.ContainsKey(Permission.Location)) { status = results[Permission.Location]; } } if (status == PermissionStatus.Granted) { CancellationTokenSource ctx = new CancellationTokenSource(); var locator = CrossGeolocator.Current; //CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged; locator.DesiredAccuracy = 15; if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled) { var location = await locator.GetPositionAsync(TimeSpan.FromSeconds(10)); TK.CustomMap.Position position = new TK.CustomMap.Position(location.Latitude, location.Longitude); // MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMiles(0.25))); _pins.Clear(); var pin = new TKCustomMapPin { IsVisible = true, IsDraggable = true, //Type = TKCustomMapPin.Place, Position = position, Title = "Posición Actual" //Label = "Posición Actual", }; _pins.Add(pin); if (MyMap.Pins == null) { MyMap.Pins = _pins; } MyMap.MoveToMapRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMiles(0.25))); Xamarin.Forms.Maps.Geocoder geoCoder = new Xamarin.Forms.Maps.Geocoder(); var vm = (MainViewModel)BindingContext; vm.Maps.Coordenadas = position.Latitude + "," + position.Longitude; var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude)); vm.Maps.Direccion = ""; foreach (var a in possibleAddresses) { vm.Maps.Direccion += a; break; } } } else if (status != PermissionStatus.Unknown) { await DisplayAlert("Localización denegada", "No se puede continuar, intentar nuevamente.", "OK"); } } catch (Exception ex) { } }
/// <summary> /// Inserts BBC News rss feed data into the database /// </summary> private void InsertRssData() { Distance distance = new Distance(); try { // create database context var dbContext = new rlnews.DAL.RlnewsDb(); foreach (var newsItem in _feeds) { if (IsPostNew(newsItem.PubDateTime)) { string clusterType = null; int parentId = 0; DateTime nowMinus24 = DateTime.Now; DateTime now = DateTime.Now; nowMinus24 = nowMinus24.AddHours(-24); if (newsItem.PubDateTime > nowMinus24 && newsItem.PubDateTime <= now) { parentId = distance.CheckRelated(newsItem.Title); } if (parentId > 0) { clusterType = "Child"; } else { clusterType = "Parent"; } //Increment import counter _importCount++; //create object to add to database var dbObj = new rlnews.DAL.Models.NewsItem { Title = _validate.TrimNewsHtml(newsItem.Title), SourceName = newsItem.SourceName, Description = _validate.TrimNewsHtml(newsItem.Description), SourceUrl = newsItem.SourceUrl, ImageUrl = newsItem.ImageUrl, PubDateTime = newsItem.PubDateTime, Views = 0, ClusterType = clusterType }; dbContext.NewsItems.Add(dbObj); //Save database changes dbContext.SaveChanges(); if (parentId > 0) { //Create related news object to add the database var dbRelated = new rlnews.DAL.Models.RelatedNews { ParentNewsId = parentId, ChildNewsId = dbObj.NewsId }; dbContext.RelatedNews.Add(dbRelated); //Save database changes dbContext.SaveChanges(); } } } if (_importCount == 0) { _importMessage = "No new posts found from BBC News."; } else { _importMessage = "Successfully imported '" + _importCount + "' news items from BBC News."; } } catch (Exception ex) { _importMessage = "BBC News import failed: " + ex; } }
public async Task <IList <RecordTime> > GetRecordsBrokeAsync(IDisciplineCalculator calculator, Distance distance, PersonCompetitor competitor, TimeSpan time) { if (distance.Competition == null) { throw new ArgumentNullException(nameof(distance), Resources.DistanceCompetitionIsNull); } if (competitor.Person == null) { throw new ArgumentNullException(nameof(competitor), Resources.PersonCompetitorPersonIsNull); } var season = calculator.Season(distance.Competition.Starts); var age = calculator.SeasonAge(season, competitor.Person.BirthDate); return(await(from rt in context.RecordTimes where rt.LicenseIssuerId == distance.Competition.LicenseIssuerId && rt.Discipline == distance.Competition.Discipline && rt.DistanceDiscipline == distance.Discipline && rt.Distance == distance.Value && rt.Gender == competitor.Person.Gender && ((rt.Type == RecordType.National || rt.Type == RecordType.World) || (rt.Type == RecordType.Track && rt.VenueCode == distance.VenueCode) || (rt.Type == RecordType.TrackAge && rt.VenueCode == distance.VenueCode && rt.FromAge <= age && rt.ToAge >= age)) && time < rt.Time select rt).ToListAsync()); }
public MainPage(RoutePoints points) { InitializeComponent(); foreach (Points tmp in points.routePoints) { CustomPin pin = new CustomPin { Type = PinType.SavedPin, Position = new Position(tmp.X, tmp.Y), Label = tmp.Name, Address = tmp.Description, Name = "Xamarin", Url = "http://xamarin.com/about/", Question = "", Answer = "" }; if (String.IsNullOrWhiteSpace(tmp.Name)) { pin.Label = "Name"; } pin.MarkerClicked += async(s, args) => { args.HideInfoWindow = true; string pinName = ((CustomPin)s).Label; // string pytanie = ((CustomPin)s).Question; string opis = ((CustomPin)s).Address; // string odpowiedz = ((CustomPin)s).Answer; await DisplayAlert($"{pinName}", $"{opis}", "Ok"); // await DisplayAlert("Quiz", $"{pytanie}", "Przejdź do odpowiedzi"); //await Navigation.PushAsync(new QuestionPage(new Question())); }; customMap.Pins.Add(pin); } if (points.routePoints.Count > 0) { customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(points.routePoints[0].X, points.routePoints[0].Y), Distance.FromMiles(2.0))); } else { customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(53.010281, 18.604922), Distance.FromMiles(2.0))); } }
public async void OnAppearing() { Location loc = await Geolocation.GetLocationAsync(); Map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(loc.Latitude, loc.Longitude), Distance.FromMeters(5000))); Services.RestService connection = new Services.RestService(); (List <Stop> stops, int statuscode) = await connection.GetDraftStops(App.User_id); if (statuscode == 200) { Map.Pins.Clear(); foreach (Stop stop in stops) { Pin location = new Pin() { Type = PinType.Place, Label = stop.title, Address = stop.description, Position = new Position(stop.latitude, stop.longitude), }; Map.Pins.Add(location); } } }
public CustomMapPage() { InitializeComponent(); var map = new Map(MapSpan.FromCenterAndRadius( new Position(49.619335, 20.698595), Distance.FromMiles(0.75))) { IsShowingUser = true, VerticalOptions = LayoutOptions.FillAndExpand }; var position1 = new Position(49.625150, 20.692775); var position2 = new Position(49.625247, 20.690861); var position3 = new Position(49.628702, 20.689008); var position4 = new Position(49.628726, 20.690247); var position5 = new Position(49.620495, 20.694799); var position6 = new Position(49.616928, 20.704588); var position7 = new Position(49.606776, 20.702306); //Pkp var position8 = new Position(49.626263, 20.690385); //Rezydencja var position9 = new Position(49.627790, 20.690492); //synagoga var position10 = new Position(49.625014, 20.693392); //dom gotycki var position11 = new Position(49.623370, 20.692184); //kapliczka var position12 = new Position(49.622277, 20.695019); //Sokół var pin1 = new Pin { Type = PinType.Place, Position = position1, Label = "Bazylika", Address = "www.intilaq.tn", }; var pin2 = new Pin { Type = PinType.Place, Position = position2, Label = "Ratusz", Address = "www.groupe-telnet.com" }; var pin3 = new Pin { Type = PinType.Place, Position = position3, Label = "Ruiny Zamku Królewskiego", Address = "www.kromberg-schubert.com" }; var pin4 = new Pin { Type = PinType.Place, Position = position4, Label = "Zegar kwiatowy", Address = "www.kromberg-schubert.com" }; var pin5 = new Pin { Type = PinType.Place, Position = position5, Label = "Planty", Address = "Planty " }; var pin6 = new Pin { Type = PinType.Place, Position = position6, Label = "Cmentarz Komunalny", Address = "www.kromberg-schubert.com" }; var pin7 = new Pin { Type = PinType.Place, Position = position7, Label = "Dworzec PKP", Address = "www.intilaq.tn", }; var pin8 = new Pin { Type = PinType.Place, Position = position8, Label = "Rezydencja Lubomirskich", Address = "www.groupe-telnet.com" }; var pin9 = new Pin { Type = PinType.Place, Position = position9, Label = "Dawna Synagoga", Address = "www.kromberg-schubert.com" }; var pin10 = new Pin { Type = PinType.Place, Position = position10, Label = "Dom Gotycki", Address = "www.kromberg-schubert.com" }; var pin11 = new Pin { Type = PinType.Place, Position = position11, Label = "Kapliczka Szwedzka", Address = "Planty " }; var pin12 = new Pin { Type = PinType.Place, Position = position12, Label = "Sokół", Address = "www.kromberg-schubert.com" }; map.Pins.Add(pin1); map.Pins.Add(pin2); map.Pins.Add(pin3); map.Pins.Add(pin4); map.Pins.Add(pin5); map.Pins.Add(pin6); map.Pins.Add(pin7); map.Pins.Add(pin8); map.Pins.Add(pin9); map.Pins.Add(pin10); map.Pins.Add(pin11); map.Pins.Add(pin12); Content = map; }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } if (Name != null) { hashCode = hashCode * 59 + Name.GetHashCode(); } if (ActivityType != null) { hashCode = hashCode * 59 + ActivityType.GetHashCode(); } if (Distance != null) { hashCode = hashCode * 59 + Distance.GetHashCode(); } if (AverageGrade != null) { hashCode = hashCode * 59 + AverageGrade.GetHashCode(); } if (MaximumGrade != null) { hashCode = hashCode * 59 + MaximumGrade.GetHashCode(); } if (ElevationHigh != null) { hashCode = hashCode * 59 + ElevationHigh.GetHashCode(); } if (ElevationLow != null) { hashCode = hashCode * 59 + ElevationLow.GetHashCode(); } if (StartLatlng != null) { hashCode = hashCode * 59 + StartLatlng.GetHashCode(); } if (EndLatlng != null) { hashCode = hashCode * 59 + EndLatlng.GetHashCode(); } if (ClimbCategory != null) { hashCode = hashCode * 59 + ClimbCategory.GetHashCode(); } if (City != null) { hashCode = hashCode * 59 + City.GetHashCode(); } if (State != null) { hashCode = hashCode * 59 + State.GetHashCode(); } if (Country != null) { hashCode = hashCode * 59 + Country.GetHashCode(); } if (_Private != null) { hashCode = hashCode * 59 + _Private.GetHashCode(); } if (AthletePrEffort != null) { hashCode = hashCode * 59 + AthletePrEffort.GetHashCode(); } if (AthleteSegmentStats != null) { hashCode = hashCode * 59 + AthleteSegmentStats.GetHashCode(); } return(hashCode); } }
public void SolvePoissonMatrixAndBackMultiply() { // Create the matrix var matrix = new SparseMatrix(100); // Assemble the matrix. We assume we're solving the Poisson equation // on a rectangular 10 x 10 grid const int GridSize = 10; // The pattern is: // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0 for (var i = 0; i < matrix.RowCount; i++) { // Insert the first set of -1's if (i > (GridSize - 1)) { matrix[i, i - GridSize] = -1; } // Insert the second set of -1's if (i > 0) { matrix[i, i - 1] = -1; } // Insert the centerline values matrix[i, i] = 4; // Insert the first trailing set of -1's if (i < matrix.RowCount - 1) { matrix[i, i + 1] = -1; } // Insert the second trailing set of -1's if (i < matrix.RowCount - GridSize) { matrix[i, i + GridSize] = -1; } } // Create the y vector var y = Vector <Complex> .Build.Dense(matrix.RowCount, 1); // Create an iteration monitor which will keep track of iterative convergence var monitor = new Iterator <Complex>( new IterationCountStopCriterion <Complex>(MaximumIterations), new ResidualStopCriterion <Complex>(ConvergenceBoundary), new DivergenceStopCriterion <Complex>(), new FailureStopCriterion <Complex>()); var solver = new TFQMR(); // Solve equation Ax = y var x = matrix.SolveIterative(y, solver, monitor); // Now compare the results Assert.IsNotNull(x, "#02"); Assert.AreEqual(y.Count, x.Count, "#03"); // Back multiply the vector var z = matrix.Multiply(x); // Check that the solution converged Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04"); // Now compare the vectors Assert.LessOrEqual(Distance.Chebyshev(y, z), 2 * ConvergenceBoundary); }
protected override async void OnAppearing() { base.OnAppearing(); var position = await CrossGeolocator.Current.GetPositionAsync(); MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(0.1))); }
//private async void OnMatchAddressTapped(object sender, EventArgs e) //{ // if (Reachability.InternetConnectionStatus() != ReachabilityNetworkStatus.NotReachable) // { // //API Call to Match Address // await AppData.API.UtilityByAddresses(AppData.PropertyModel.SelectedProperty.Address.RawAddress); // if (AddNewCaseView.UtilityAddressesByAdd == null) return; // if (AddNewCaseView.UtilityAddressesByAdd.Results > 0) // { // //Open Exist Add Case View // await SplitView.Instace().PushRightContent(UpdateNewCase = new AddNewCaseView()); // } // else // await SplitView.DisplayAlert("Invalid Address Selected", "No Data Retrieved. Please try another location", "Ok",null); // } //} /// <summary> /// Loads the map content on the right side for the specific platform. /// </summary> /// <returns></returns> private void Update() { try { if (Device.OS == TargetPlatform.Android) { // AppContext.AppContext.MapView = new AndroidMapView(); SplitView.MapView?.ClearPin(); if (AppData.PropertyModel.SelectedProperty.HasValidCoords) { Gl_CaseSummary.Children.Add((AndroidMapView)SplitView.MapView, 0, 0); AndroidMapView.HideLocator(); var googleMapPin = MapViewModel.GetCustomePin(); if (googleMapPin != null) { SplitView.MapView?.LoadPin(googleMapPin); } } } else { //AppContext.AppContext.MapView = new WindowsMapView(); if (AppData.PropertyModel.SelectedProperty.HasValidCoords) { var windowMapPin = MapViewModel.GetCurrentPin(); if (windowMapPin != null) { AppContext.AppContext.MapView?.MoveToRegion( new Position(windowMapPin.Pin.Position.Latitude, windowMapPin.Pin.Position.Longitude), Distance.FromKilometers(0.3)); } } Gl_CaseSummary.Children.Add((WindowsMapView)AppContext.AppContext.MapView, 0, 0); } ShowDetails(); } catch (Exception ex) { LogTracking.LogTrace(ex.ToString()); } }
// Use this for initialization void Start() { Distance d = new Distance("potato"); }
public async void obtenerDatosDelServicioZonasTrabajoAsync(int codigoUsuario) { googleMaps.Circles.Clear(); googleMaps.Pins.Clear(); String IP_LEGAL = App.Current.Properties["IpPublicado"].ToString(); Zonas zonas = new Zonas(); String url = IP_LEGAL + "/legal/ZonaTrabajo/ZonaTrabajoListarJsonExterno?id=" + codigoUsuario; var content = await _Client.GetStringAsync(url); var service = new RestClient <Zonas>(); zonas = await service.GetRestServicieDataAsync(url); bool habilitarAcceso = false; int userObtenerID = 0; int codigoZonaTrabajo = 0; double distance = 0.0d; const double metersInKm = 1000.0d; for (int i = 0; i < zonas.zonas.Length; i++) { var position = new Position(zonas.zonas[i].Latitud, zonas.zonas[i].Longitud); googleMaps.Pins.Add(new Pin { Position = position, Label = zonas.zonas[i].Direccion }); circle = new Circle(); circle.IsClickable = true; circle.Center = position; circle.Radius = Distance.FromMeters(zonas.zonas[i].Radio); circle.StrokeColor = Color.SaddleBrown; circle.StrokeWidth = 3f; //circle.FillColor = Color.FromRgba(0, 0, 255, 32); //error intensifica el color por cada peticion circle.FillColor = Color.Transparent; circle.Tag = zonas.zonas[i].Direccion; // Can set any object googleMaps.Circles.Add(circle); distance = Location.CalculateDistance(userCurrentlocation, position.Latitude, position.Longitude, DistanceUnits.Kilometers);//this result give in KM distance = distance * metersInKm; userObtenerID = zonas.zonas[i].UsuarioID; if (distance < zonas.zonas[i].Radio && codigoUsuario.Equals(userObtenerID)) { habilitarAcceso = true; codigoZonaTrabajo = zonas.zonas[i].ZonaTrabajoId; } else { habilitarAcceso = (habilitarAcceso) ? habilitarAcceso : false; } } String situacion = "0"; bool existeUsuario = false; for (int i = 0; i < zonas.zonas.Length; i++) { if (zonas.zonas[i].UsuarioID.Equals(codigoUsuario)) { existeUsuario = true; break; } } if (existeUsuario == false) { situacion = " sin Zona de Trabajo asignado"; } else { situacion = habilitarAcceso ? " Acceso Habilitado y Zona: " + codigoZonaTrabajo : "Se encuentra fuera de una Zona de Trabajo asignado"; } String mensaje = "Usuario " + situacion; //Si no hay zonas de Trabajo con ese usario no guarda su historial if (existeUsuario == false) { mensajeEstaDentroZonaUsuarioAsync(mensaje, existeUsuario, habilitarAcceso); } else { Position positionGMaps = new Position(userCurrentlocation.Latitude, userCurrentlocation.Longitude); Geocoder geocoder = new Geocoder(); IEnumerable <string> address = await geocoder.GetAddressesForPositionAsync(positionGMaps); var pais = "4"; var ciudad = "2"; var direccion = "0"; direccion = address.ElementAt(0); ciudad = address.ElementAt(2); pais = address.ElementAt(4); string imei = CrossDeviceInfo.Current.Id; HistorialAccesoInsertarJsonExternoAsync(codigoUsuario, imei, userCurrentlocation.Latitude, userCurrentlocation.Longitude, pais, ciudad, direccion); if (habilitarAcceso) { habilitarAccesoAZonaTrabajoUsuarioAsync(codigoZonaTrabajo, "1"); obtenerTokenDelUsuarioAsync(codigoUsuario); } else { //habilitarAccesoAZonaTrabajoUsuario(codigoZonaTrabajo,"0"); labelToken.Text = "Token"; if (_timer.Enabled) { _timer.Stop(); labelTokenTiempoRestante.Text = "tiempo restante"; } } mensajeEstaDentroZonaUsuarioAsync(mensaje, existeUsuario, habilitarAcceso); } }
private async void OnSearchEntryCompleted(object sender, EventArgs e) { this.SearchEntry.Unfocus(); if (String.IsNullOrEmpty(this.SearchEntry.Text) || String.IsNullOrWhiteSpace(this.SearchEntry.Text)) { return; } if (!CrossConnectivity.Current.IsConnected) { DependencyService.Get <IMessageHelper>().LongAlert($"Gagal memuat. Periksa kembali koneksi internet anda."); return; } AutoCompleteLocationResult results = null; try { results = await AutoCompleteLocationService.GetPlaces(this.SearchEntry.Text); } catch (Exception ex) { await this.DisplayAlert("Error", ex.Message, "OK"); return; } if (results == null) { await this.DisplayAlert("Lokasi Tidak Ditemukan", "Geocoder tidak dapat menemukan lokasi yang anda tuju.", "OK"); return; } this.MyMap.Pins.Clear(); Location location = await AutoCompleteLocationService.GetPlace(results.AutoCompletePlaces.First().Place_ID); Position position = new Position( location.Latitude, location.Longitude); Pin locatedPin = new Pin() { Type = PinType.Place, Label = this.SearchEntry.Text, Address = this.SearchEntry.Text, Position = position, Flat = true }; this.MyMap.Pins.Add(locatedPin); this.MyMap.MoveToRegion( MapSpan.FromCenterAndRadius( position, Distance.FromMeters( MAP_SPAN_RADIUS))); var pins = await CreatePins(position); foreach (Pin pin in pins) { this.MyMap.Pins.Add(pin); } }
/// <summary> /// Returns true if SummarySegment instances are equal /// </summary> /// <param name="other">Instance of SummarySegment to be compared</param> /// <returns>Boolean</returns> public bool Equals(SummarySegment other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( ActivityType == other.ActivityType || ActivityType != null && ActivityType.Equals(other.ActivityType) ) && ( Distance == other.Distance || Distance != null && Distance.Equals(other.Distance) ) && ( AverageGrade == other.AverageGrade || AverageGrade != null && AverageGrade.Equals(other.AverageGrade) ) && ( MaximumGrade == other.MaximumGrade || MaximumGrade != null && MaximumGrade.Equals(other.MaximumGrade) ) && ( ElevationHigh == other.ElevationHigh || ElevationHigh != null && ElevationHigh.Equals(other.ElevationHigh) ) && ( ElevationLow == other.ElevationLow || ElevationLow != null && ElevationLow.Equals(other.ElevationLow) ) && ( StartLatlng == other.StartLatlng || StartLatlng != null && StartLatlng.Equals(other.StartLatlng) ) && ( EndLatlng == other.EndLatlng || EndLatlng != null && EndLatlng.Equals(other.EndLatlng) ) && ( ClimbCategory == other.ClimbCategory || ClimbCategory != null && ClimbCategory.Equals(other.ClimbCategory) ) && ( City == other.City || City != null && City.Equals(other.City) ) && ( State == other.State || State != null && State.Equals(other.State) ) && ( Country == other.Country || Country != null && Country.Equals(other.Country) ) && ( _Private == other._Private || _Private != null && _Private.Equals(other._Private) ) && ( AthletePrEffort == other.AthletePrEffort || AthletePrEffort != null && AthletePrEffort.Equals(other.AthletePrEffort) ) && ( AthleteSegmentStats == other.AthleteSegmentStats || AthleteSegmentStats != null && AthleteSegmentStats.Equals(other.AthleteSegmentStats) )); }
/// <summary> /// Calculates the radial contour. /// </summary> /// <param name="startLocation">The start location.</param> /// <param name="distance">The distance.</param> /// <returns>returns List{Location}.</returns> private static List <Location> CalculateRadialContour(Location startLocation, Distance distance) { // rotating azimuth at 1 degree intervals List <Location> deltaLocations = new List <Location>(); for (int azimuth = 0; azimuth <= 360; azimuth++) { var deltaCoord = GeoCalculations.GetLocationTowardsBearing(startLocation, distance, azimuth); deltaLocations.Add(deltaCoord); } return(deltaLocations); }
/// <summary> /// Detect BoxPlane Collisions. /// </summary> /// <param name="info"></param> /// <param name="collTolerance"></param> /// <param name="collisionFunctor"></param> public override void CollDetect(CollDetectInfo info, float collTolerance, CollisionFunctor collisionFunctor) { if (info.Skin0.GetPrimitiveOldWorld(info.IndexPrim0).Type == this.Type1) { CollisionSkin skinSwap = info.Skin0; info.Skin0 = info.Skin1; info.Skin1 = skinSwap; int primSwap = info.IndexPrim0; info.IndexPrim0 = info.IndexPrim1; info.IndexPrim1 = primSwap; } Vector3 body0Pos = (info.Skin0.Owner != null) ? info.Skin0.Owner.OldPosition : Vector3.Zero; Vector3 body1Pos = (info.Skin1.Owner != null) ? info.Skin1.Owner.OldPosition : Vector3.Zero; Box oldBox = info.Skin0.GetPrimitiveOldWorld(info.IndexPrim0) as Box; Box newBox = info.Skin0.GetPrimitiveNewWorld(info.IndexPrim0) as Box; JPlane oldPlane = info.Skin1.GetPrimitiveOldWorld(info.IndexPrim1) as JPlane; JPlane newPlane = info.Skin1.GetPrimitiveNewWorld(info.IndexPrim1) as JPlane; Matrix4 newPlaneInvTransform = newPlane.InverseTransformMatrix; Vector3 newBoxCen = Vector3.Transform(newBox.GetCentre(), newPlaneInvTransform); // quick check float centreDist = Distance.PointPlaneDistance(newBoxCen, newPlane); if (centreDist > collTolerance + newBox.GetBoundingRadiusAroundCentre()) { return; } Matrix4 oldPlaneInvTransform = oldPlane.InverseTransformMatrix; Vector3[] newPts; newBox.GetCornerPoints(out newPts); Vector3[] oldPts; oldBox.GetCornerPoints(out oldPts); unsafe { #if USE_STACKALLOC SmallCollPointInfo *collPts = stackalloc SmallCollPointInfo[MaxLocalStackSCPI]; #else SmallCollPointInfo[] collPtArray = SCPIStackAlloc(); fixed(SmallCollPointInfo *collPts = collPtArray) #endif { int numCollPts = 0; for (int i = 0; i < 8; ++i) { Vector3.Transform(ref oldPts[i], ref oldPlaneInvTransform, out oldTransPts[i]); Vector3.Transform(ref newPts[i], ref newPlaneInvTransform, out newPts[i]); float oldDepth = -Distance.PointPlaneDistance(ref oldTransPts[i], oldPlane); float newDepth = -Distance.PointPlaneDistance(ref newPts[i], newPlane); if (OpenTKHelper.Max(oldDepth, newDepth) > -collTolerance) { if (numCollPts < MaxLocalStackSCPI) { // BEN-OPTIMISATION: Now reuses instead of reallocating. collPts[numCollPts].R0 = oldPts[i] - body0Pos; collPts[numCollPts].R1 = oldPts[i] - body1Pos; collPts[numCollPts++].InitialPenetration = oldDepth; } } } if (numCollPts > 0) { collisionFunctor.CollisionNotify(ref info, ref oldPlane.normal, collPts, numCollPts); } } #if !USE_STACKALLOC FreeStackAlloc(collPtArray); #endif } }
public PinsPage() { InitializeComponent(); Pin pinTokyo = null; Pin pinNewYork = null; // Tokyo pin buttonAddPinTokyo.Clicked += (sender, e) => { pinTokyo = new Pin() { Type = PinType.Place, Label = "Tokyo SKYTREE", Address = "Sumida-ku, Tokyo, Japan", Position = new Position(35.71d, 139.81d), Rotation = 33.3f, Tag = "id_tokyo" }; map.Pins.Add(pinTokyo); map.MoveToRegion(MapSpan.FromCenterAndRadius(pinTokyo.Position, Distance.FromMeters(5000))); ((Button)sender).IsEnabled = false; buttonRemovePinTokyo.IsEnabled = true; }; buttonRemovePinTokyo.Clicked += (sender, e) => { map.Pins.Remove(pinTokyo); pinTokyo = null; ((Button)sender).IsEnabled = false; buttonAddPinTokyo.IsEnabled = true; }; buttonRemovePinTokyo.IsEnabled = false; // New York pin buttonAddPinNewYork.Clicked += (sender, e) => { pinNewYork = new Pin() { Type = PinType.Place, Label = "Central Park NYC", Address = "New York City, NY 10022", Position = new Position(40.78d, -73.96d), Tag = "id_new_york" }; map.Pins.Add(pinNewYork); map.MoveToRegion(MapSpan.FromCenterAndRadius(pinNewYork.Position, Distance.FromMeters(5000))); ((Button)sender).IsEnabled = false; buttonRemovePinNewYork.IsEnabled = true; }; buttonRemovePinNewYork.Clicked += (sender, e) => { map.Pins.Remove(pinNewYork); pinNewYork = null; ((Button)sender).IsEnabled = false; buttonAddPinNewYork.IsEnabled = true; }; buttonRemovePinNewYork.IsEnabled = false; // Clear Pins buttonClearPins.Clicked += (sender, e) => { map.Pins.Clear(); pinTokyo = null; pinNewYork = null; buttonAddPinTokyo.IsEnabled = true; buttonAddPinNewYork.IsEnabled = true; buttonRemovePinTokyo.IsEnabled = false; buttonRemovePinNewYork.IsEnabled = false; }; // Select New York Pin buttonSelectPinNewYork.Clicked += (sender, e) => { if (pinNewYork == null) { DisplayAlert("Error", "New York is not added.", "Close"); return; } map.SelectedPin = pinNewYork; }; // Clear Pin Selection buttonClearSelection.Clicked += (sender, e) => { if (map.SelectedPin == null) { DisplayAlert("Error", "Pin is not selected.", "Close"); return; } map.SelectedPin = null; }; map.PinClicked += Map_PinClicked;; // Selected Pin changed map.SelectedPinChanged += SelectedPin_Changed; map.InfoWindowClicked += InfoWindow_Clicked; }
private async Task populateMap(List <Person> people) { mapLocsProperties.Clear(); mapRef.Pins.Clear(); double avgLat = 0; double avgLong = 0; double minLat = 90; double maxLat = -90; double minLong = 180; double maxLong = -180; foreach (Person person in people) { //Person person = await DataStore.GetItemAsync(ids[0]); //Person person = people.FirstOrDefault(p => p.Id == id); string address = person.Address.ToString(); try { Location location = await GeocodeThis(address); locs.Add(location); Pin apin = new Pin() { Position = new Position(location.Latitude, location.Longitude), Label = person.Name }; if (location.Latitude > maxLat) { maxLat = location.Latitude; } if (location.Latitude < minLat) { minLat = location.Latitude; } if (location.Longitude > maxLong) { maxLong = location.Longitude; } if (location.Longitude < minLong) { minLong = location.Longitude; } //avgLat += location.Latitude; //avgLong += location.Longitude; mapRef.Pins.Add(apin); mapLocsProperties.Add(new MapLocation(address, person.Name, new Position(location.Latitude, location.Longitude))); //TODO Map by name } catch (Exception ex) { Console.WriteLine($"Exception:{ex} Outside Geocoding"); } } var dist = Location.CalculateDistance(maxLat, maxLong, minLat, minLong, DistanceUnits.Kilometers) / 2; avgLat = (maxLat - minLat) / 2 + minLat; avgLong = (maxLong - minLong) / 2 + minLong; Console.WriteLine("{maxLat}, {minLat}, {maxLong}, {minLong}, {dist}, {avgLat}, {avgLong}"); Console.WriteLine($"{maxLat}, {minLat}, {maxLong}, {minLong}, {dist}, {avgLat}, {avgLong}"); //avgLat /= mapLocsProperties.Count; //avgLong /= mapLocsProperties.Count; Console.WriteLine($"{avgLat}, {avgLong}, {mapLocsProperties.Count}"); //new Position(avgLat, avgLong);mapLocsProperties[0].Position mapRef.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(avgLat, avgLong), Distance.FromKilometers(dist > 20?dist:20))); //Console.WriteLine($"Check Formating: \n{address}"); }
public override string ToString() { return(MarkingTextType.ToString() + " = " + Distance.ToString().Replace(',', '.') + "," + Text + "," + TurnText); }
static void GeoFence_Tests() { // CHANGE LATS e LONS Coordinate c1 = new Coordinate(31.66, -106.52); Coordinate c2 = new Coordinate(31.64, -106.53); Coordinate c3 = new Coordinate(42.02, -106.52); Coordinate c4 = new Coordinate(42.03, -106.53); List <GeoFence.Point> points = new List <GeoFence.Point>(); points.Add(new GeoFence.Point(31.65, -106.52)); points.Add(new GeoFence.Point(31.65, -84.02)); points.Add(new GeoFence.Point(42.03, -84.02)); points.Add(new GeoFence.Point(42.03, -106.52)); points.Add(new GeoFence.Point(31.65, -106.52)); GeoFence gf = new GeoFence(points); bool pass = true; if (gf.IsPointInPolygon(c1)) { pass = false; } if (gf.IsPointInPolygon(c2)) { pass = false; } if (gf.IsPointInPolygon(c3)) { pass = false; } if (gf.IsPointInPolygon(c4)) { pass = false; } Write_Pass("Outside Polygon: ", pass); c1 = new Coordinate(31.67, -106.51); c2 = new Coordinate(31.67, -84.03); c3 = new Coordinate(42.01, -106.51); c4 = new Coordinate(42.01, -84.03); pass = true; if (!gf.IsPointInPolygon(c1)) { pass = false; } if (!gf.IsPointInPolygon(c2)) { pass = false; } if (!gf.IsPointInPolygon(c3)) { pass = false; } if (!gf.IsPointInPolygon(c4)) { pass = false; } Write_Pass("Inside Polygon: ", pass); pass = true; Distance d = new Distance(1000, DistanceType.Meters); if (!gf.IsPointInRangeOfLine(c1, 1000)) { pass = false; } if (!gf.IsPointInRangeOfLine(c1, d)) { pass = false; } Write_Pass("In Range of Polyline: ", pass); pass = true; d = new Distance(900, DistanceType.Meters); if (gf.IsPointInRangeOfLine(c1, 900)) { pass = false; } if (gf.IsPointInRangeOfLine(c1, d)) { pass = false; } Write_Pass("Out of Range of Polyline: ", pass); }
public MyCustomFilter(FeatureGeometry geometry, Distance innerDistance, Distance outerDistance) : base(geometry) { _distanceInner = innerDistance; _distanceOuter = outerDistance; }
internal static void CollDetectSphereStaticMeshSweep(BoundingSphere oldSphere, BoundingSphere newSphere, TriangleMesh mesh, CollDetectInfo info, float collTolerance, CollisionFunctor collisionFunctor) { // really use a swept test - or overlap? Vector3 delta = newSphere.Center - oldSphere.Center; if (delta.LengthSquared() < (0.25f * newSphere.Radius * newSphere.Radius)) { CollDetectSphereStaticMeshOverlap(oldSphere, newSphere, mesh, info, collTolerance, collisionFunctor); } else { Vector3 body0Pos = (info.Skin0.Owner != null) ? info.Skin0.Owner.OldPosition : Vector3.Zero; Vector3 body1Pos = (info.Skin1.Owner != null) ? info.Skin1.Owner.OldPosition : Vector3.Zero; float sphereTolR = collTolerance + oldSphere.Radius; float sphereToR2 = sphereTolR * sphereTolR; Vector3 collNormal = Vector3.Zero; BoundingBox bb = BoundingBoxHelper.InitialBox; BoundingBoxHelper.AddSphere(oldSphere, ref bb); BoundingBoxHelper.AddSphere(newSphere, ref bb); // get the spheres centers in triangle mesh space Vector3 newSphereCen = Vector3.Transform(newSphere.Center, mesh.InverseTransformMatrix); Vector3 oldSphereCen = Vector3.Transform(oldSphere.Center, mesh.InverseTransformMatrix); unsafe { #if USE_STACKALLOC SmallCollPointInfo *collPts = stackalloc SmallCollPointInfo[MaxLocalStackSCPI]; int *potentialTriangles = stackalloc int[MaxLocalStackTris]; { { #else SmallCollPointInfo[] collPtArray = SCPIStackAlloc(); fixed(SmallCollPointInfo *collPts = collPtArray) { int[] potTriArray = IntStackAlloc(); fixed(int *potentialTriangles = potTriArray) { #endif int numCollPts = 0; int numTriangles = mesh.GetTrianglesIntersectingtAABox(potentialTriangles, MaxLocalStackTris, ref bb); for (int iTriangle = 0; iTriangle < numTriangles; ++iTriangle) { // first test the old sphere for being on the wrong side IndexedTriangle meshTriangle = mesh.GetTriangle(potentialTriangles[iTriangle]); float distToCentreOld = meshTriangle.Plane.DotCoordinate(oldSphereCen); if (distToCentreOld <= 0.0f) { continue; } // now test the new sphere for being clear float distToCentreNew = meshTriangle.Plane.DotCoordinate(newSphereCen); if (distToCentreNew > sphereTolR) { continue; } int i0, i1, i2; meshTriangle.GetVertexIndices(out i0, out i1, out i2); Triangle triangle = new Triangle(mesh.GetVertex(i0), mesh.GetVertex(i1), mesh.GetVertex(i2)); // If the old sphere is intersecting, just use that result float s, t; float d2 = Distance.PointTriangleDistanceSq(out s, out t, oldSphereCen, triangle); if (d2 < sphereToR2) { float dist = (float)System.Math.Sqrt(d2); float depth = oldSphere.Radius - dist; Vector3 triangleN = triangle.Normal; Vector3 normSafe = oldSphereCen - triangle.GetPoint(s, t); JiggleMath.NormalizeSafe(ref normSafe); Vector3 collisionN = (dist > float.Epsilon) ? normSafe : triangleN; // since impulse gets applied at the old position Vector3 pt = oldSphere.Center - oldSphere.Radius * collisionN; if (numCollPts < MaxLocalStackSCPI) { collPts[numCollPts++] = new SmallCollPointInfo(pt - body0Pos, pt - body1Pos, depth); } collNormal += collisionN; } else if (distToCentreNew < distToCentreOld) { // old sphere is not intersecting - do a sweep, but only if the sphere is moving into the // triangle Vector3 pt, N; // CHECK THIS float depth; if (Intersection.SweptSphereTriangleIntersection(out pt, out N, out depth, oldSphere, newSphere, triangle, distToCentreOld, distToCentreNew, Intersection.EdgesToTest.EdgeAll, Intersection.CornersToTest.CornerAll)) { // collision point etc must be relative to the old position because that's //where the impulses are applied float dist = (float)System.Math.Sqrt(d2); float depth2 = oldSphere.Radius - dist; Vector3 triangleN = triangle.Normal; Vector3 normSafe = oldSphereCen - triangle.GetPoint(s, t); JiggleMath.NormalizeSafe(ref normSafe); Vector3 collisionN = (dist > JiggleMath.Epsilon) ? normSafe : triangleN; // since impulse gets applied at the old position Vector3 pt2 = oldSphere.Center - oldSphere.Radius * collisionN; if (numCollPts < MaxLocalStackSCPI) { collPts[numCollPts++] = new SmallCollPointInfo(pt2 - body0Pos, pt2 - body1Pos, depth); } collNormal += collisionN; } } } if (numCollPts > 0) { JiggleMath.NormalizeSafe(ref collNormal); collisionFunctor.CollisionNotify(ref info, ref collNormal, collPts, numCollPts); } } #if USE_STACKALLOC } } #else FreeStackAlloc(potTriArray); } FreeStackAlloc(collPtArray); } #endif } }
public MainPage() { InitializeComponent(); customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(53.010281, 18.604922), Distance.FromMiles(1.0))); }
public static void CollDetectSphereStaticMeshOverlap(BoundingSphere oldSphere, BoundingSphere newSphere, TriangleMesh mesh, CollDetectInfo info, float collTolerance, CollisionFunctor collisionFunctor) { Vector3 body0Pos = (info.Skin0.Owner != null) ? info.Skin0.Owner.OldPosition : Vector3.Zero; Vector3 body1Pos = (info.Skin1.Owner != null) ? info.Skin1.Owner.OldPosition : Vector3.Zero; float sphereTolR = collTolerance + newSphere.Radius; float sphereTolR2 = sphereTolR * sphereTolR; unsafe { #if USE_STACKALLOC SmallCollPointInfo *collPts = stackalloc SmallCollPointInfo[MaxLocalStackSCPI]; int *potentialTriangles = stackalloc int[MaxLocalStackTris]; { { #else SmallCollPointInfo[] collPtArray = SCPIStackAlloc(); fixed(SmallCollPointInfo *collPts = collPtArray) { int[] potTriArray = IntStackAlloc(); fixed(int *potentialTriangles = potTriArray) { #endif int numCollPts = 0; Vector3 collNormal = Vector3.Zero; BoundingBox bb = BoundingBoxHelper.InitialBox; BoundingBoxHelper.AddSphere(newSphere, ref bb); int numTriangles = mesh.GetTrianglesIntersectingtAABox(potentialTriangles, MaxLocalStackTris, ref bb); // Deano : get the spheres centers in triangle mesh space Vector3 newSphereCen = Vector3.Transform(newSphere.Center, mesh.InverseTransformMatrix); Vector3 oldSphereCen = Vector3.Transform(oldSphere.Center, mesh.InverseTransformMatrix); for (int iTriangle = 0; iTriangle < numTriangles; ++iTriangle) { IndexedTriangle meshTriangle = mesh.GetTriangle(potentialTriangles[iTriangle]); float distToCentre = meshTriangle.Plane.DotCoordinate(newSphereCen); if (distToCentre <= 0.0f) { continue; } if (distToCentre >= sphereTolR) { continue; } int i0, i1, i2; meshTriangle.GetVertexIndices(out i0, out i1, out i2); Triangle triangle = new Triangle(mesh.GetVertex(i0), mesh.GetVertex(i1), mesh.GetVertex(i2)); float s, t; float newD2 = Distance.PointTriangleDistanceSq(out s, out t, newSphereCen, triangle); if (newD2 < sphereTolR2) { // have overlap - but actually report the old intersection float oldD2 = Distance.PointTriangleDistanceSq(out s, out t, oldSphereCen, triangle); float dist = (float)System.Math.Sqrt((float)oldD2); float depth = oldSphere.Radius - dist; Vector3 triPointSTNorm = oldSphereCen - triangle.GetPoint(s, t); JiggleMath.NormalizeSafe(ref triPointSTNorm); Vector3 collisionN = (dist > float.Epsilon) ? triPointSTNorm : triangle.Normal; // since impulse get applied at the old position Vector3 pt = oldSphere.Center - oldSphere.Radius * collisionN; if (numCollPts < MaxLocalStackSCPI) { collPts[numCollPts++] = new SmallCollPointInfo(pt - body0Pos, pt - body1Pos, depth); } collNormal += collisionN; } } if (numCollPts > 0) { JiggleMath.NormalizeSafe(ref collNormal); collisionFunctor.CollisionNotify(ref info, ref collNormal, collPts, numCollPts); } #if USE_STACKALLOC } } #else FreeStackAlloc(potTriArray); } FreeStackAlloc(collPtArray); } #endif } }
/// <summary> /// Calculate contours from given incumbent and parent incumbent locations /// </summary> /// <param name="sourceContour">portal contours</param> /// <returns>contours data</returns> private static string GetContourPoints(PortalContour sourceContour) { lock (portalContourLock) { Location stationLocation = new Location(sourceContour.Latitude, sourceContour.Longitude); Distance sameChannelKeyHoleDistance = new Distance(80, DistanceUnit.KM); // 80 km (outer keyhole) Distance sameChannelDistance = new Distance(8, DistanceUnit.KM); // 8 km (inner keyhole) Location parentLocation = new Location(sourceContour.ParentLatitude, sourceContour.ParentLongitude); var stationToParentTxBearing = GeoCalculations.CalculateBearing(stationLocation, parentLocation); // keyhole calculations var keyHoleArcStarting = stationToParentTxBearing - 30; var keyHoleArcEnding = stationToParentTxBearing + 30; if (keyHoleArcStarting > 360) { keyHoleArcStarting = keyHoleArcStarting - 360; } if (keyHoleArcEnding > 360) { keyHoleArcEnding = keyHoleArcEnding - 360; } if (keyHoleArcStarting < 0) { keyHoleArcStarting = keyHoleArcStarting + 360; } if (keyHoleArcEnding < 0) { keyHoleArcEnding = keyHoleArcEnding + 360; } List <Location> contourPoints = CalculateRadialContour(stationLocation, sameChannelDistance); List <Location> keyHolePoints = CalculateRadialContour(stationLocation, sameChannelKeyHoleDistance); if (keyHoleArcStarting < keyHoleArcEnding) { for (int i = (int)keyHoleArcStarting; i < (int)keyHoleArcEnding; i++) { contourPoints[i] = keyHolePoints[i]; } } else { for (int i = (int)keyHoleArcStarting; i <= 360; i++) { contourPoints[i] = keyHolePoints[i]; } for (int i = (int)0; i <= (int)keyHoleArcEnding; i++) { contourPoints[i] = keyHolePoints[i]; } } StringBuilder contourBuilder = new StringBuilder(); foreach (Location point in contourPoints) { contourBuilder.Append(point.Latitude); contourBuilder.Append(" "); contourBuilder.Append(point.Longitude); contourBuilder.Append(" "); } return(contourBuilder.ToString().Trim()); } }
/// <summary> /// Creates a JSON string that represents the motor's serialized state. We /// do this since Unity can't handle putting lists of derived objects into /// prefabs. /// </summary> /// <returns>JSON string representing the object</returns> public virtual string SerializeMotor() { if (_Type.Length == 0) { _Type = this.GetType().AssemblyQualifiedName; } StringBuilder lStringBuilder = new StringBuilder(); lStringBuilder.Append("{"); // These four properties are important from the base MotionControllerMotion lStringBuilder.Append(", \"Type\" : \"" + _Type + "\""); lStringBuilder.Append(", \"Name\" : \"" + _Name + "\""); lStringBuilder.Append(", \"IsEnabled\" : \"" + _IsEnabled.ToString() + "\""); lStringBuilder.Append(", \"ActionAlias\" : \"" + _ActionAlias.ToString() + "\""); lStringBuilder.Append(", \"UseRigAnchor\" : \"" + _UseRigAnchor.ToString() + "\""); lStringBuilder.Append(", \"AnchorIndex\" : \"" + _AnchorIndex.ToString() + "\""); lStringBuilder.Append(", \"AnchorOffset\" : \"" + _AnchorOffset.ToString("G8") + "\""); lStringBuilder.Append(", \"Offset\" : \"" + _Offset.ToString("G8") + "\""); lStringBuilder.Append(", \"Distance\" : \"" + Distance.ToString("f5") + "\""); lStringBuilder.Append(", \"MaxDistance\" : \"" + MaxDistance.ToString("f5") + "\""); lStringBuilder.Append(", \"IsCollisionEnabled\" : \"" + _IsCollisionEnabled.ToString() + "\""); lStringBuilder.Append(", \"IsFadingEnabled\" : \"" + _IsFadingEnabled.ToString() + "\""); lStringBuilder.Append(", \"SpecifyFadeRenderers\" : \"" + _SpecifyFadeRenderers.ToString() + "\""); lStringBuilder.Append(", \"FadeTransformIndexes\" : \"" + string.Join(",", _FadeTransformIndexes.Select(n => n.ToString()).ToArray()) + "\""); // Cycle through all the properties. // Unfortunately Binding flags don't seem to be working. So, // we need to ensure we don't include base properties PropertyInfo[] lBaseProperties = typeof(CameraMotor).GetProperties(); PropertyInfo[] lProperties = this.GetType().GetProperties(); foreach (PropertyInfo lProperty in lProperties) { if (!lProperty.CanWrite) { continue; } bool lAdd = true; for (int i = 0; i < lBaseProperties.Length; i++) { if (lProperty.Name == lBaseProperties[i].Name) { lAdd = false; break; } } if (!lAdd || lProperty.GetValue(this, null) == null) { continue; } object lValue = lProperty.GetValue(this, null); if (lProperty.PropertyType == typeof(Vector2)) { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + ((Vector2)lValue).ToString("G8") + "\""); } else if (lProperty.PropertyType == typeof(Vector3)) { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + ((Vector3)lValue).ToString("G8") + "\""); } else if (lProperty.PropertyType == typeof(Vector4)) { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + ((Vector4)lValue).ToString("G8") + "\""); } else if (lProperty.PropertyType == typeof(Quaternion)) { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + ((Quaternion)lValue).ToString("G8") + "\""); } else if (lProperty.PropertyType == typeof(Transform)) { // We use the _StoredTransformIndex for serialization } else if (lProperty.PropertyType == typeof(List <int>)) { List <int> lList = lValue as List <int>; lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + string.Join(",", lList.Select(n => n.ToString()).ToArray()) + "\""); } else if (lProperty.PropertyType == typeof(AnimationCurve)) { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \""); AnimationCurve lCurve = lValue as AnimationCurve; for (int i = 0; i < lCurve.keys.Length; i++) { Keyframe lKey = lCurve.keys[i]; lStringBuilder.Append(lKey.time.ToString("f5") + "|" + lKey.value.ToString("f5") + "|" + lKey.tangentMode.ToString() + "|" + lKey.inTangent.ToString("f5") + "|" + lKey.outTangent.ToString("f5")); if (i < lCurve.keys.Length - 1) { lStringBuilder.Append(";"); } } lStringBuilder.Append("\""); } else { lStringBuilder.Append(", \"" + lProperty.Name + "\" : \"" + lValue.ToString() + "\""); } } lStringBuilder.Append("}"); return(lStringBuilder.ToString()); }
public MapPageCS() { CustomMap customMap = new CustomMap { MapType = MapType.Street }; CustomPin pin = new CustomPin { Type = PinType.Place, Position = new Position(37.79752, -122.40183), Label = "Xamarin San Francisco Office", Address = "394 Pacific Ave, San Francisco CA", Name = "Xamarin", Url = "http://xamarin.com/about/" }; customMap.CustomPins = new List <CustomPin> { pin }; customMap.Pins.Add(pin); customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0))); Content = customMap; }