Esempio n. 1
0
        private Geolocation BinarySearch(Geolocation[] locationArray, long ip)
        {
            int low = 0;
            int high = locationArray.Length - 1;
            int mid;

            while (low <= high)
            {
                mid = (low + high) / 2;
                if (locationArray[mid].CompareTo(ip) < 0)
                    low = mid + 1;
                else if (locationArray[mid].CompareTo(ip) > 0)
                    high = mid - 1;
                else
                    return locationArray[mid];
            }
            return null;
        }
Esempio n. 2
0
        private async Task <string> getUserAddress()
        {
            var location = await Geolocation.GetLastKnownLocationAsync();

            if (location == null)
            {
                location = await Geolocation.GetLocationAsync(new GeolocationRequest
                {
                    DesiredAccuracy = GeolocationAccuracy.Best,
                    Timeout         = TimeSpan.FromSeconds(30)
                });
            }
            string lat          = location.Latitude.ToString().Replace(",", ".");
            string lng          = location.Longitude.ToString().Replace(",", ".");
            string latlng       = lat + "," + lng;
            string reqUri       = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&key=AIzaSyA9rHJZEGWe6rX4nAHTGXFxCubmw-F0BBw";
            string responseData = await httpObject.GetRequest(reqUri);

            JObject json    = JObject.Parse(responseData);
            string  address = json["results"][0]["formatted_address"].ToString();

            return(address);
        }
Esempio n. 3
0
        /// <summary>
        ///     Gets the current location.
        /// </summary>
        /// <returns></returns>
        public async Task <Xamarin.Essentials.Location> GetCurrentLocation()
        {
            try
            {
                await CheckPermissionAsync();

                UserDialogs.Instance.ShowLoading("GettingLocation".Translate());
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromMinutes(1));
                _cts = new CancellationTokenSource();
                return(await Geolocation.GetLocationAsync(request).ConfigureAwait(false));
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
            }
            finally
            {
                _cts?.Dispose();
                _cts = null;
                UserDialogs.Instance.HideLoading();
            }
            return(null);
        }
Esempio n. 4
0
        //----------------------------------------------------------
        #region  Unity イベント関数
        //----------------------------------------------------------

        private void Awake()
        {
            mCamera   = GetComponent <Camera>();
            mListener = GetComponent <AudioListener>();
            Assert.IsNotNull(mCamera);
            Assert.IsNotNull(mListener);
            Assert.IsNotNull(Resource);

            Resource.Initialize();

            mTime    = new Time();
            mGraphic = new Graphic(Resource, mCamera);
            mGraphic.SetResolution(CanvasWidth, CanvasHeight);
            mSound         = new Sound(this, Resource, GetComponents <AudioSource>());
            mCollision     = new Collision(Resource);
            mNetwork       = new Network(this, mGraphic);
            mPointer       = new Pointer(mGraphic);
            mKeyboard      = new Keyboard();
            mAccelerometer = new Accelerometer();
            mGeolocation   = new Geolocation();
            mCameraDevice  = new CameraDevice(mGraphic);
            mProxy         = new Proxy(mTime, mGraphic, mSound, mCollision, mNetwork, mPointer, mKeyboard, mAccelerometer, mGeolocation, mCameraDevice);
        }
Esempio n. 5
0
        private async void ButtonSaveMyParking_Clicked(object sender, EventArgs e)
        {
            try
            {
                Location LastLocation = null;
                LastLocation = await Geolocation.GetLastKnownLocationAsync();

                if (LastLocation != null)
                {
                    Preferences.Set("Latitude", LastLocation.Latitude);
                    Preferences.Set("Longitude", LastLocation.Longitude);
                    await PopupNavigation.Instance.PushAsync(new LocationSavedPopup("מיקום החניה נשמר"));
                }
                else
                {
                    await PopupNavigation.Instance.PushAsync(new LocationSavedPopup("חניה לא נשמרה, יתכן ששירותי המיקום לא פעילים"));
                }
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }
Esempio n. 6
0
        public async Task <string> GetLocationStringAsync()
        {
            string locationString = "";

            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    locationString = $"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}";
                }
            }
            catch (Exception ex)
            {
                // Unable to get location
                Console.WriteLine(ex.Message);
                return(ex.Message);
            }

            return(locationString);
        }
