internal void StartLocationUpdates()
        {
            LocationRequest mLocationRequest = new LocationRequest();
              mLocationRequest.SetInterval(CrossGeofence.LocationUpdatesInterval == 0 ? 30000 : CrossGeofence.LocationUpdatesInterval);
              mLocationRequest.SetFastestInterval(CrossGeofence.FastestLocationUpdatesInterval == 0 ? 5000 : CrossGeofence.FastestLocationUpdatesInterval);
              string priorityType="Balanced Power";
              switch(CrossGeofence.GeofencePriority)
              {
              case GeofencePriority.HighAccuracy:
                  priorityType="High Accuracy";
                  mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                  break;
              case GeofencePriority.LowAccuracy:
                  priorityType="Low Accuracy";
                  mLocationRequest.SetPriority(LocationRequest.PriorityLowPower);
                  break;
              case GeofencePriority.LowestAccuracy:
                  priorityType="Lowest Accuracy";
                  mLocationRequest.SetPriority(LocationRequest.PriorityNoPower);
                  break;
              case GeofencePriority.MediumAccuracy:
              case GeofencePriority.AcceptableAccuracy:
              default:
                  mLocationRequest.SetPriority(LocationRequest.PriorityBalancedPowerAccuracy);
                  break;
              }

              Debug.WriteLine("{0} - {1}: {2}", CrossGeofence.Id, "Priority set to", priorityType);
              //(Regions.Count == 0) ? (CrossGeofence.SmallestDisplacement==0?50 :CrossGeofence.SmallestDisplacement): Regions.Min(s => (float)s.Value.Radius)
              if(CrossGeofence.SmallestDisplacement>0)
              {
              mLocationRequest.SetSmallestDisplacement(CrossGeofence.SmallestDisplacement);
              Debug.WriteLine("{0} - {1}: {2} meters", CrossGeofence.Id, "Location smallest displacement set to", CrossGeofence.SmallestDisplacement);
              }

              LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, mLocationRequest, GeofenceLocationListener.SharedInstance);
        }
Example #2
0
        // Lighthouse

        private async void StartLighthouse()
        {
            System.Diagnostics.Debug.WriteLine("StartLighthouse");

            // Initialize Estimote (TODO: Remove values when distributing)
            EstimoteSdk.Common.Config.Estimote.EnableDebugLogging(true);
            EstimoteSdk.Common.Config.Estimote.Initialize(Application.Context, LHPEEstimoteId, LHPEEstimoteKey);

            // Initialize GPS Location
            if (IsPlayServicesAvailable())
            {
                locationRequest = new LocationRequest()
                                  .SetPriority(LocationRequest.PriorityBalancedPowerAccuracy)
                                  .SetInterval(1000)
                                  .SetFastestInterval(locationFrequencySeconds * 1000);
                locationCallback = new FusedLocationProviderCallback((MainActivity)CrossCurrentActivity.Current.Activity);

                fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
            }

            // Initialize lhpe
            await Lighthouse.Start(LHPEEnvironment, LHPEAppId, LHPEAppKey);

            // Stop Loading Activity, Start Main Activity
            var intent = new Intent(this, typeof(LHPEXamarinSample.Droid.MainActivity));

            StartActivity(intent);
        }
Example #3
0
        public void OnConnected(Bundle p0)
        {
            Log.Debug("LocClient", "Connected");

            if (currentRequest == ConnectionUpdateRequest.None)
            {
                return;
            }

            if (callbackIntent == null)
            {
                var intent = new Intent(this, typeof(BikrActivityService));
                callbackIntent = PendingIntent.GetService(this, Resource.Id.bikr_intent_location, intent, PendingIntentFlags.UpdateCurrent);
            }
            if (currentRequest == ConnectionUpdateRequest.Start)
            {
                var req = new LocationRequest()
                          .SetInterval(5000)
                          .SetFastestInterval(2000)
                          .SetSmallestDisplacement(5)
                          .SetPriority(LocationRequest.PriorityHighAccuracy);

                api.RequestLocationUpdates(client, req, callbackIntent);
                prevStoredLocation = api.GetLastLocation(client);
                Log.Info("LocClient", "Requested updates");
            }
            else
            {
                api.RemoveLocationUpdates(client, callbackIntent);
                prevStoredLocation = null;
                Log.Info("LocClient", "Finished updates");
            }
            currentRequest = ConnectionUpdateRequest.None;
            client.Disconnect();
        }
Example #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);


            Window.RequestFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.activity_main);

            if (IsGooglePlayServicesInstalled())
            {
                _fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
                _locationTextView            = FindViewById <TextView>(Resource.Id.textViewCoordinates);

                _locationRequest = new LocationRequest()
                                   .SetPriority(LocationRequest.PriorityHighAccuracy)
                                   .SetInterval(5 * 1000)
                                   .SetFastestInterval(5 * 1000);

                ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.AccessFineLocation }, RC_LOCATION_UPDATES_PERMISSION_CHECK);
            }

            InitializeDataSetFetchers();

            InitializeSearchStrategies();

            InitializeSearchAlgorithms();

            SetupDataSetSpinner();
            SetupSearchMethodSpinner();
            SetupSearchEditText();
        }
Example #5
0
        public async Task <Position> GetLocationAsync()
        {
            tcsResult = new TaskCompletionSource <bool>();
            Context context = Android.App.Application.Context;

            fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(context);
            LocationRequest locationRequest = new LocationRequest();

            //Set the location update interval (int milliseconds).
            locationRequest.SetInterval(10000);
            //Set the weight.
            locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);

            try
            {
                await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, this, Looper.MainLooper);

                await tcsResult.Task;
                Log.Info(Tag, $"User Location {userLocation.Longitude},{userLocation.Latitude}");
                return(userLocation);
            }
            catch (Exception e)
            {
                Log.Error(Tag, $"GetLocationAsync exception: {e.Message}");
            }

            return(null);
        }
Example #6
0
        public async Task <LocationRequest> SaveMyLocation(LocationRequest input)
        {
            var uri    = $"{Settings.SERVERENDPOINT}/Location/SaveMyLocation";
            var result = await _requestService.PostAsync <LocationRequest>(uri, input);

            return(result);
        }
 /**
  * Sets the location request parameters.
  */
 void CreateLocationRequest()
 {
     LocationRequest = new LocationRequest();
     LocationRequest.SetInterval(UpdateIntervalInMilliseconds);
     LocationRequest.SetFastestInterval(FastestUpdateIntervalInMilliseconds);
     LocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
 }
