/// <summary> /// given world pos 'pt', find out the dist to given edge /// </summary> public static float DistPointToVEdge(Vector3 pt, VEdge vEdge) { Vector3 pos0 = vEdge.GetVVert(0).GetWorldPos(); Vector3 pos1 = vEdge.GetVVert(1).GetWorldPos(); return(GeoUtil.DistPointToLine(pt, pos0, pos1)); }
public override Scene MakeScene() { Scene scene = new Scene(); Model root = new Model(); Shape shape; string name = "testgeo"; string bricktex = GetMediaPath("brick.jpg"); TriMesh mesh; ExtModel extmodel; scene.Models = root; scene.Name = name + ".scene"; root.Name = name + ".root"; shape = MakeShape(name + ".block", new Col4(1.0f, 0.5f, 0.5f), bricktex, Sampler.DIFFUSE); mesh = (TriMesh)shape.Geometry; GeoUtil.Block(mesh, new Vec3(20.0f, 10.0f, 10.0f)); shape.Translate(-40.0f, 0.0f, 0.0f); root.Append(shape); shape = MakeShape(name + ".sphere", new Col4(0.5f, 1.0f, 0.5f), bricktex, Sampler.DIFFUSE); GeoUtil.Ellipsoid((TriMesh)shape.Geometry, new Vec3(10.0f, 10.0f, 10.0f), 9); root.Append(shape); shape = MakeShape(name + ".torus", new Col4(1.0f, 0.5f, 1.0f), bricktex, Sampler.DIFFUSE); GeoUtil.Torus((TriMesh)shape.Geometry, 5.0f, 10.0f, 15); shape.Translate(30.0f, 20.0f, 0.0f); shape.Turn(new Vec3(1.0f, 0f, 0f), 3.14159f / 2); root.Append(shape); extmodel = new ExtModel(); extmodel.Name = "testgeo.external"; extmodel.FileName = ContentFile; root.Append(extmodel); scene.ShowAll(); return(scene); }
private void shpToolStripMenuItem_Click(object sender, EventArgs e) { GeoUtil util = new GeoUtil(axMapControl1); OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog() == DialogResult.OK) { util.loadShapefile(dialog.FileName); this.lAYER_COUNT = axMapControl1.LayerCount; } }
protected override void Init() { // this one should be an instersection of ranger buffer and current road buffer fineGraphic.Geometry = GeoUtil.GetBuffer(ranger.Graphic.Geometry, meters); #if true fineGraphic.Symbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.FromArgb(defaultAlpha, 0, 0, 0), null); #else fineGraphic.Symbol = GeneralRenderers.DollarPicSymbol.Clone(); #endif ranger.Graphic.GraphicsOverlay.Graphics.Add(fineGraphic); }
public void UpdateDistances() { foreach (var station in this.StationSource) { station.Distance = (int)(GeoUtil.DistanceTo(station.Location.Position, this.myLocation.Position) * 1000.0); } var ordered = this.StationSource.OrderBy(x => x.Distance); this.StationSource = new ObservableCollection <StationViewModel>(ordered); }
protected override void Update(double elapsedSeconds) { double maxRadius = Sensor.Range * 3; double pcRadious = Math.Abs(Math.Sin(1.75 * Math.PI * elapsedSeconds)); double pcOpacity = elapsedSeconds / DurationSeconds; //SimpleFillSymbol s = sensor.AlarmGraphic.Symbol as SimpleFillSymbol; //var curColor = s.Color; //curColor.A = (byte) ((1.0 - Math.Sqrt(pcOpacity)) * 255); //Console.WriteLine("new color = {0}", curColor.A); //s.Color = curColor; sensor.AlarmGraphic.Geometry = GeoUtil.GetBuffer(sensor.Graphic.Geometry, pcRadious * maxRadius); }
private void txtCoord_TextChanged(object sender, EventArgs e) { var coord = GeoUtil.ParseCoordinate(txtCoord.Text); if (coord != null) { foreach (var s in _streets) { s.Distance = s.Coordinate != null?GeoUtil.Distance(coord, s.Coordinate) : -1; } } Refresh(); }
public override Scene MakeScene() { Scene scene = new Scene(); Shape shape = new Shape(); Appearance app = new Appearance(); TriMesh mesh = new TriMesh(VertexPool.TEXCOORDS); MediaSource video = new MediaSource(); SoundPlayer sound = null; Texture tex = new Texture(); Sampler sampler = new Sampler(); Camera cam; Vec2 videosize = new Vec2(1, 1); // pixel dimensions of video frame Vec2 texsize = new Vec2(512, 512); // pixel dimensions of texture (powers of 2) video.Name = "videotest.simroot"; video.Control = Engine.CYCLE; video.Target = tex; video.FileName = GetMediaPath(ContentFile); videosize = video.VideoSize; if (videosize.x > 0) { texsize = video.TexSize; } if (AudioFile != "") { sound = new SoundPlayer(); sound.FileName = GetMediaPath(AudioFile); video.Append(sound); } tex.Name = "videotest.videotexture"; sampler.Set(Sampler.TEXTUREOP, Sampler.EMISSION); sampler.Set(Sampler.TEXCOORD, 0); sampler.Set(Sampler.MIPMAP, 0); sampler.Texture = tex; app.Set(Appearance.CULLING, 0); app.Set(Appearance.LIGHTING, 0); app.SetSampler(0, sampler); shape.Appearance = app; GeoUtil.Rect(mesh, videosize.x / videosize.y, 1.0f, videosize.x / texsize.x, videosize.y / texsize.y); shape.Geometry = mesh; shape.Name = "videotest.root"; scene.Models = shape; scene.Engines = video; cam = scene.Camera; cam.Translation = new Vec3(0.0f, 0.0f, 2.0f); cam.Hither = 0.1f; cam.Name = "videotest.camera"; return(scene); }
/* * Make the shape for the Kinect depth camera output */ protected Shape MakeCameraOutputShape(Camera cam, bool iscolor) { Shape shape = new Shape(); Appearance app = new Appearance(); PhongMaterial mtl = new PhongMaterial(new Col4(1.0f, 1.0f, 1.0f, 0.7f)); Sampler sampler = new Sampler(); TriMesh mesh = new TriMesh("position float 3, normal float 3, texcoord float 2"); Vec2 videosize = new Vec2(640, 480); Vec2 texsize = new Vec2(1024, 512); Box3 vvol = cam.ViewVol; Vec3 campos = cam.Translation; float camdist = campos.Length; // distance of camera from body float backdist = camdist + vvol.max.z / 6.0f; float h = backdist * vvol.Height / vvol.min.z; float w = h; backdist -= camdist; if (Kinect != null) { Texture tex = new Texture(); sampler.Texture = tex; if (iscolor) { tex.Name = "magicmirror.kinect.colorimage"; Kinect.ColorTexture = tex; } else { tex.Name = "magicmirror.kinect.depthimage"; Kinect.DepthTexture = tex; } } sampler.Name = "diffuse"; sampler.Set(Sampler.TEXTUREOP, Sampler.DIFFUSE); sampler.Set(Sampler.TEXCOORD, 0); app.Set(Appearance.CULLING, 1); app.Set(Appearance.LIGHTING, 1); app.Set(Appearance.TRANSPARENCY, 1); app.SetSampler(0, sampler); app.Material = mtl; app.Name = "cameraoutput"; shape.Appearance = app; GeoUtil.Rect(mesh, h * videosize.x / videosize.y, h, videosize.x / texsize.x, videosize.y / texsize.y); shape.Geometry = mesh; shape.Name = "magicmirror.kinect.camerashape"; shape.Translate(0, h / 2, -backdist); return(shape); }
public void Initialize() { LastPacketTime = Environment.TickCount; var geoData = GeoUtil.GetDataFromIPAddress(this.IPAddress); if (geoData != null) { this.CountryId = GeoUtil.GetCountryId(geoData["country"]["names"]["en"].ToString()); this.Language = CultureInfo .GetCultures(CultureTypes.AllCultures) .First(c => c.Name.EndsWith(geoData["country"]["iso_code"].ToString())) .Name; this.Latitude = float.Parse(geoData["location"]["latitude"].ToString()); this.Longitude = float.Parse(geoData["location"]["longitude"].ToString()); } Status = new bUserStatus(bStatus.Idle, "", "", Mods.None, this.currentMode, 0); this.GetModesData(); QueueCommand( new Command(Commands.OUT_ChoProtocol, Bancho.Protocol), //TODO: Is boxing good? idk.. new Command(Commands.OUT_LoginResult, this.Id), new Command(Commands.OUT_UserTags, (int)this.Tags), new Command(Commands.OUT_FriendsList, new[] { 2, 3 }), //TODO: Friendslist new Command(Commands.OUT_Announcement, "http://puu.sh/jh7t7/20c04029ad.png|https://osu.ppy.sh/news/123912240253"), new Command(Commands.OUT_UpdateUserInfo, new bUserInfo(this.Id, this.Username, this.TimeZone, (byte)this.CountryId, UserTags.Player, PlayModes.Osu, this.Longitude, this.Latitude, 1)), //Yes, idk what is this "1" new Command(Commands.OUT_UpdateUserState, this.SerializableStats), new Command(Commands.OUT_UpdateUserInfo, new bUserInfo(-3, "BanchoBot", 0, 0, UserTags.None, PlayModes.Osu, 0, 0, 0)) ); QueueCommand(Commands.OUT_ChannelJoinSuccess, "#osu"); QueueCommand(Commands.OUT_ChannelJoinSuccess, "#broadcast"); //FBUG: cant click in BanchoBot on his messages //FIXED? Probally negative id is only sent in UpdateUserInfo .. QueueCommand(Commands.OUT_IrcMessage, new bIRCMessage("BanchoBot", "#osu", "Welcome to the Bancho!") { SenderId = 3 }); //NOTE: This is a test message }
private void button4_Click(object sender, EventArgs e) { if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "") { MessageBox.Show("输入要素不可以为空\n裁剪要素不可以为空\n输出要素不可以为空"); } else if (textBox1.Text == "" && textBox2.Text == "") { MessageBox.Show("输入要素不可以为空\n裁剪要素不可以为空"); return; } else if (textBox1.Text == "" && textBox3.Text == "") { MessageBox.Show("输入要素不可以为空\n输出要素不可以为空"); return; } else if (textBox2.Text == "" && textBox3.Text == "") { MessageBox.Show("裁剪要素不可以为空\n输出要素不可以为空"); return; } else if (textBox2.Text == "") { MessageBox.Show("裁剪要素不可以为空"); } else if (textBox1.Text == "") { MessageBox.Show("输入要素不可以为空"); } else if (textBox3.Text == "") { MessageBox.Show("输出要素不可以为空"); } else { Geoprocessor gp = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.Clip clipTool = new Clip(textBox1.Text, textBox2.Text, textBox3.Text); gp.OverwriteOutput = true; gp.Execute(clipTool, null); GeoUtil util = new GeoUtil(axmapcontrol1); util.loadShapefile(textBox3.Text); this.Close(); } }
protected override void Update(double elapsedSeconds) { double perc = elapsedSeconds / DurationSeconds; #if true fineGraphic.Geometry = GeoUtil.GetBuffer(ranger.Graphic.Geometry, meters); SimpleFillSymbol symbol = fineGraphic.Symbol as SimpleFillSymbol; var curColor = symbol.Color; curColor.A = (byte)((1.0 - Math.Sqrt(perc)) * defaultAlpha); symbol.Color = curColor; #else var sym = fineGraphic.Symbol as PictureMarkerSymbol; double nv = 1.0 - Math.Sqrt(perc); nv = Math.Min(1.0, nv); nv = Math.Max(0.0, nv); sym.Opacity = nv; #endif }
private bool StationSourceFilter(StationViewModel station) { if (station == null) { return(false); } var myCity = Cities.CurrentCity; if (myCity == null) { return(false); } if (GeoUtil.DistanceTo(station.Location.Position, myCity.Center) < 50000) { return(true); } return(false); }
private void SelectNearestStationWithAvailablilty(Predicate <StationViewModel> condition) { double minDist = Double.MaxValue; StationViewModel nearestStation = null; foreach (var station in this.StationSource) { double dist = GeoUtil.DistanceTo(myLocation.Position, station.Location.Position); if (dist < minDist && condition(station)) { nearestStation = station; minDist = dist; } } this.SelectStation(nearestStation); if (nearestStation != null) { this.MapCenter = nearestStation.Location; } }
public async Task <double> GetDistance(double fromLat, double fromLong, double toLat, double tolong) { if (!int.TryParse(_context.User.Claims.FirstOrDefault(cl => cl.Type == "id")?.Value, out var userId)) { RaiseError("unauthorized", HttpStatusCode.Unauthorized); } var distance = await _distanceRepo.GetQueryableItems(predicate : en => en.FromLat == fromLat && en.FromLong == fromLong && en.ToLat == toLat && en.ToLong == tolong).SingleOrDefaultAsync(); var request = new Request() { UserId = userId }; if (distance == null) { request.Distance = new Distance() { FromLat = fromLat, FromLong = fromLong, ToLat = toLat, ToLong = tolong, Value = GeoUtil.GetDistance(fromLat, fromLong, toLat, tolong) }; } if (distance != null) { request.DistanceId = distance.Id; } await _RequestRepo.InsertAsync(request); await _unitofWork.SaveChangesAsync(); return(distance != null ? distance.Value : request.Distance.Value); }
public void GeoUtil_ConvertsMetersToMilesCorrecly() { var target = GeoUtil.MetersToMiles(500); //500 meters to miles Assert.AreEqual(0.310685596118667, target, float.Epsilon); }
public void GeoUtil_ConvertsMetersToYardsCorrecly() { var target = GeoUtil.MetersToYards(500); //500 meters to yards Assert.AreEqual(546.80664916885394, target, float.Epsilon); }
static void Main() { ServerStarted = DateTime.Now; if (File.Exists("MOTD.txt")) { MOTD = Encoding.Default.GetBytes($"<pre>\n{File.ReadAllText("MOTD.txt").InsertHrefInUrls()}\n</pre>"); } Console.Write("Initializing Bancho"); if (IsDebug) { Console.Write(" in debug mode"); } Console.WriteLine(".."); Process.GetCurrentProcess().PriorityBoostEnabled = true; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime; Thread.CurrentThread.Priority = ThreadPriority.Highest; Console.CursorVisible = false; Console.Title = (IsDebug?"[DEBUG] ":"") + "osu!Bancho"; GeoUtil.Initialize(); if (!File.Exists("config.ini")) { File.WriteAllText("config.ini", IniFile.DefaultIni); } IniFile ini = new IniFile("config.ini"); Bancho.IsRestricted = ini.GetValue("Bancho", "Restricted", false); CultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); Console.WriteLine("Initializing Database.."); var connectionString = new MySqlConnectionStringBuilder { ConnectionTimeout = ini.GetValue("DatabaseConnection", "ConnectionTimeout", 10u), Database = ini.GetValue("DatabaseConnection", "Database", "osu!"), DefaultCommandTimeout = ini.GetValue("DatabaseConnection", "CommandTimeout", 30u), Logging = false, MaximumPoolSize = ini.GetValue("DatabaseConnection", "MaximumPoolSize", 250u), MinimumPoolSize = ini.GetValue("DatabaseConnection", "MinimumPoolSize", 10u), Password = ini.GetValue("DatabaseConnection", "Password", ""), Pooling = true, Port = ini.GetValue("DatabaseConnection", "Port", 3306u), Server = ini.GetValue("DatabaseConnection", "Server", "127.0.0.1"), UserID = ini.GetValue("DatabaseConnection", "User", "root"), AllowZeroDateTime = true, ConvertZeroDateTime = true, }; _databaseManager = new DatabaseManager(connectionString.ToString()); if (!_databaseManager.IsConnected()) { Console.Error.WriteLine("Failed to connect to the specified MySQL server."); Console.ReadKey(true); Environment.Exit(1); } workerTimer = new Timer( (state) => { foreach (Player player in PlayerManager.Players .Where(player => (Environment.TickCount - player.LastPacketTime) >= 80000)) { PlayerManager.DisconnectPlayer(player, DisconnectReason.Timeout); } try { UpdateOnlineNow(); } catch (Exception e) { Debug.WriteLine("Can't update onlines_now: " + e.Message); } }, null, 0, 15000); #if DEBUG Debug.Listeners.Add(new ConsoleTraceListener()); #endif Console.WriteLine("Initializing IRC.."); irc = new IrcManager(); irc.Start(); var port = ini.GetValue("Bancho", "Port", 80); Console.WriteLine($"Initializing HTTP in port {port.ToString()}.."); HttpAsyncHost http = new HttpAsyncHost(IsDebug? 1 : 120); http.Run("http://+:" + port.ToString() + "/"); Console.ReadLine(); }
public void GeoUtil_ConvertsMilesToMetersCorrecly() { var target = GeoUtil.MilesToMeters(200); //200 mile to meters Assert.AreEqual(321868.8, target, float.Epsilon); }
public SettingsViewModel(TabiConfiguration config, INavigation navigation, IRepoManager repoManager, SyncService syncService, DataResolver dataResolver) { _navigation = navigation ?? throw new ArgumentNullException(nameof(navigation)); _config = config ?? throw new ArgumentNullException(nameof(config)); _repoManager = repoManager ?? throw new ArgumentNullException(nameof(repoManager)); _dataResolver = dataResolver ?? throw new ArgumentNullException(nameof(dataResolver)); _syncService = syncService ?? throw new ArgumentNullException(nameof(syncService)); ExportDatabaseCommand = new Command(async key => { Log.Info("Command: Exporting database"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; var t = await rootFolder.GetFileAsync("tabi.db"); DependencyService.Get <IShareFile>().ShareFile(t.Path); }); DropDatabaseCommand = new Command(async() => { Log.Info("Command: Dropping database"); var answer = await Application.Current.MainPage.DisplayAlert("Confirm", "Drop database?", "Yes", "Cancel"); if (answer) { //SQLiteHelper.Instance.ClearPositions(); } }); InfoCommand = new Command((obj) => { InfoCount++; if (InfoCount == 10 && App.Developer) { Settings.Developer = true; InfoCount = 0; } }); ExportKMLCommand = new Command(async key => { Log.Info("Command: Export KML"); //IFolder rootFolder = FileSystem.Current.LocalStorage; //string fileName = "Tabi-Export.kml"; //IFile file = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); ////Repository<Position> posRepo = new Repository<Position>(SQLiteHelper.Instance.Connection); //var result = await posRepo.Get(p => p.Accuracy < 100, x => x.Timestamp); //string kml = GeoUtil.GeoSerialize(result); //await file.WriteAllTextAsync(kml); //DependencyService.Get<IShareFile>().ShareFile(file.Path); }); ExportCSVCommand = new Command(async key => { Log.Info("Command: Export CSV"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; string fileName = "Tabi-Export.txt"; string path = PortablePath.Combine(rootFolder.Path, fileName); IFile file = await rootFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); IPositionEntryRepository positionEntryRepository = _repoManager.PositionEntryRepository; var result = positionEntryRepository.FilterAccuracy(100).ToList(); Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite); GeoUtil.PositionsToCsv(result, stream); DependencyService.Get <IShareFile>().ShareFile(path, "text/csv"); }); ExportBatteryCSVCommand = new Command(async key => { Log.Info("Command: Export Battery CSV"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; string fileName = "Tabi-Export-Battery.txt"; string path = PortablePath.Combine(rootFolder.Path, fileName); IFile file = await rootFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); var batteryEntryRepo = _repoManager.BatteryEntryRepository; var result = batteryEntryRepo.GetAll().ToList(); Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite); using (TextWriter tw = new StreamWriter(stream)) { var csv = new CsvWriter(tw); csv.Configuration.RegisterClassMap <BatteryEntryMap>(); csv.WriteRecords(result); } DependencyService.Get <IShareFile>().ShareFile(path, "text/csv"); }); ClearStopsCommand = new Command((obj) => { _repoManager.StopVisitRepository.ClearAll(); _repoManager.TrackEntryRepository.ClearAll(); }); OpenLogsCommand = new Command((obj) => { LogsPage page = new LogsPage(); _navigation.PushAsync(page); }); LoadSampleCommand = new Command(async() => { DummyDbLoader dummy = new DummyDbLoader(); await dummy.LoadAsync(); }); ShowMockupCommand = new Command(() => { var assembly = typeof(SettingsViewModel).GetTypeInfo().Assembly; using (Stream stream = assembly.GetManifestResourceStream("Tabi.DemoCsv")) { List <PositionEntry> entries = GeoUtil.CsvToPositions(stream).ToList(); _dataResolver.ResolveData(DateTimeOffset.MinValue, DateTimeOffset.Now); //var x = sv.GroupPositions(entries, 100); //var z = sv.DetermineStopVisits(x, null); //Log.Debug(z.ToString()); } // ActivityOverviewMockupPage sPage = new ActivityOverviewMockupPage(); // navigationPage.PushAsync(sPage); }); ShowPageCommand = new Command(() => { TourVideoPage sPage = new TourVideoPage(); _navigation.PushModalAsync(sPage); }); ShowTourCommand = new Command(async() => { Page tPage = new TourVideoPage(); Analytics.TrackEvent("ShowTour clicked"); await _navigation.PushModalAsync(tPage); }); PrivacyDataCommand = new Command(async() => { Analytics.TrackEvent("Privacy & data settings clicked"); await _navigation.PushAsync(new SettingsPrivacyPage(this)); }); AppAboutCommand = new Command(async() => { Analytics.TrackEvent("Privacy & data settings clicked"); await _navigation.PushAsync(new AboutSettings(this)); }); SendSupportCallCommand = new Command(async() => { try { PhoneDialer.Open(_config.Support.PhoneNumber); } catch (ArgumentNullException ex) { await UserDialogs.Instance.AlertAsync(AppResources.ErrorOccurredTitle, okText: AppResources.OkText); Log.Error(ex); } catch (FeatureNotSupportedException ex) { await UserDialogs.Instance.AlertAsync(AppResources.DeviceUnsupportedText, AppResources.DeviceUnsupportedTitle, AppResources.OkText); Log.Error(ex); } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(AppResources.ErrorOccurredTitle, AppResources.OkText); Log.Error(ex); } }); SendSupportEmailCommand = new Command(async() => { string subject = _config.Support.EmailSubject ?? "Tabi app"; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(" "); stringBuilder.AppendLine("=========================="); stringBuilder.AppendLine($"{_config.App.AppName} app"); stringBuilder.AppendLine($"Version: {VersionTracking.CurrentVersion} ({VersionTracking.CurrentBuild})"); stringBuilder.AppendLine($"Platform: {DeviceInfo.Platform} ({DeviceInfo.VersionString})"); stringBuilder.AppendLine($"Model: {DeviceInfo.Manufacturer} ({DeviceInfo.Model})"); stringBuilder.AppendLine($"API URL: {_config.Api.Url}"); stringBuilder.AppendLine($"Client Id: {_config.Api.ClientIdentifier}"); stringBuilder.AppendLine($"Device ID: {Settings.Device}"); stringBuilder.AppendLine($"Username: {Settings.Username}"); List <string> to = new List <string>() { _config.Support.Email }; try { var message = new EmailMessage { Subject = subject, Body = stringBuilder.ToString(), To = to, }; await Email.ComposeAsync(message); } catch (FeatureNotSupportedException ex) { await UserDialogs.Instance.AlertAsync(AppResources.DeviceUnsupportedText, AppResources.DeviceUnsupportedTitle, AppResources.OkText); Log.Error(ex); } catch (Exception ex) { Log.Error(ex); } }); OpenSupportWebsiteCommand = new Command(async() => { await Browser.OpenAsync(_config.Support.Url); }); LicensesCommand = new Command(async() => { await Browser.OpenAsync(_config.App.LicensesUrl); }); AgreementCommand = new Command(async() => { await Browser.OpenAsync(_config.App.AgreementUrl); }); UploadCommand = new Command(async() => { Analytics.TrackEvent("Upload clicked"); // Check if there is an active internet connection if (CrossConnectivity.Current.IsConnected) { bool wifiAvailable = CrossConnectivity.Current.ConnectionTypes.Contains(Plugin.Connectivity.Abstractions.ConnectionType.WiFi); bool upload = !Settings.WifiOnly || wifiAvailable; // Check if connected to WiFI if (!upload) { upload = await UserDialogs.Instance.ConfirmAsync(AppResources.MobileDataUsageText, AppResources.MobileDataUsageTitle, AppResources.ContinueButton, AppResources.CancelText); } if (upload) { UserDialogs.Instance.ShowLoading(AppResources.UploadDataInProgress, MaskType.Black); // Check if the API is available (within 5 seconds). // Display message to user if api is unavailable. bool available = await _syncService.Ping(5); if (!available) { UserDialogs.Instance.HideLoading(); await UserDialogs.Instance.AlertAsync(AppResources.APIUnavailableText, AppResources.APIUnavailableTitle, AppResources.OkText); return; } try { await _syncService.UploadAll(false); UserDialogs.Instance.HideLoading(); Settings.LastUpload = DateTime.Now.Ticks; UserDialogs.Instance.Toast(AppResources.DataUploadSuccesful); } catch (Exception e) { UserDialogs.Instance.HideLoading(); await UserDialogs.Instance.AlertAsync(AppResources.UploadDataErrorText, AppResources.ErrorOccurredTitle, AppResources.OkText); Log.Error($"UploadAll exception {e.Message}: {e.StackTrace}"); } } } else { UserDialogs.Instance.HideLoading(); // Show user a message that there is no internet connection await UserDialogs.Instance.AlertAsync(AppResources.NoInternetConnectionText, AppResources.NoInternetConnectionTitle, AppResources.OkText); } }); Settings.PropertyChanged += Settings_PropertyChanged; }
/// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="loc">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="lat">The latitude of the destination point.</param> /// <param name="lng">The longitude of the destination point.</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation loc, double lat, double lng) { return(GeoUtil.DistanceTo(loc, new GeoName { Latitude = lat, Longitude = lng })); }
/// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="loc">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="lat">The latitude of the destination point.</param> /// <param name="lng">The longitude of the destination point.</param> /// <param name="radiusofearthinmeters">The radius of the earth in meters (default: 6371000).</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation loc, double lat, double lng, double radiusofearthinmeters) { return(GeoUtil.DistanceTo(loc, new GeoName { Latitude = lat, Longitude = lng }, radiusofearthinmeters)); }
/// <summary> /// Calculates the distance from the this instance to destination location (in meters). /// </summary> /// <param name="src">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="dst">The destination location.</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation src, IGeoLocation dst) { return(GeoUtil.DistanceTo(src, dst)); }
public Location GetBarycenter() => new Location( GeoUtil.GetMidpoint(Sw.Lat, Ne.Lat), GeoUtil.GetMidpoint(Sw.Lng, Ne.Lng) );
public bool Contains(Location location) => GeoUtil.Contains(location.Lat, Sw.Lat, Ne.Lat) && GeoUtil.Contains(location.Lng, Sw.Lng, Ne.Lng);
public virtual T GetNearestTo(MapPoint point) { MapPoint nearestCoord = GeoUtil.GetNearestCoordinateInGraphicsCollection(point, GetBaseGraphics()); return(ByPosition(nearestCoord)); }
/// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="src">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="dst">The destination location.</param> /// <param name="radiusofearthinmeters">The radius of the earth in meters (default: 6371000).</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation src, IGeoLocation dst, double radiusofearthinmeters) { return(GeoUtil.DistanceTo(src, dst, radiusofearthinmeters)); }
public void GeoUtil_ConvertsYardsToMetersCorrecly() { var target = GeoUtil.YardsToMeters(200); //200 yards to meters Assert.AreEqual(182.88, target, float.Epsilon); }