Esempio n. 7
0
        public async Task <string> GetCoordinates()
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Best);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    Latitude  = location.Latitude;
                    Longitude = location.Longitude;
                    Location  = await GetCity(location);

                    CurrentWeatherConst.Location = Location;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                throw;
            }
            return(Location);
        }
Esempio n. 8
0
        public async Task Get_Location_With_Request_Is_Something()
        {
            await MainThread.InvokeOnMainThreadAsync(async() =>
            {
                await Permissions.RequestAsync <Permissions.LocationWhenInUse>();
            });

            var request  = new GeolocationRequest(GeolocationAccuracy.Best);
            var location = await Geolocation.GetLocationAsync(request);

            Assert.NotNull(location);

            Assert.True(location.Accuracy > 0);
            Assert.NotEqual(0.0, location.Latitude);
            Assert.NotEqual(0.0, location.Longitude);

            Assert.NotEqual(DateTimeOffset.MaxValue, location.Timestamp);
            Assert.NotEqual(DateTimeOffset.MinValue, location.Timestamp);

            // before right now, but after yesterday
            Assert.True(location.Timestamp < DateTimeOffset.UtcNow);
            Assert.True(location.Timestamp > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(1)));
        }
Esempio n. 9
0
        public void GetGeolocationTest()
        {
            var geolocation = new Geolocation()
            {
                Host      = "host",
                Ip        = "ip",
                Latitude  = 0,
                Longitude = 0,
                Location  = "location"
            };

            GeolocationDao.Insert(geolocation);
            var response = _controller.GetGeolocation(geolocation.Host);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            var result = response.Content.ReadAsAsync <Geolocation>().Result;

            Assert.AreEqual(geolocation.Host, result.Host);
            Assert.AreEqual(geolocation.Ip, result.Ip);
            Assert.AreEqual(geolocation.Latitude, result.Latitude);
            Assert.AreEqual(geolocation.Longitude, result.Longitude);
            Assert.AreEqual(geolocation.Location, result.Location);
        }
Esempio n. 10
0
 public List<LocationResult> Convert(List<PageRequest> data)
 {
     Dictionary<long, LocationResult> resultDictionary = new Dictionary<long, LocationResult>();
     foreach (var item in data)
     {
         Geolocation toSearch = new Geolocation();
         Geolocation location = BinarySearch(_geolocations, ConvertIP(item.IpAddress));
         if (location != null)
         {
             LocationResult gettedValue;
             bool returned = resultDictionary.TryGetValue(location.IpMin, out gettedValue);
             if (returned)
             {
                 gettedValue.Count++;
             }
             else
             {
                 resultDictionary.Add(location.IpMin, new LocationResult{ Latitude = location.Latitude, Longitude =location.Longitude, Count = 1 });
             }
         }
     }
     return resultDictionary.Values.ToList();
 }
Esempio n. 11
0
        /// <summary>
        /// Gets the current GPS location
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetGPSLocation()
        {
            //Code from official Xamarin documentation
            //https://docs.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                cts = new CancellationTokenSource();
                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                if (location != null)
                {
                    return(location.Latitude + "," + location.Longitude);
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
                return("Exception: FeatureNotSupportedException");
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
                return("Exception: FeatureNotEnabledException");
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                return("Exception: PermissionException");
            }
            catch (Exception ex)
            {
                // Unable to get location
                return("Exception: Exception");
            }
            return("Unable to get GPS location");
        }