Example #8
0
        public override async void OnDestroy()
        {
            _log.Info("Service is stopped.");

            try
            {
                IsServiceRunning = false;
                if (_apiClient?.IsConnected == true)
                {
                    await LocationServices.FusedLocationApi.RemoveLocationUpdates(_apiClient, this);

                    _apiClient?.Disconnect();
                }

                _locRequest?.Dispose();
                _locRequest = null;

                _apiClient?.Dispose();
                _apiClient = null;
            }
            catch (Exception ex)
            {
                _log.Debug(ex);
            }

            base.OnDestroy();
        }
        public void CheckLocationSetting()
        {
            TestTip.Inst.ShowText("RequestLocationUpdatesWithCallback start");
            this.requestType             = CALLBACK;
            mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(new Context());
            mSettingsClient  = LocationServices.getSettingsClient(new Context());
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(5000);
            mLocationRequest.setPriority(102);
            // get LocationSettingsRequest
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
            builder.addLocationRequest(mLocationRequest);
            LocationSettingsRequest locationSettingsRequest = builder.build();

            Task task = mSettingsClient.checkLocationSettings(locationSettingsRequest);

            task.addOnSuccessListener(new HmsSuccessListener <LocationSettingsResponse>((LocationSettingsResponse setting) =>
            {
                var status = setting.getLocationSettingsStates();
                TestTip.Inst.ShowText($"isBlePresent :{status.isBlePresent()}");
                TestTip.Inst.ShowText($"isBleUsable :{status.isBleUsable()}");
                TestTip.Inst.ShowText($"isGpsPresent :{status.isGpsPresent()}");
                TestTip.Inst.ShowText($"isGpsUsable :{status.isGpsUsable()}");
                TestTip.Inst.ShowText($"isLocationPresent :{status.isLocationPresent()}");
                TestTip.Inst.ShowText($"isLocationUsable :{status.isLocationUsable()}");
                TestTip.Inst.ShowText($"isNetworkLocationPresent :{status.isNetworkLocationPresent()}");
                TestTip.Inst.ShowText($"isNetworkLocationUsable :{status.isNetworkLocationUsable()}");
            })).addOnFailureListener(new HmsFailureListener((Exception e) => SetSettingsFailuer(e)));
        }
        public void RequestLocationUpdates(int priority, int requestType)
        {
            TestTip.Inst.ShowText("RequestLocationUpdatesWithCallback start");
            this.requestType             = requestType;
            mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(new Context());
            mSettingsClient  = LocationServices.getSettingsClient(new Context());
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(5000);
            mLocationRequest.setPriority(priority);
            // get LocationSettingsRequest
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
            builder.addLocationRequest(mLocationRequest);
            LocationSettingsRequest locationSettingsRequest = builder.build();

            Task task = mSettingsClient.checkLocationSettings(locationSettingsRequest);

            task.addOnSuccessListener(new LocationSuccessListener((AndroidJavaObject o) =>
            {
                switch (requestType)
                {
                case CALLBACK:
                    SetCallbackSuccess();
                    break;

                case INTENT:
                    SetIntentSuccess();
                    break;

                case LocationHD:
                    SetHDSuccess();
                    break;
                }
            }));
            task.addOnFailureListener(new HmsFailureListener((Exception e) => SetSettingsFailuer(e)));
        }
Example #11
0
 public EventArgsBeforeWarp(LocationRequest req, int targetX, int targetY, int targetFacing)
 {
     this.WarpTargetLocation = req;
     this.WarpTargetX        = targetX;
     this.WarpTargetY        = targetY;
     this.WarpTargetFacing   = targetFacing;
 }
Example #12
0
        public void Api_Submit_InvalidLocationRequest_ReturnsNotFound(string cityName,
                                                                      ApiProxy apiProxy,
                                                                      ILocationRequest locationRequest,
                                                                      ILocationResponse locationResponse)
        {
            $"Given a cityName value of {cityName}"
            .x(() => locationRequest = new LocationRequest {
                CityName = cityName
            });

            "And an ApiProxy".x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the location request is submitted"
            .x(async() => locationResponse =
                   await apiProxy.SubmitLocationRequest(locationRequest).ConfigureAwait(false));

            "Then the location response should return HttpStatusCode.NotFound, and Locations should be empty"
            .x(() =>
            {
                using (new AssertionScope())
                {
                    locationResponse.StatusCode.Should().Be(HttpStatusCode.NotFound);
                    locationResponse.Locations.Should().BeNullOrEmpty();
                }
            });
        }
        public override async Task MakeNewBookingGRPC(EmptyRequest request, IServerStreamWriter <LocationRequest> responseStream, ServerCallContext context)
        {
            // lav facade kald her og gør det lig locations istedet
            List <LocationRequest> locationRequests = new List <LocationRequest>();
            List <Location>        locations        = DbFacade.GetAllLocations();

            foreach (var l in locations)
            {
                LocationRequest a = new LocationRequest()
                {
                    Address = l.Address,
                    City    = l.City,
                    Country = l.Country,
                    Id      = l.Id,
                    Zipcode = l.Zipcode
                };

                locationRequests.Add(a);
            }

            foreach (var location in locationRequests)
            {
                // this sends our CarReply class to the client one at a time, until there are no more
                // essentially making this method of type void, as opposed to the previous method that returns a type.

                await responseStream.WriteAsync(location);
            }
        }
Example #14
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            if (bundle != null)
            {
                isRequestingLocationUpdates = bundle.KeySet().Contains(KEY_REQUESTING_LOCATION_UPDATES) &&
                                              bundle.GetBoolean(KEY_REQUESTING_LOCATION_UPDATES);
            }
            else
            {
                isRequestingLocationUpdates = false;
            }

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            isGooglePlayServicesInstalled = IsGooglePlayServicesInstalled();
            rootLayout = FindViewById(Resource.Id.root_layout);

            // UI to display last location
            getLastLocationButton = FindViewById <Button>(Resource.Id.get_last_location_button);
            latitude  = FindViewById <TextView>(Resource.Id.latitude);
            longitude = FindViewById <TextView>(Resource.Id.longitude);
            provider  = FindViewById <TextView>(Resource.Id.provider);

            // UI to display location updates
            requestLocationUpdatesButton = FindViewById <Button>(Resource.Id.request_location_updates_button);
            latitude2  = FindViewById <TextView>(Resource.Id.latitude2);
            longitude2 = FindViewById <TextView>(Resource.Id.longitude2);
            provider2  = FindViewById <TextView>(Resource.Id.provider2);

            //addressText = FindViewById<TextView>(Resource.Id.address_text);
            //locationText = FindViewById<TextView>(Resource.Id.location_text);
            macAddressText   = FindViewById <TextView>(Resource.Id.macaddress);
            batteryLevelText = FindViewById <TextView>(Resource.Id.batterylevel);

            //batteryLevelText = FindViewById<TextView>(Resource.Id.batterylevel_text);
            //FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;


            if (isGooglePlayServicesInstalled)
            {
                locationRequest = new LocationRequest()
                                  .SetPriority(LocationRequest.PriorityHighAccuracy)
                                  .SetInterval(FIVE_MINUTES)
                                  .SetFastestInterval(TWO_MINUTES);
                locationCallback = new FusedLocationProviderCallback(this);

                fusedLocationProviderClient         = LocationServices.GetFusedLocationProviderClient(this);
                getLastLocationButton.Click        += GetLastLocationButtonOnClick;
                requestLocationUpdatesButton.Click += RequestLocationUpdatesButtonOnClick;
            }
            else
            {
                // If there is no Google Play Services installed, then this sample won't run.
                Snackbar.Make(rootLayout, Resource.String.missing_googleplayservices_terminating, Snackbar.LengthIndefinite)
                .SetAction(Resource.String.ok, delegate { FinishAndRemoveTask(); })
                .Show();
            }
        }
Example #15
0
 public OnCallbackSettingsSuccessListener(RequestWithCallbackActivity locationActivity, FusedLocationProviderClient fusedLocationProviderClient, LocationRequest locationRequest, LocationCallback callback)
 {
     this.locationActivity            = locationActivity;
     this.fusedLocationProviderClient = fusedLocationProviderClient;
     this.locationRequest             = locationRequest;
     this.locationCallback            = callback;
 }