Esempio n. 12
0
        async Task GetClosestAsync()
        {
            if (Monkeys.Count == 0)
            {
                return;
            }

            if (IsBusy)
            {
                return;
            }
            try
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                if (location == null)
                {
                    location = await Geolocation.GetLocationAsync(new GeolocationRequest
                    {
                        DesiredAccuracy = GeolocationAccuracy.Medium,
                        Timeout         = TimeSpan.FromSeconds(30)
                    });
                }

                var first = Monkeys.OrderBy(m => location.CalculateDistance(
                                                new Location(m.Latitude, m.Longitude), DistanceUnits.Miles))
                            .FirstOrDefault();

                await Application.Current.MainPage.DisplayAlert("", first.Name + " " +
                                                                first.Location, "OK");
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Something is wrong",
                                                                "Unable to get location! :(", "OK");
            }
        }
        public async Task LoadCurrentLocation()
        {
            try
            {
                IsBusy = true;
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    Longitude = location.Longitude.ToString();
                    Latitude  = location.Latitude.ToString();

                    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
            finally
            {
                IsBusy = false;
            }
        }
        async void FilterApply()
        {
            IsFilter = false;
            GpsLocationModel gpsLocationModel = null;

            try
            {
                var location = await Geolocation.GetLocationAsync();

                gpsLocationModel = new GpsLocationModel
                {
                    Latitude  = location.Latitude,
                    Longitude = location.Longitude
                };
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                gpsLocationModel = new GpsLocationModel();
            }
            catch (PermissionException pEx)
            {
                gpsLocationModel = new GpsLocationModel();
            }
            catch (Exception ex)
            {
                gpsLocationModel = new GpsLocationModel();
            }

            SearchRequestModel request = new SearchRequestModel
            {
                Keywords        = Keywords,
                SearchDistance  = (int)FilterDistance,
                CurrentLocation = gpsLocationModel
            };

            GetItems(request);
        }
        public async Task Run(CancellationToken token)
        {
            await Task.Run(async() => {
                while (!stopping)
                {
                    token.ThrowIfCancellationRequested();
                    try
                    {
                        await Task.Delay(2000);

                        var request  = new GeolocationRequest(GeolocationAccuracy.High);
                        var location = await Geolocation.GetLocationAsync(request);
                        if (location != null)
                        {
                            var message = new LocationMessage
                            {
                                Latitude  = location.Latitude,
                                Longitude = location.Longitude
                            };

                            Device.BeginInvokeOnMainThread(() =>
                            {
                                MessagingCenter.Send <LocationMessage>(message, "Location");
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            var errormessage = new LocationErrorMessage();
                            MessagingCenter.Send <LocationErrorMessage>(errormessage, "LocationError");
                        });
                    }
                }
            }, token);
        }
    public static Geolocation toWGS84(Geolocation etrs)
    {
        if (!WithinTM35FIN(etrs))
        {
            return(Geolocation.zero);
        }

        double E   = etrs.latitude / (CA1 * Ck0);
        double nn  = (etrs.longitude - CE0) / (CA1 * Ck0);
        double E1p = Ch1 * System.Math.Sin(2.0 * E) * System.Math.Cosh(2.0 * nn);
        double E2p = Ch2 * System.Math.Sin(4.0 * E) * System.Math.Cosh(4.0 * nn);
        double E3p = Ch2 * System.Math.Sin(6.0 * E) * System.Math.Cosh(6.0 * nn);
        double E4p = Ch3 * System.Math.Sin(8.0 * E) * System.Math.Cosh(8.0 * nn);

        double nn1p = Ch1 * System.Math.Cos(2.0 * E) * System.Math.Sinh(2.0 * nn);
        double nn2p = Ch2 * System.Math.Cos(4.0 * E) * System.Math.Sinh(4.0 * nn);
        double nn3p = Ch3 * System.Math.Cos(6.0 * E) * System.Math.Sinh(6.0 * nn);
        double nn4p = Ch4 * System.Math.Cos(8.0 * E) * System.Math.Sinh(8.0 * nn);

        double Ep = E - E1p - E2p - E3p - E4p;

        double nnp = nn - nn1p - nn2p - nn3p - nn4p;
        double be  = System.Math.Asin(System.Math.Sin(Ep) / System.Math.Cosh(nnp));

        double Q  = Asinh(System.Math.Tan(be));
        double Qp = Q + Ce * Atanh(Ce * System.Math.Tanh(Q));

        Qp = Q + Ce * Atanh(Ce * System.Math.Tanh(Qp));
        Qp = Q + Ce * Atanh(Ce * System.Math.Tanh(Qp));
        Qp = Q + Ce * Atanh(Ce * System.Math.Tanh(Qp));

        double latitude = RadianToDegree(System.Math.Atan(System.Math.Sinh(Qp)));

        double longitude = RadianToDegree(Clo0 + System.Math.Asin(System.Math.Tanh(nnp) / System.Math.Cos(be)));

        return(new Geolocation(longitude, latitude));
    }
        public async Task <PositionModel> RequestPosition()
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.High);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    return(new PositionModel
                    {
                        Latitude = location.Latitude,
                        Longitude = location.Longitude,
                        Altitude = location.Altitude
                    });
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                // Unable to get location
            }

            return(null);
        }
Esempio n. 18
0
        private async void GetLocation()
        {
            var locationStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

            if (locationStatus != PermissionStatus.Granted)
            {
                var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });

                locationStatus = results[Permission.Location];
            }
            if (locationStatus == PermissionStatus.Granted)
            {
                try
                {
                    var request  = new GeolocationRequest(GeolocationAccuracy.High, TimeSpan.FromMilliseconds(5000));
                    var location = await Geolocation.GetLocationAsync(request);

                    MainMap.MapRegion = MapSpan.FromCenterAndRadius(
                        new Position(location.Longitude, location.Longitude), Distance.FromKilometers(50));
                }
                catch (FeatureNotEnabledException)
                {
                    await PopupNavigation.Instance.PushAsync(new LocationErrorPage());

                    //  await DisplayAlert(AppResources.Alert, AppResources.LocationEnabled, AppResources.Ok);
                }
            }
            else
            {
                await PopupNavigation.Instance.PushAsync(new LocationErrorPage(x));

                //await DisplayAlert(AppResources.PermissionsDenied, AppResources.PermissionLocationDetails,
                //    AppResources.Ok);
                //On iOS you may want to send your user to the settings screen.
                //  CrossPermissions.Current.OpenAppSettings();
            }
        }
Esempio n. 19
0
        private async void BttnGetBPEJ_Clicked(object sender, EventArgs e)
        {
            if (GUIAnimations.CheckConnection(this))
            {
                return;
            }

            BttnGetBPEJ.IsEnabled = false;

            var token = GUIAnimations.DotLoadingAnimation(LblBPEJFinding, "Vyhodnocování", 7, 300);

            Location location = null;

            try
            {
                location = await Geolocation.GetLocationAsync();

                EntrBPEJcode.Text = await BluetoothController.GetDataFromRPiAsync($"get_bpej {location.Longitude} {location.Latitude}", 1000, 1000);

                EntrBPEJcode_Completed(null, null);
            }
            catch (FeatureNotEnabledException)
            {
                _ = DisplayAlert("Lokace není povolená", "Pro použití funkce si povolte lokaci v telefonu.", "OK");
            }
            catch (Exception ex)
            {
                _ = DisplayAlert("Debug - Exception", ex.Message, "OK");
            }

            token.Cancel();
            await Task.Delay(500);

            LblBPEJFinding.Text = location != null ? $"Vaše pozice | z. délka: {location.Longitude}, z. šířka: {location.Latitude}" : "Vaši pozici se nepodařilo lokalizovat.";

            BttnGetBPEJ.IsEnabled = true;
        }
Esempio n. 20
0
        async void SetLocation()
        {
            MyMap.Pins.Add(
                new Pin
            {
                Position = new Position(42.349344, -71.082504),
                Label    = "Wired Puppy"
            }
                );

            try
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                if (location != null)
                {
                    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                    MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(42.349344, -71.082504), Distance.FromMiles(0.1)));
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }
Esempio n. 21
0
        async void FetchLocationAsync()
        {
            var hasPermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

            if (hasPermission != PermissionStatus.Granted)
            {
                var requestedResponse = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);

                if (requestedResponse[Permission.Location] != PermissionStatus.Granted)
                {
                    PrintLogDetails.GetInstance().PrintLogDeatails("Select Location", "Unable to get location: ", "");
                    return;
                }
            }
            try
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                if (location != null)
                {
                    Settings.UserLatSettings  = location.Latitude.ToString();
                    Settings.UserLongSettings = location.Longitude.ToString();
                    System.Console.WriteLine("latitude: " + location.Latitude);
                    System.Console.WriteLine("Longitude: " + location.Longitude);
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                System.Console.WriteLine("Longitude: " + fnsEx);
                // Handle not supported on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                System.Console.WriteLine("Longitude: " + pEx);
            }
        }