Example #16
0
        public void Api_Submit_ValidLocationRequest_ReturnsCorrectWoeid(string cityName,
                                                                        int expectedCount,
                                                                        int expectedWoeid,
                                                                        ApiProxy apiProxy,
                                                                        ILocationRequest locationRequest,
                                                                        ILocationResponse locationResponse)
        {
            $"Given a cityName value of {cityName}"
            .x(() => locationRequest = new LocationRequest {
                CityName = cityName
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the location request is submitted"
            .x(async() => locationResponse =
                   await apiProxy.SubmitLocationRequest(locationRequest).ConfigureAwait(false));

            $"Then the location response should return HttpStatusCode.OK), CityName {cityName} and WoeId {expectedWoeid}"
            .x(() =>
            {
                using (new AssertionScope())
                {
                    locationResponse.StatusCode.Should().Be(HttpStatusCode.OK);
                    locationResponse.Locations.Should().HaveCount(expectedCount);
                    locationResponse.Locations[0].WoeId.Should().Be(expectedWoeid);
                }
            });
        }
Example #17
0
        public void OnConnected(Bundle p0)
        {
            Log.Debug ("LocClient", "Connected");
            if (currentRequest == ConnectionUpdateRequest.None)
                return;

            if (callbackIntent == null) {
                var intent = new Intent (this, typeof(BikrActivityService));
                callbackIntent = PendingIntent.GetService (this, Resource.Id.bikr_intent_location, intent, PendingIntentFlags.UpdateCurrent);
            }
            if (currentRequest == ConnectionUpdateRequest.Start) {
                var req = new LocationRequest ()
                    .SetInterval (5000)
                    .SetFastestInterval (2000)
                    .SetSmallestDisplacement (5)
                    .SetPriority (LocationRequest.PriorityHighAccuracy);
                client.RequestLocationUpdates (req, callbackIntent);
                prevStoredLocation = client.LastLocation;
                Log.Info ("LocClient", "Requested updates");
            } else {
                client.RemoveLocationUpdates (callbackIntent);
                prevStoredLocation = null;
                Log.Info ("LocClient", "Finished updates");
            }
            currentRequest = ConnectionUpdateRequest.None;
            client.Disconnect ();
        }
Example #18
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            try
            {
                if (AppStatus.UserLogged == null)
                {
                    MyTrapBDConfig.Initialize();

                    AppStatus.UserLogged = UserApiService.GetUserLogged();
                }

                if (AppStatus.UserLogged != null)
                {
                    Token = AppStatus.UserLogged.Token;

                    apiClient = new GoogleApiClient.Builder(Context, this, this).AddApi(LocationServices.API).Build();

                    locRequest = new LocationRequest();

                    apiClient.Connect();

                    IsStarted = true;
                }
                else
                {
                    StopSelf();
                }
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }

            return(StartCommandResult.Sticky);
        }
        private static LocationRequest CreateLocationRequest(MvxLocationOptions options)
        {
            // NOTE options.TrackingMode is not supported

            var request = LocationRequest.Create();

            switch (options.Accuracy)
            {
            case MvxLocationAccuracy.Fine:
                request.SetPriority(LocationRequest.PriorityHighAccuracy);
                break;

            case MvxLocationAccuracy.Coarse:
                request.SetPriority(LocationRequest.PriorityBalancedPowerAccuracy);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            request.SetInterval((long)options.TimeBetweenUpdates.TotalMilliseconds);
            request.SetSmallestDisplacement(options.MovementThresholdInM);

            return(request);
        }
Example #20
0
 void GPS_StatusChange()
 {
     try
     {
         if (_locationService is null)
         {
             _locationManager = (LocationManager)GetSystemService(Context.LocationService);
             Criteria criteriaForLocationService = new Criteria
             {
                 Accuracy = Accuracy.Fine
             };
             IList <string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
             if (acceptableLocationProviders.Any())
             {
                 _locationManager.RequestLocationUpdates(acceptableLocationProviders.First(), 0, 0, this);
             }
             _locationService = LocationServices.GetFusedLocationProviderClient(this);
             var locationRequest = new LocationRequest();
             locationRequest.SetInterval(180000);
             locationRequest.SetFastestInterval(90000);
             locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
             _providerCallback = new FusedLocationProviderCallback();
             _locationService.RequestLocationUpdates(locationRequest, _providerCallback, Looper.MyLooper());
         }
     }
     catch (Exception e)
     {
         //Crashes.TrackError(e);
     }
 }
        public override async Task ShowAvailableCarsGRPC(LocationRequest request, IServerStreamWriter <CarReply> responseStream, ServerCallContext context)
        {
            // facade kald til alle cars på en given location istedet
            Location        l          = new Location(request.Id, request.Address, request.City, request.Zipcode, request.Country);
            List <Car>      cars       = DbFacade.GetAvailableCars(l);
            List <CarReply> carReplies = new List <CarReply>();

            foreach (var car in cars)
            {
                CarReply c = new CarReply()
                {
                    AnimalsAllowed = car.AnimalsAllowed,
                    Brand          = car.Brand,
                    CarId          = car.Id,
                    Color          = car.Color,
                    Doors          = car.Doors,
                    FuelType       = car.FuelType,
                    LicensePlate   = car.LicensePlate,
                    Model          = car.Model,
                    Price          = car.Price,
                    Type           = car.Type
                };
                carReplies.Add(c);
            }
            foreach (var car in carReplies)
            {
                // this sends our CarReply class to the client one at a time, until there are no more
                // essentially making this method of type void, as opposed to the previous method that returns a type.
                await responseStream.WriteAsync(car);
            }
        }
        async Task <bool> CheckLocationAvailability(LocationRequest locationRequest)
        {
            // Build a new request with the given location request
            var locationSettingsRequest = new LocationSettingsRequest.Builder()
                                          .AddLocationRequest(locationRequest)
                                          .Build();

            // Ask the Settings API if we can fulfill this request
            var locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, locationSettingsRequest);


            // If false, we might be able to resolve it by showing the location settings
            // to the user and allowing them to change the settings
            if (!locationSettingsResult.Status.IsSuccess)
            {
                if (locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired)
                {
                    locationSettingsResult.Status.StartResolutionForResult(this, 101);
                }
                else
                {
                    Toast.MakeText(this, "Location Services Not Available for the given request.", ToastLength.Long).Show();
                }

                return(false);
            }

            return(true);
        }
Example #23
0
        public async Task <bool> AddOrUpdateUserLocationAsync(string userId, LocationRequest currentPosition)
        {
            // Get the list of ordered regions the user currently is within
            var currentUserAreaLocationList = await _locationsRepository.GetCurrentUserRegionsListAsync(currentPosition);

            if (currentUserAreaLocationList is null)
            {
                throw new LocationDomainException("User current area not found");
            }

            // If current area found, then update user location
            var locationAncestors = new List <string>();
            var userLocation      = await _locationsRepository.GetUserLocationAsync(userId);

            userLocation            = userLocation ?? new UserLocation();
            userLocation.UserId     = userId;
            userLocation.LocationId = currentUserAreaLocationList[0].LocationId;
            userLocation.UpdateDate = DateTime.UtcNow;
            await _locationsRepository.UpdateUserLocationAsync(userLocation);

            // Publish integration event to update marketing read data model
            // with the new locations updated
            PublishNewUserLocationPositionIntegrationEvent(userId, currentUserAreaLocationList);

            return(true);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_huaweilocation);
            //Button click listeners
            FindViewById(Resource.Id.location_requestLocationUpdatesWithCallback).SetOnClickListener(this);
            FindViewById(Resource.Id.location_removeLocationUpdatesWithcallback).SetOnClickListener(this);


            AddLogFragment();

            mFusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
            mSettingsClient  = LocationServices.GetSettingsClient(this);
            mLocationRequest = new LocationRequest();
            // Sets the interval for location update (unit: Millisecond)
            mLocationRequest.SetInterval(5000);
            // Sets the priority
            mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            if (null == mLocationCallback)
            {
                mLocationCallback = new LocationCallbackImpl();
            }
            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
            {
                string[] strings =
                { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation };
                ActivityCompat.RequestPermissions(this, strings, 1);
            }
        }
Example #25
0
        public async void turnOnGps()
        {
            try
            {
                MainActivity activity = global::Xamarin.Forms.Forms.Context as MainActivity;

                GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity).AddApi(LocationServices.API).Build();
                googleApiClient.Connect();
                LocationRequest locationRequest = LocationRequest.Create();
                locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                locationRequest.SetInterval(10000);
                locationRequest.SetFastestInterval(10000 / 2);

                LocationSettingsRequest.Builder
                    locationSettingsRequestBuilder = new LocationSettingsRequest.Builder().AddLocationRequest(locationRequest);
                locationSettingsRequestBuilder.SetAlwaysShow(false);
                LocationSettingsResult locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(
                    googleApiClient, locationSettingsRequestBuilder.Build());


                if (locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired)
                {
                    locationSettingsResult.Status.StartResolutionForResult(activity, 0);
                }

                var result = await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, locationSettingsRequestBuilder.Build());
            }
            catch (Exception ex)
            {
            }
        }
Example #26
0
        async Task<bool> CheckLocationAvailability (LocationRequest locationRequest)
        {
            // Build a new request with the given location request
            var locationSettingsRequest = new LocationSettingsRequest.Builder ()
                .AddLocationRequest (locationRequest)
                .Build ();

            // Ask the Settings API if we can fulfill this request
            var locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync (googleApiClient, locationSettingsRequest);


            // If false, we might be able to resolve it by showing the location settings 
            // to the user and allowing them to change the settings
            if (!locationSettingsResult.Status.IsSuccess) {
                
                if (locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired)
                    locationSettingsResult.Status.StartResolutionForResult (this, 101);
                else 
                    Toast.MakeText (this, "Location Services Not Available for the given request.", ToastLength.Long).Show ();

                return false;
            }

            return true;
        }
Example #27
0
 private void CreateLocationRequest()
 {
     locRequest = new LocationRequest();
     locRequest.SetInterval(5000);
     locRequest.SetFastestInterval(4000);
     locRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
 }
Example #28
0
        public virtual IHttpActionResult SaveCurrentLocation([FromBody] LocationRequest locationRequest)
        {
            var response        = new InsertLocationResponse();
            var requestValidate = new ValidateRequestEngine(locationRequest);

            try
            {
                if (requestValidate.IsValid)
                {
                    LocationDa da = new LocationDa();
                    da.SaveChanges(LocationConverter.Convert(locationRequest));
                    response.Success = true;
                    response.Message = "Saved Location.";
                    da.Dispose();
                }
                else
                {
                    response.Success = false;
                    response.Message = requestValidate.Message;
                    return(new HttpActionResult(HttpStatusCode.BadRequest, response));
                }
            }
            catch (Exception ex)
            {
            }
            return(new HttpActionResult(HttpStatusCode.OK, response));
        }
Example #29
0
        //set user location info
        public dynamic SetUserLocationInfo(LocationRequest request, int id)
        {
            dynamic result = null;

            try
            {
                var dyParam = new OracleDynamicParameters();
                dyParam.Add("p_id", OracleDbType.Int32, ParameterDirection.Input, id, sizeof(Int32));
                dyParam.Add("p_country", OracleDbType.Varchar2, ParameterDirection.Input, request.country, request.country.Length * sizeof(Char));
                dyParam.Add("p_city", OracleDbType.Varchar2, ParameterDirection.Input, request.city, request.city.Length * sizeof(Char));
                dyParam.Add("p_latitude", OracleDbType.Varchar2, ParameterDirection.Input, request.latitude, request.latitude.Length * sizeof(Char));
                dyParam.Add("p_longitude", OracleDbType.Varchar2, ParameterDirection.Input, request.longitude, request.longitude.Length * sizeof(Char));

                dyParam.Add("cursorParam", OracleDbType.RefCursor, ParameterDirection.Output);

                var conn = MatchboxConnection.GetConnection(this.configuration);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                if (conn.State == ConnectionState.Open)
                {
                    var query = "USP_SETUSERLOCATIONINFO";
                    result = SqlMapper.Query(conn, query, param: dyParam, commandType: CommandType.StoredProcedure);
                }
            }
            catch (Exception ex)
            {
                // throw ex;
                result = "ERROR";
            }
            return(result);
        }
Example #30
0
        public async Task StartListener(GpsRequest?request = null)
        {
            if (this.IsListening)
            {
                return;
            }

            request = request ?? new GpsRequest();
            var access = await this.RequestAccess(request);

            access.Assert();

            var nativeRequest = LocationRequest
                                .Create()
                                .SetPriority(GetPriority(request.Priority))
                                .SetInterval(request.Interval.ToMillis());

            if (request.ThrottledInterval != null)
            {
                nativeRequest.SetFastestInterval(request.ThrottledInterval.Value.ToMillis());
            }

            await this.client.RequestLocationUpdatesAsync(
                nativeRequest,
                this.GetPendingIntent() // used for background - should switch to LocationCallback for foreground
                );

            this.IsListening = true;
        }
Example #31
0
        async Task StartLocationUpdatesAsync()
        {
            // Create a callback that will get the location updates
            if (locationCallback == null)
            {
                locationCallback = new MyLocationCallback();
                locationCallback.LocationUpdated += OnLocationResult;
            }

            // Get the current client
            if (locationClient == null)
            {
                locationClient = LocationServices.GetFusedLocationProviderClient(this);
            }

            try
            {
                //Create request and set intervals:
                //Interval: Desired interval for active location updates, it is inexact and you may not receive upates at all if no location servers are available
                //Fastest: Interval is exact and app will never receive updates faster than this value
                var locationRequest = new LocationRequest()
                                      .SetInterval(10000)
                                      .SetFastestInterval(5000)
                                      .SetPriority(LocationRequest.PriorityHighAccuracy);

                await locationClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);
            }
            catch (Exception)
            {
            }
        }
Example #32
0
		////Lifecycle methods

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			Log.Debug ("OnCreate", "OnCreate called, initializing views...");

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// UI to print last location
			button = FindViewById<Button> (Resource.Id.myButton);
			latitude = FindViewById<TextView> (Resource.Id.latitude);
			longitude = FindViewById<TextView> (Resource.Id.longitude);
			provider = FindViewById<TextView> (Resource.Id.provider);

			// UI to print location updates
			button2 = FindViewById<Button> (Resource.Id.myButton2);
			latitude2 = FindViewById<TextView> (Resource.Id.latitude2);
			longitude2 = FindViewById<TextView> (Resource.Id.longitude2);
			provider2 = FindViewById<TextView> (Resource.Id.provider2);

			_isGooglePlayServicesInstalled = IsGooglePlayServicesInstalled ();

			if (_isGooglePlayServicesInstalled) {
				// pass in the Context, ConnectionListener and ConnectionFailedListener
				locClient = new LocationClient (this, this, this);

				// generate a location request that we will pass into a call for location updates
				locRequest = new LocationRequest ();

			} else {
				Log.Error ("OnCreate", "Google Play Services is not installed");
			}

		}
 protected void CreateLocationRequest()
 {
     mLocationRequest = new LocationRequest();
     mLocationRequest.SetInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
     mLocationRequest.SetFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
     mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
 }
Example #34
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get controls:
            _addressButton     = FindViewById <Button>(Resource.Id.MyButton);
            _locationsListView = FindViewById <ListView>(Resource.Id.LocationsListView);

            _addressButton.Text = "Location updating paused. Tap to start.";
            if (_googleApiClient == null)
            {
                _googleApiClient = new Builder(Application.Context, this, this)
                                   .AddApi(LocationServices.API)
                                   .Build();
            }

            _locRequest = new LocationRequest();
            _locRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            _locRequest.SetInterval(2000);
            _locRequest.SetFastestInterval(1000);

            // Get our button from the layout resource,
            // and attach an event to it
            _addressButton.Click += AddressButton_OnClick;

            _locationsListViewAdapter  = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleExpandableListItem1, _locationsListViewData);
            _locationsListView.Adapter = _locationsListViewAdapter;
        }
Example #35
0
        public void OnConnected ( Bundle connectionHint )
        {
            Log.Debug (TAG, "OnConnected");

            _locationRequest = LocationRequest.Create ();
            _locationRequest.SetInterval (1000);
            _locationRequest.SetFastestInterval (1000);
            _locationRequest.SetPriority (LocationRequest.PriorityHighAccuracy);
            LocationServices.FusedLocationApi.RequestLocationUpdates (_googleApiClient, _locationRequest, this);
        }