Esempio n. 22
0
 public void StartListenChanges()
 {
     if (!_started && IsLocationAvailable())
     {
         _started = true;
         try
         {
             CrossGeolocator.Current.PositionChanged -= Current_PositionChanged;
             CrossGeolocator.Current.PositionChanged += Current_PositionChanged;
             CrossGeolocator.Current.GetLastKnownLocationAsync().ContinueWith((t) =>
             {
                 if (t.Result != null)
                 {
                     LastGeolocation = new Geolocation(t.Result.Latitude, t.Result.Longitude, true);
                 }
             });
             CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromMinutes(10)).ContinueWith((t) =>
             {
                 if (t.Result != null)
                 {
                     LastGeolocation = new Geolocation(t.Result.Latitude, t.Result.Longitude, true);
                 }
             });
             CrossGeolocator.Current.StartListeningAsync(
                 minimumTime: TimeSpan.FromMinutes(2),
                 minimumDistance: GeolocationMetersMinimumDistance,
                 listenerSettings: new ListenerSettings()
             {
                 ActivityType = ActivityType.Other
             });
         }
         catch (Exception e)
         {
             Log.Error("Error while initializing GeolocationDataHandler", e);
         }
     }
 }
        private async Task GetGpsLocation()
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.High);
                var location = await Geolocation.GetLocationAsync(request, CancellationToken.None).ConfigureAwait(false);

                if (location != null)
                {
                    _settingsService.Latitude  = location.Latitude.ToString();
                    _settingsService.Longitude = location.Longitude.ToString();
                }
            }
            catch (Exception ex)
            {
                if (ex is FeatureNotEnabledException || ex is FeatureNotEnabledException || ex is PermissionException)
                {
                    _settingsService.AllowGpsLocation = false;
                }

                // Unable to get location
                Debug.WriteLine(ex);
            }
        }