Example #36
0
        protected override bool isValid(out string exceptionMessage)
        {
            if (distance <= 0) {
                return makeExceptionMessage (out exceptionMessage, "The distance between the locations is invalid");
            }

            LocationRequest lr = new LocationRequest ();
            if (lr.fetchLocationFromAirports (start_airport, destination_airport).Count () != 0) {
                return makeExceptionMessage(out exceptionMessage, "There is already an traject between the given airports");
            }

            return validAirport(start_airport, out exceptionMessage) && validAirport(destination_airport, out exceptionMessage);
        }
Example #37
0
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Set up Google Play location service
			apiClient = new GoogleApiClient.Builder (this, this, this)
				.AddApi (LocationServices.API).Build ();
			apiClient.Connect ();

			lastLocationButton = FindViewById<Button> (Resource.Id.lastLocationButton);
			locationTextView = FindViewById<TextView> (Resource.Id.locationTextView);
			
			// Clicking the button will make a one-time call to get the device's last known location
			lastLocationButton.Click += delegate {
				Android.Locations.Location location = LocationServices.FusedLocationApi.GetLastLocation (apiClient);
				locationTextView.Text = "Last location:\n";
				DisplayLocation(location);
			};		

			locationUpdateButton = FindViewById<Button> (Resource.Id.locationUpdateButton);

			// Clicking the button will send a request for continuous updates
			locationUpdateButton.Click += async delegate {
				if (apiClient.IsConnected)
				{
					locationTextView.Text = "Requesting Location Updates";
					var locRequest = new LocationRequest();

					// Setting location priority to PRIORITY_HIGH_ACCURACY (100)
					locRequest.SetPriority(100);

					// Setting interval between updates, in milliseconds
					// NOTE: the default FastestInterval is 1 minute. If you want to receive location updates more than 
					// once a minute, you _must_ also change the FastestInterval to be less than or equal to your Interval
					locRequest.SetFastestInterval(500);
					locRequest.SetInterval(1000);

					// pass in a location request and LocationListener
					await LocationServices.FusedLocationApi.RequestLocationUpdates (apiClient, locRequest, this);
					// In OnLocationChanged (below), we will make calls to update the UI
					// with the new location data
				}
				else
				{
					locationTextView.Text = "Client API not connected";
				}
			};
		}
Example #38
0
        async Task RequestLocationUpdates ()
        {
            // Describe our location request
            var locationRequest = new LocationRequest ()
                .SetInterval (10000)
                .SetFastestInterval (1000)
                .SetPriority (LocationRequest.PriorityHighAccuracy);

            // Check to see if we can request updates first
            if (await CheckLocationAvailability (locationRequest)) {

                // Request updates
                await LocationServices.FusedLocationApi.RequestLocationUpdates (googleApiClient,
                    locationRequest, 
                    this);
            }
        }
        public Location GetLocation()
        {
            WlanClient.WlanClient client = new WlanClient.WlanClient();
            List<WifiAccessPoint> wifiAccessPoints = new List<WifiAccessPoint>();
            foreach (WlanClient.WlanClient.WlanInterface wlanInterface in client.Interfaces)
            {
                Wlan.WlanBssEntry[] bssList = wlanInterface.GetNetworkBssList();
                foreach (Wlan.WlanBssEntry bss in bssList)
                {
                    WifiAccessPoint accessPoint = new WifiAccessPoint();
                    accessPoint.macAddress = ByteArrayToMacAddress(bss.dot11Bssid);
                    wifiAccessPoints.Add(accessPoint);
                }
            }
            LocationRequest locationRequest = new LocationRequest();
            locationRequest.wifiAccessPoints = wifiAccessPoints.ToArray();
            string requestJson = JsonConvert.SerializeObject(locationRequest);
            byte[] requestBytes = GetBytes(requestJson);

            string url = "https://www.googleapis.com/geolocation/v1/geolocate";

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/json";
            webRequest.Accept = "*/*";
            webRequest.UserAgent = Program.APP_USER_AGENT;
            webRequest.ContentLength = requestBytes.Length;

            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(requestBytes, 0, requestBytes.Length);
            requestStream.Close();

            WebResponse response = webRequest.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);

            string responseJson = responseStreamReader.ReadToEnd();
            responseStreamReader.Close();
            responseStream.Close();

            return JsonConvert.DeserializeObject<LocationResponse>(responseJson).location;
        }
		public LocationProvider (Activity context)
		{
			Context = context;

			//apiClient = new GoogleApiClient.Builder (Android.App.Application.Context, this, this).AddApi (LocationServices.API).Build ();
			apiClient = new GoogleApiClient.Builder (Android.App.Application.Context, this, this).AddApi (LocationServices.API).Build ();

			locRequest = LocationRequest.Create ();

			// Setting location priority to PRIORITY_HIGH_ACCURACY (100)
			locRequest.SetPriority (100);

			// Setting interval between updates, in milliseconds
			// NOTE: the default FastestInterval is 1 minute. If you want to receive location updates more than 
			// once a minute, you _must_ also change the FastestInterval to be less than or equal to your Interval
			locRequest.SetFastestInterval (500);
			locRequest.SetInterval (1000);

			WriteLine ($"Request priority set to status code {locRequest.Priority}, interval set to {locRequest.Interval} ms");
		}
 public void OnConnected(Bundle bundle)
 {
     LocationClientConnected = true;
     var locationRequest = new LocationRequest ();
     locationRequest.SetInterval (5000);
     locationRequest.SetFastestInterval (1000);
     LocationClient.RequestLocationUpdates (locationRequest, this);
     if (MapViewFragment != null)
         MapViewFragment.FlyDownToMyLocation ();
 }
        private void locationRequest_ReadLocationFinished( LocationRequest locationRequest, TrackerState result )
        {
            if ( result.Error != null )
            return;

              try
              {
            lock ( this.statSync )
            {
              if ( this.succTime == null ||
               this.succTime.Value < result.CreateTime )
              {
            this.succTime = result.CreateTime;
              }
            }
              }
              catch ( Exception exc )
              { // don't really expect an exception here, but just to be on the safe side:
            LogManager.GetLogger( GetType( ) ).Error( exc );
              }
        }
 public override void RequestFinished( LocationRequest locReq, bool isTimedOut )
 {
     if ( isTimedOut )
     throw new ApplicationException( "Test requests should not time out" );
 }
Example #44
0
        ////Lifecycle methods
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            Log.Debug ("OnCreate", "OnCreate called, initializing views...");

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // UI to print last location
            button = FindViewById<Button> (Resource.Id.myButton);
            latitude = FindViewById<TextView> (Resource.Id.latitude);
            longitude = FindViewById<TextView> (Resource.Id.longitude);
            provider = FindViewById<TextView> (Resource.Id.provider);

            // UI to print location updates
            button2 = FindViewById<Button> (Resource.Id.myButton2);
            latitude2 = FindViewById<TextView> (Resource.Id.latitude2);
            longitude2 = FindViewById<TextView> (Resource.Id.longitude2);
            provider2 = FindViewById<TextView> (Resource.Id.provider2);

            //UI Sensor
            txtRaw = FindViewById<TextView>(Resource.Id.txtRaw);
            txtStdDev = FindViewById<TextView>(Resource.Id.txtStdDev);
            txtOverallDev = FindViewById<TextView>(Resource.Id.txtAvgStdDev);
            txtCondition = FindViewById<TextView>(Resource.Id.txtCondition);

            txtRange1 = FindViewById<EditText>(Resource.Id.txtRange1);
            txtRange2 = FindViewById<EditText>(Resource.Id.txtRange2);
            txtRange3 = FindViewById<EditText>(Resource.Id.txtRange3);
            txtRange4 = FindViewById<EditText>(Resource.Id.txtRange4);
            //txtRange1.Text = "0.45";
            //txtRange2.Text = "0.75";
            //txtRange3.Text = "1.2";
            //txtRange4.Text = "3";
            txtRange1.Text = "0.7";
            txtRange2.Text = "1.0";
            txtRange3.Text = "4";
            txtRange4.Text = "8";
            GPXDataSet.SlightBumpRange = 4;
            GPXDataSet.BumpRange = 8;

            //JK Socket
            _mySocket = new JKSocket("192.168.1.24", 1800);
            _mySocket.RecdDataEvent = recvText;
            _mySocket.StatusEvent = ClientStatusUpdate;

            _kmlGen = new KMLGenerator();
            btnGenerateCSV = FindViewById<Button>(Resource.Id.btnGenerateKML);
            togglebutton = FindViewById<ToggleButton>(Resource.Id.togglebutton);
            _tgStartStop = FindViewById<ToggleButton>(Resource.Id.tgStartStop);
            _tgStartStop.Checked = false;
            togglebutton.Checked = true;
            _mpWorse = MediaPlayer.Create(this, Resource.Raw.Worse);
            _mpSBumpy = MediaPlayer.Create(this, Resource.Raw.SBumpy);
            _mpBumpy = MediaPlayer.Create(this, Resource.Raw.Bumpy);

            mSensorManager = (SensorManager)GetSystemService(SensorService);
            _gpxDataSet = new GPXDataSet();
            GPXDataSet.PlayRoadStatus = new Action<RoadType>(PlayRoadType);
            _sensorData = new List<SensorData>();
            _tmrOverallAvg.Elapsed += new ElapsedEventHandler(_gpxDataSet.OnOverallAvgTimedEvent);
            _tmrOverallAvg.Interval = 5000;
            //_tmrOverallAvg.Enabled = true;

            _tmrSampling.Elapsed += new ElapsedEventHandler(this.OnSamplingTimedEvent);
            _tmrSampling.Interval = SAMPLE_TIME_INTERVAL;
            //_tmrSampling.Enabled = true;

            _tmrSampling.Enabled = false;
            _tmrOverallAvg.Enabled = false;

            mlistView = FindViewById<ListView>(Resource.Id.myListView);
            _arrAdp = new ListViewAdapter(this, _gpxDataSet.GPXDataList);
            mlistView.Adapter = _arrAdp;

            _isGooglePlayServicesInstalled = IsGooglePlayServicesInstalled ();

            if (_isGooglePlayServicesInstalled) {
                // pass in the Context, ConnectionListener and ConnectionFailedListener
                apiClient = new GoogleApiClientBuilder (this, this, this)
                    .AddApi (LocationServices.API).Build ();

                // generate a location request that we will pass into a call for location updates
                locRequest = new LocationRequest ();

            } else {
                Log.Error ("OnCreate", "Google Play Services is not installed");
                Toast.MakeText (this, "Google Play Services is not installed", ToastLength.Long).Show ();
                Finish ();
            }
        }