Esempio n. 24
0
        public async Task ReciveGeo()
        {
            try
            {
                //var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));

                var location = await Geolocation.GetLocationAsync(request);

                string teststop = "";

                if (location != null)
                {
                    XLatitude  = location.Latitude;
                    YLongitude = location.Longitude;
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
            // return coordinates;
            // return result;
        }
Esempio n. 25
0
        private async Task GetLocation()
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    var placemarks = await Geocoding.GetPlacemarksAsync(location.Latitude, location.Longitude);

                    var placemark = placemarks?.FirstOrDefault();

                    if (placemark != null)
                    {
                        ViewModel.Zip = placemark.PostalCode;
                        GetWeather(null, null);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 26
0
        protected Venue UpdateVenue(Geolocation item, Venue FilVenue, int FilCityId, Guid ModifiedBy)
        {
            string VenueName = "";

            if (item.Label == null)
            {
                VenueName = item.Address;
            }
            else
            {
                VenueName = item.Label;
            }
            //Venue
            Venue FilVenueInserted = new Venue();

            if (FilVenue == null)
            {
                Venue newFilVenue = new Venue
                {
                    AltId          = Guid.NewGuid(),
                    Name           = VenueName,
                    AddressLineOne = item.Address,
                    CityId         = FilCityId,
                    Latitude       = item.Latitude,
                    Longitude      = item.Longitude,
                    ModifiedBy     = ModifiedBy,
                    IsEnabled      = true
                };
                FilVenueInserted = _venueRepository.Save(newFilVenue);
            }
            else
            {
                FilVenueInserted = FilVenue;
            }
            return(FilVenueInserted);
        }
Esempio n. 27
0
 /// <inheritdoc/>
 public new async Task <IChromiumBrowserContext> NewContextAsync(
     string userAgent                = null,
     bool?bypassCSP                  = null,
     bool?javaScriptEnabled          = null,
     string timezoneId               = null,
     Geolocation geolocation         = null,
     ContextPermission[] permissions = null,
     bool?isMobile               = null,
     bool?offline                = null,
     decimal?deviceScaleFactor   = null,
     Credentials httpCredentials = null,
     bool?hasTouch               = null,
     bool?acceptDownloads        = null,
     bool?ignoreHTTPSErrors      = null,
     ColorScheme?colorScheme     = null,
     string locale               = null,
     Dictionary <string, string> extraHttpHeaders = null,
     RecordVideoOptions recordVideo = null)
 => await base.NewContextAsync(
     userAgent,
     bypassCSP,
     javaScriptEnabled,
     timezoneId,
     geolocation,
     permissions,
     isMobile,
     offline,
     deviceScaleFactor,
     httpCredentials,
     hasTouch,
     acceptDownloads,
     ignoreHTTPSErrors,
     colorScheme,
     locale,
     extraHttpHeaders,
     recordVideo).ConfigureAwait(false) as IChromiumBrowserContext;
Esempio n. 28
0
        private async void CheckGeolocation()
        {
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(2));
                cts = new CancellationTokenSource();

                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                if (location != null)
                {
                    BuilderData.geoLocation = location.Latitude + " " + location.Longitude;

                    NetworkClient client = new NetworkClient();
                    client.ConnectToServer();
                    client.SetBuilderLastGeoLocation();
                    client.CloseConnection();
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }
Esempio n. 29
0
        async void OnButtonClicked(object sender, EventArgs args)
        {
            string locationResult = "";

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Permission.Granted)
            {
                //Configure the gps
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = Geolocation.GetLocationAsync(request);
                if (location != null)
                {
                    locationResult = location.Result.Longitude.ToString() + "," + location.Result.Latitude.ToString();
                }
            }
            else
            {
                // The app does not have permission ACCESS_FINE_LOCATION
            }

            //Retrieve cross page shared data
            var userEmail = Intent.GetStringExtra("user");

            SendEmail(locationResult, userEmail);
        }
Esempio n. 30
0
        async Task GetCurrentLocation()
        {
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                cts = new CancellationTokenSource();
                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                if (location != null)
                {
                    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");

                    latitude  = location.Latitude;
                    longitude = location.Longitude;

                    await InitializeGetWeatherAsyncLocation();
                    await InitializeGetWeatherAsyncLocationForecast();
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }
        public ActionResult New([Bind(Exclude = "ConstituentID")] Constituent constituent)
        {
            if (ModelState.IsValid)
            {
                // Determine what the current highest ID is, then increment by one
                Constituent[] allConstituents  = unitOfWork.Constituents.GetConstituents().OrderByDescending(x => x.ConstituentID).ToArray();
                int           newConstituentID = allConstituents[0].ConstituentID + 1;

                // Use that number as the ID for this Constituent
                constituent.ConstituentID = newConstituentID;

                // Calculate their latitude and longitude
                Geolocation geo = new Geolocation();
                geo.GetGeocode(constituent.getFullAddress());
                constituent.Latitude  = Convert.ToDecimal(geo.Latitude);
                constituent.Longitude = Convert.ToDecimal(geo.Longitude);

                unitOfWork.Constituents.Add(constituent);
                unitOfWork.Complete();
                return(RedirectToAction("Index"));
            }

            return(View(constituent));
        }
 public static Location GetLocation()
 {
     try
     {
         return(Geolocation.GetLastKnownLocationAsync().Result);
     }
     catch (FeatureNotSupportedException fnsEx)
     {
         Console.WriteLine($"GeoLocation GetLocation feature is not supported: {fnsEx.Message}");
     }
     catch (FeatureNotEnabledException fneEx)
     {
         Console.WriteLine($"Geolocation GetLocation feature is not enabled: {fneEx.Message}");
     }
     catch (PermissionException pEx)
     {
         Console.WriteLine($"Geolocation GetLocation feature is not permitted: {pEx.Message}");
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Unable to get location: {ex.Message}");
     }
     return(new Location());
 }
Esempio n. 33
0
 // Use this for initialization
 void Start()
 {
     _camvec = new GPSCameraVector ();
     _camloc = new Geolocation ();
     //_camloc.initGPS ();
     _vecLength = 1;
     _initialized = false;
     //checkGPS ();
 }
Esempio n. 34
0
    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        AndroidJNI.AttachCurrentThread();
        //gpsActivityJavaClass = new AndroidJavaClass ("com.TeamWARIS.WARISProject.CustomGPS");
        _camLoc = gameObject.AddComponent<Geolocation>();
        _camLoc.initGPS();
        _directionx = 0;
        _directiony = 1;
        setCamVecLength(0.00015);
        checkGPS();
        gcs = GetComponent<GUIControllerScript>();
        _location = "";
        _GUIWindow = new Rect(Screen.width / 4 + 10, (Screen.height / 2) + 10, Screen.width / 4 - 20, (Screen.height / 2) - 35);

        rc = (ResourceController)GameObject.Find ("Resource Controller").GetComponent<ResourceController> ();
        buildingManager = rc.GetBuildingManager ();
        staffManager = rc.GetStaffManager ();
        lectureManager = rc.GetLectureManager ();

        gpsActivityJavaClass = new AndroidJavaClass ("com.TeamWARIS.WARISProject.CustomGPS");
    }
Esempio n. 35
0
 /// <summary>
 /// Click event to set the current location and update our server
 /// with the user's new geolocation information.
 /// </summary>
 /// <param name="sender">Sender.</param>
 /// <param name="e">E.</param>
 private void mButtonSetLocation_Click(object sender, EventArgs e)
 {
     Location location = locationManager.GetLastKnownLocation(provider);
     userProfile.current_lat = location.Latitude;
     userProfile.current_long = location.Longitude;
     Geolocation currentLocation = new Geolocation(userProfile.username, location.Latitude, location.Longitude);
     currentLocation.UpdateGeolocation(userProfile.token);
     Toast.MakeText(this, "Set Location Successfully", ToastLength.Short).Show();
 }
		/// <summary>
		/// Gets the location manager and creates a new Geolocation object with
		/// the user's current location and receives a list from our server
		/// containing all of the nearby users based on that geolocation.
		/// The list is parsed and the profile bios are formatted and placed 
		/// into a string array with the same corresponding index of the string
		/// array of nearby usernames.
		/// </summary>
		/// <param name="savedInstanceState">Bundle.</param>
		public override void OnActivityCreated(Bundle savedInstanceState)
		{
			base.OnActivityCreated(savedInstanceState);

			var ProfileFrame = Activity.FindViewById<View>(Resource.Id.UserProfile);

			// If running on a tablet, then the layout in Resources/Layout-Large will be loaded. 
			// That layout uses fragments, and defines the detailsFrame. We use the visiblity of 
			// detailsFrame as this distinguisher between tablet and phone.
			isDualPane = ProfileFrame != null && ProfileFrame.Visibility == ViewStates.Visible;


			// Get the location manager
			locationManager = (LocationManager) Config.context.GetSystemService(Context.LocationService);
			// Define the criteria how to select the location provider -> use default
			Criteria criteria = new Criteria();
			criteria.Accuracy = Accuracy.Fine;
			provider = locationManager.GetBestProvider(criteria, true);
			Location location = locationManager.GetLastKnownLocation(provider);

            //Create a Geolocation object which handles most of the location related functionality, including server calls
            Geolocation currentLocation = new Geolocation (MainActivity.username, location.Latitude, location.Longitude);

            //Get the list of nearby profiles
            Task<List<Profile>> nearbyProfiles = Task<List<Profile>>.Factory.StartNew(() => 
				{ 
					return currentLocation.GetNearbyUsers().Result;
				});

            //Filter the list of profiles, removing the profile for this user, if it was returned by the server
            nearbyUserslist = new List<Profile>();
			try{
				nearbyUserslist = nearbyProfiles.Result;
				foreach (Profile p in nearbyUserslist){
					if(p.username.Equals(MainActivity.credentials.username)){
						nearbyUserslist.Remove(p);
						break;
					}
				}
			}
			catch(Exception e) {
				string error = e.Message;
				System.Diagnostics.Debug.WriteLine ("\n\nServer offline\n\n" + error);
			}

            //Create the arrays containing the information about the users
			int numUsers = nearbyUserslist.Count;
			string[] nearbyUsers = new string[numUsers];
			nearbyBios = new string[numUsers];

            //Process the information about the nearby users in a formatted string, for display
			for (int i = 0; i < numUsers; i++)
			{
				nearbyUsers [i] = nearbyUserslist [i].username;
				nearbyBios [i] = "⇧ " + nearbyUserslist[i].positive_votes 
					+ "\n⇩ " + nearbyUserslist[i].negative_votes 
					+ "\n\n" + nearbyUserslist [i].gender
					+ "\n\n" + nearbyUserslist [i].bio;
			}
		
            //Set up the adapted to display the list of users
			var adapter = new ArrayAdapter<String>(Activity, Android.Resource.Layout.SimpleListItemChecked, nearbyUsers);
			ListAdapter = adapter;

			if (savedInstanceState != null)
			{
				selectedUserId = savedInstanceState.GetInt("selected_user_id", 0);
			}

			if (isDualPane)
			{
				ListView.ChoiceMode = ChoiceMode.Single;
				ShowProfile(selectedUserId);
			}
		}
Esempio n. 37
0
        /// <summary>
        /// Code to the executed when the activity is created
        /// </summary>
        /// <param name="bundle">Any additional data sent to the activity</param>
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view 
			SetContentView (Resource.Layout.message_spinner);

            //Create the spinner for the name of the nearby users
			Spinner spinner = FindViewById<Spinner> (Resource.Id.spinner);
			spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);

			// Get the location manager
			locationManager = (LocationManager)Config.context.GetSystemService (Context.LocationService);

			// Define the criteria how to select the location provider -> use default
			Criteria criteria = new Criteria ();
			criteria.Accuracy = Accuracy.Fine;
			provider = locationManager.GetBestProvider (criteria, true);
			Location location = locationManager.GetLastKnownLocation (provider);

            //Create a Geolocation object which handles most of the location related functionality, including server calls
			Geolocation currentLocation = new Geolocation (MainActivity.username, location.Latitude, location.Longitude);

            //Get the list of nearby profiles
			Task<List<Profile>> nearbyProfiles = Task<List<Profile>>.Factory.StartNew (() => { 
				return currentLocation.GetNearbyUsers ().Result;
			});

            //Filter the list of profiles, removing the profile for this user, if it was returned by the server
			nearbyUserslist = new List<Profile> ();
			try {
				nearbyUserslist = nearbyProfiles.Result;
				foreach (Profile p in nearbyUserslist) {
					if (p.username.Equals (MainActivity.credentials.username)) {
						nearbyUserslist.Remove (p);
						break;
					}
				}
			} catch (Exception e) {
				string error = e.Message;
				System.Diagnostics.Debug.WriteLine ("\n\nServer offline\n\n" + error);
			}

            //Create an array containing all the usernames of the nearby users
			string[] nearbyUsers = new string[nearbyUserslist.Count];

			for (int i = 0; i < nearbyUserslist.Count; i++) {
				nearbyUsers [i] = nearbyUserslist [i].username;
			}

            //Set up the spinner object to user the array of nearby users
			var adapter = new ArrayAdapter<String> (this, Android.Resource.Layout.SimpleListItemChecked, nearbyUsers);

			adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
			spinner.Adapter = adapter;

			mMessage = FindViewById<EditText> (Resource.Id.sendMessageTxt);
			mSendMessage = FindViewById<Button> (Resource.Id.btnSendMsg);

			mSendMessage.Click += MSendMessage_Click;
		}