Example #45
0
		protected void CreateLocationRequest ()
		{
			mLocationRequest = new LocationRequest ();

			mLocationRequest.SetInterval (UPDATE_INTERVAL_IN_MILLISECONDS);

			mLocationRequest.SetFastestInterval (FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

			mLocationRequest.SetPriority (LocationRequest.PriorityHighAccuracy);
		}
        protected override void PlatformSpecificStart(MvxLocationOptions options)
        {
            if (_googleApiClient != null)
                throw new MvxException("You cannot start MvxLocation service more than once");

            if (GooglePlayServicesUtil.IsGooglePlayServicesAvailable(Context) != ConnectionResult.Success)
                throw new MvxException("Google Play Services are not available");

            _locationRequest = LocationRequest.Create();
            _locationRequest.SetInterval((long)options.TimeBetweenUpdates.TotalMilliseconds);
            _locationRequest.SetSmallestDisplacement(options.MovementThresholdInM);
            _locationRequest.SetFastestInterval(1000);

            _locationRequest.SetPriority(options.Accuracy == MvxLocationAccuracy.Fine
                ? LocationRequest.PriorityHighAccuracy
                : LocationRequest.PriorityBalancedPowerAccuracy);

            _googleApiClient = new GoogleApiClient.Builder(this.Context)
                .AddApi(LocationServices.API)
                .AddConnectionCallbacks(_connectionCallBacks)
                .AddOnConnectionFailedListener(_connectionFailed)
                .Build();

            //_locationClient = new LocationClient(Context, _connectionCallBacks, _connectionFailed);
            //_locationClient.Connect();
            _googleApiClient.Connect();
        }
		public void Start (MvxLocationOptions options)
		{
			_request = CreateLocationRequest (options);
			_client.Connect ();
		}
        private void EnsureStopped()
        {
            if (_googleApiClient == null) return;

            LocationServices.FusedLocationApi.RemoveLocationUpdates(_googleApiClient, _locationListener);
            _googleApiClient.Disconnect();
            _googleApiClient = null;
            //_locationClient.RemoveLocationUpdates(_locationListener);
            //_locationClient.Disconnect();
            //_locationClient = null;
            _locationRequest = null;
        }
        public override void RequestFinished( LocationRequest locReq, bool isTimedOut )
        {
            if ( this.consequentErrorsCounter == null )
            return;

              if ( !isTimedOut )
              {
            this.consequentErrorsCounter.TimedOutRequestsCounter.Reset( );
              }
              else
              {
            bool shouldReportProblem;
            int consequentErrorsCount =
              this.consequentErrorsCounter.TimedOutRequestsCounter.Increment( out shouldReportProblem );

            string message =
              string.Format(
            "Location request hasn't finished in time for lrid {0}, tracker id {1}. That's a consequent time out #{2}",
            locReq.Lrid,
            locReq.Id,
            consequentErrorsCount );

            if ( shouldReportProblem )
              LocationRequest.ErrorHandlingLog.Error( message );
            else
              LocationRequest.ErrorHandlingLog.Info( message );
              }
        }
 LocationRequest CreateLocationRequest()
 {
     var locationRequest = new LocationRequest();
     locationRequest.SetSmallestDisplacement((float)smallestDisplacementMeters);
     locationRequest.SetPriority(accuracy);
     locationRequest.SetInterval(interval);
     locationRequest.SetFastestInterval(fastestInterval);
     return locationRequest;
 }
        private static async Task<LocationReponse> LookupByCoordinatesAsync(LocationRequest.LocationCoordinates coordinates)
        {
            string country = string.Empty;
            string region = string.Empty;
            string postalCode = string.Empty;
            string city = string.Empty;

            var connectionString = ConfigurationManager.ConnectionStrings["SqlAzure"];

            if (connectionString != null && !string.IsNullOrEmpty(connectionString.ConnectionString))
            {
                using (var connection = new SqlConnection(connectionString.ConnectionString))
                {
                    await connection.OpenAsync();

                    try
                    {
                        using (var command = connection.CreateCommand())
                        {
                            command.Parameters.Add(new SqlParameter("@lat", coordinates.Latitude));
                            command.Parameters.Add(new SqlParameter("@long", coordinates.Longitude));

                            command.CommandText = @"
declare @g geography = geography::Point(@lat, @long, 4326)

select top 1 [Iso2],
             [PostalCode],
             [PlaceName],
             [StateCode]
from [dbo].[tblGB]
where [GeoLocation].STDistance(@g) is not null
order by [GeoLocation].STDistance(@g);
";

                            using (var reader = await command.ExecuteReaderAsync())
                            {
                                while (await reader.ReadAsync())
                                {
                                    city = Convert.ToString(reader["PlaceName"], CultureInfo.InvariantCulture);
                                    country = Convert.ToString(reader["Iso2"], CultureInfo.InvariantCulture);
                                    postalCode = Convert.ToString(reader["PostalCode"], CultureInfo.InvariantCulture);
                                    region = Convert.ToString(reader["StateCode"], CultureInfo.InvariantCulture);

                                    break;
                                }
                            }
                        }
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                var client = new Google.Geocoding.Client.GeocodingClient()
                {
                    ApiKey = ConfigurationManager.AppSettings["Google_ApiKey"],
                };

                var lookup = await client.LookupAsync(coordinates.Latitude, coordinates.Longitude);

                if (lookup != null)
                {
                    city = lookup.City;
                    country = lookup.CountryCode;
                    region = lookup.RegionCode;
                    postalCode = lookup.PostalCode;
                }
            }

            return new LocationReponse()
            {
                DerivationMethod = "coordinates",
                City = city,
                Country = country,
                PostalCode = postalCode,
                Region = region,
            };
        }
        public void IsLocationEnabled(Action<bool> returnAction)
        {
            InitializeGoogleAPI();

            var locationRequestPriority = LocationRequest.PriorityBalancedPowerAccuracy;
            switch (CrossGeofence.GeofencePriority)
            {
                case GeofencePriority.HighAccuracy:
                    locationRequestPriority = LocationRequest.PriorityHighAccuracy;
                    break;
                case GeofencePriority.LowAccuracy:
                    locationRequestPriority = LocationRequest.PriorityLowPower;
                    break;
                case GeofencePriority.LowestAccuracy:
                    locationRequestPriority = LocationRequest.PriorityNoPower;
                    break;
            }
            var locationRequest = new LocationRequest();
            locationRequest.SetPriority(locationRequestPriority);
            locationRequest.SetInterval(CrossGeofence.LocationUpdatesInterval);
            locationRequest.SetFastestInterval(CrossGeofence.FastestLocationUpdatesInterval);

            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().AddLocationRequest(locationRequest);
            var pendingResult = LocationServices.SettingsApi.CheckLocationSettings(mGoogleApiClient, builder.Build());
            pendingResult.SetResultCallback((LocationSettingsResult locationSettingsResult) => {
                if (locationSettingsResult != null)
                {
                    returnAction(locationSettingsResult.Status.StatusCode <= CommonStatusCodes.Success);
                } 
            });
        }
 private void InitalizeGoogleLocationSettingsRequest()
 {
     _googleLocationRequest = new LocationRequest();
     _googleLocationRequest.SetInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
     _googleLocationRequest.SetFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
     _googleLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
 }
Example #54
0
		public void OnConnected (Bundle connectionHint)
		{
			Console.WriteLine ("Connected to Google services");

			var locationRequest = new LocationRequest ();
			locationRequest.SetPriority (100);
			locationRequest.SetFastestInterval (2000);
			locationRequest.SetInterval (5000);

			LocationServices.FusedLocationApi.RequestLocationUpdates (_googleApiClient, locationRequest, this);
		}
        private void EnsureStopped()
        {
            if (_locationClient == null) return;

            _locationClient.RemoveLocationUpdates(_locationListener);
            _locationClient.Disconnect();
            _locationClient = null;
            _locationRequest = null;
        }