Beispiel #1
0
        public App(string pushNotifParameter = null)
        {
            //INITIALIZATION
            if (AppContext == null)
            {
                IGeolocator                 geoLocator              = CrossGeolocator.Current;
                IRepository                 repository              = new AzureRepository("http://xdevmessaging.azurewebsites.net/");
                IPositionUpdater            positionUpdater         = new PositionUpdater(repository);
                IDisplayNameProvider <User> userDisplayNameProvider = new UserDisplayNameProvider();
                MeetupRepository            meetupRepository        = new MeetupRepository();
                AppContext = new AppContext(repository, geoLocator, positionUpdater, userDisplayNameProvider, meetupRepository);
            }

            //Check stored data
            //if (AppContext.IsUserStored)
            //{
            //    AppContext.LoginFromStorageAsync().Wait();
            //    var mapPage = new NavigationPage(new MapPage(AppContext));
            //    MainPage = mapPage;
            //}
            //else
            //{
            var loginPage = new NavigationPage(new LoginPage(AppContext));

            MainPage = loginPage;
            //}
        }
Beispiel #2
0
 public MapViewModel()
 {
     _geolocator = Resolver.Resolve <IGeolocator>();
     // GetWeb();
     GetPosition();
     NavigateToBack = new Command(() => Navigation.PopAsync());
 }
 public MapViewModel()
 {
     _geolocator = Resolver.Resolve<IGeolocator>();
    // GetWeb();
     GetPosition();
     NavigateToBack = new Command(() => Navigation.PopAsync());
 }
        protected async override void OnElementChanged(ElementChangedEventArgs <Map> e)
        {
            if (_map != null)
            {
                _map.MapClick -= googleMap_MapClick;
            }
            base.OnElementChanged(e);
            if (Control != null)
            {
                ((MapView)Control).GetMapAsync(this);
            }

            location = CrossGeolocator.Current;

            location.DesiredAccuracy = 100;

            try
            {
                position = await location.GetPositionAsync(TimeSpan.FromSeconds(10));

                await((MapTapRenderer)Element).ChangePosition(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude));


                Console.WriteLine("pos android" + position.Latitude.ToString() + " , " + position.Longitude.ToString());
                SetMarker(position.Latitude, position.Longitude);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #5
0
        private double[] GetCurrentLocation()
        {
            double[] data     = new double[2];
            int      platform = 0;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                platform = 1;
                break;
            }

            if (platform == 0) // Android
            {
                IGeolocator locator = DependencyService.Get <IGeolocator>();
                double      currentLatitude = 0, currentLongitude = 0;
                locator.locationObtained += (sender, e) =>
                {
                    currentLatitude  = e.lat;
                    currentLatitude  = Math.Round(currentLatitude * 100000.00) / 100000.00;
                    currentLongitude = e.lng;
                    currentLongitude = Math.Round(currentLongitude * 100000.00) / 100000.00;
                };
                locator.ObtainMyLocation();
                data[0] = currentLatitude;
                data[1] = currentLongitude;
            }
            else // iOS
            {
                data[0] = MainPage.currrentLatitude;
                data[1] = MainPage.currentLongitude;
            }

            return(data);
        }
Beispiel #6
0
        public MainMapPage()
        {
            _geolocator = CrossGeolocator.Current;
            _map        = new Map
            {
                MapType       = MapType.Street,
                IsShowingUser = true
            };
            _incidentBtn = new Button()
            {
                BackgroundColor = (Color)App.Current.Resources["Blue"],
                TextColor       = Color.White,
                Text            = "Nuevo reporte"
            };
            _incidentBtn.Clicked += _incidentBtn_Clicked;
            var grid = new Grid
            {
                RowDefinitions = new RowDefinitionCollection
                {
                    new RowDefinition {
                        Height = GridLength.Star
                    },
                    new RowDefinition {
                        Height = 40
                    }
                },
                RowSpacing = 0
            };

            grid.Children.Add(_map);
            grid.Children.Add(_incidentBtn, 0, 1);

            Content = grid;
        }
        public async Task <IGeolocator> GetGeolocator()
        {
            IGeolocator geoLocator = null;

            if (deviceCanonicalNames != null && deviceCanonicalNames.Length > 0)
            {
                var qstarsGeolocator = new QstarzGeolocator();
                foreach (string deviceName in deviceCanonicalNames)
                {
                    BluetoothConnectionStatus status = await qstarsGeolocator.ConnectToDevice(deviceName);

                    if (status == BluetoothConnectionStatus.BluetoothDisabled)
                    {
                        qstarsGeolocator.Dispose();
                        break;
                    }
                    if (status == BluetoothConnectionStatus.DeviceNotFound)
                    {
                        qstarsGeolocator.Dispose();
                        continue;
                    }
                    geoLocator = qstarsGeolocator;
                    break;
                }
            }
            if (geoLocator == null)
            {
                geoLocator = new InternalGeolocator();
            }

            return(geoLocator);
        }
        async private void Button_Clicked_In(object sender, EventArgs e)
        {
            try
            {
                IsBusy = true;
                IGeolocator locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 50;
                Position position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));

                AttendanceModel model = new AttendanceModel()
                {
                    IsMockedLocation = App._IsMockLocation.ToString(),
                    Latitude         = Convert.ToString(position.Latitude),
                    Longitude        = Convert.ToString(position.Longitude),
                    UserId           = Convert.ToString(App._UserId),
                    AttendanceMode   = "IN"
                };

                await CallApiForAttendance(model);
            }
            catch (Exception ex)
            {
                lblMessage.Text      = ex.Message;
                lblMessage.TextColor = Color.Red;
            }
            finally
            {
                IsBusy = false;
            }
        }
Beispiel #9
0
        private void SetLocation()
        {
            IGeolocator locator = DependencyService.Get <IGeolocator>();

            locator.locationObtained += (sender, e) =>
            {
                UserLatitude  = e.lat;
                UserLatitude  = Math.Round(UserLatitude * 100000.00) / 100000.00;
                userLatitude  = UserLatitude;
                UserLongitude = e.lng;
                UserLongitude = Math.Round(userLongitude * 100000.00) / 100000.00;
                userLongitude = UserLongitude;
            };
            locator.ObtainMyLocation();

            Debug.WriteLine("userLatitude: " + userLatitude + ", userLongitude: " + userLongitude);

            userOffset = new DateTimeOffset(DateTime.Now).Offset.Hours;

            DateLocation defaultSettings = new DateLocation
            {
                myDate      = DateTime.Now,
                myLatitude  = userLatitude,
                myLongitude = userLongitude,
                myOffset    = userOffset
            };

            Application.Current.Properties["Default"] = defaultSettings;
        }
        private async void GetGPS()
        {
            IGeolocator locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 50;

            if (locator.IsGeolocationAvailable)
            {
                if (locator.IsGeolocationEnabled)
                {
                    try
                    {
                        position = await locator.GetPositionAsync(timeoutMilliseconds : 10000);

                        AddListItem("Latitude:\t" + position.Latitude + "\nLongitude:\t" + position.Longitude);
                    }
                    catch
                    {
                        await DisplayAlert("Error", "Could not get GPS data.", "OK");
                    }
                }
            }

            list.ScrollTo(listItems.Last(), ScrollToPosition.End, true);
        }
Beispiel #11
0
        private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
        {
            string address = SuggestBox.Text;

            if (!CrossGeolocator.Current.IsListening)
            {
                IGeolocator locator = await LocationLogic.GetGeolocator(PermissionsLogic.IsLocationAccessPermitted);
            }
            var location = await LocationLogic.GetLocation();

            string PositionNow = LocationLogic.LocationStringBuilder(location);
            var    places      = await GoogleAPIRequest.GetPlaces(PositionNow, address);

            // Only get results when it was a user typing,
            // otherwise assume the value got filled in by TextMemberPath
            // or the handler for SuggestionChosen.
            if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
            {
                //Set the ItemsSource to be your filtered dataset
                //sender.ItemsSource = dataset;
                var           PlacesList = places.predictions.ToList();
                List <string> AddresList = new List <string>();
                PlacesList.ForEach(l => AddresList.Add(l.description));
                SuggestBox.ItemsSource = AddresList;
            }
        }
        /// <summary>
        /// Creates a new maps page to explore
        /// </summary>
        public ExploreMapPage()
        {
            this.zoomToMyPosition = false;
            this.geolocator       = Plugin.Geolocator.CrossGeolocator.Current;

            Task.Factory.StartNew(this.InitLayoutAsync);
        }
Beispiel #13
0
 private void geolocator_StatusChanged(IGeolocator sender, StatusChangedEventArgs args)
 {
     if (GeolocatorStatusChanged != null)
     {
         GeolocatorStatusChanged(this, args);
     }
 }
Beispiel #14
0
        public static async Task <Position> GetCurrentPosition()
        {
            IGeolocator locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = Constants.MapDesiredAccuracy;

            Position position = await locator.GetLastKnownLocationAsync();

            if (position != null)
            {
                return(position);
            }

            if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
            {
                return(null);
            }

            position = await locator.GetPositionAsync(TimeSpan.FromSeconds(Constants.TimeOutSmall), null, true);

            if (position == null)
            {
                return(null);
            }

            return(position);
        }
Beispiel #15
0
        async Task <bool> StartTracking()
        {
            geolocator = CrossGeolocator.Current;

            if (!geolocator.IsGeolocationAvailable)
            {
                DisplayAlert("Error", "Location is not awailable", "Ok");
                return(false);
            }

            Position result = null;

            try {
                geolocator.DesiredAccuracy = 50;

                if (!geolocator.IsListening)
                {
                    await geolocator.StartListeningAsync(5, 10);
                }

                oldPosition = await geolocator.GetPositionAsync(50000, CancellationToken.None);

                geolocator.PositionChanged += Geolocator_PositionChanged;
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine("Error : {0}", ex);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Locator.Portable.ViewModels.MapPageViewModel"/> class.
        /// </summary>
        /// <param name="navigation">Navigation.</param>
        /// <param name="geolocator">Geolocator.</param>
        /// <param name="commandFactory">Command factory.</param>
        /// <param name="geocodingWebServiceController">Geocoding repository.</param>
        public MapPageViewModel(INavigationService navigation, IGeolocator geolocator, Func <Action, ICommand> commandFactory,
                                IGeocodingWebServiceController geocodingWebServiceController) : base(navigation)
        {
            _geolocator = geolocator;
            _geocodingWebServiceController = geocodingWebServiceController;

            _nearestAddressCommand = commandFactory(() => FindNearestSite());
            _geolocationCommand    = commandFactory(() =>
            {
                if (_geolocationUpdating)
                {
                    geolocator.Stop();
                }
                else
                {
                    geolocator.Start();
                }

                GeolocationButtonTitle = _geolocationUpdating ? "Start" : "Stop";
                _geolocationUpdating   = !_geolocationUpdating;
            });

            _positions = new List <IPosition> ();

            LocationUpdates = new Subject <IPosition> ();
            ClosestUpdates  = new Subject <IPosition> ();
        }
Beispiel #17
0
        /// <summary>
        /// Creates a new maps page
        /// </summary>
        public MapPage()
        {
            this.Title = Constants.AppTitle;

            this.pageIsVisible       = false;
            this.zoomToMyPosition    = false;
            this.updateMapSettings   = false;
            this.updateLocationsList = false;
            this.updateTrackList     = false;

            this.geolocator = DependencyService.Get <GeolocationService>().Geolocator;

            Task.Run(this.InitLayoutAsync);

            MessagingCenter.Subscribe <App, Layer>(this, Constants.MessageAddLayer, this.OnMessageAddLayer);
            MessagingCenter.Subscribe <App, Layer>(this, Constants.MessageZoomToLayer, (app, layer) => this.OnMessageZoomToLayer(layer));
            MessagingCenter.Subscribe <App, Layer>(this, Constants.MessageSetLayerVisibility, (app, layer) => this.OnMessageSetLayerVisibility(layer));
            MessagingCenter.Subscribe <App, Layer>(this, Constants.MessageRemoveLayer, (app, layer) => this.OnMessageRemoveLayer(layer));
            MessagingCenter.Subscribe <App>(this, Constants.MessageClearLayerList, (app) => this.OnMessageClearLayerList());

            MessagingCenter.Subscribe <App, Track>(this, Constants.MessageAddTrack, this.OnMessageAddTrack);

            MessagingCenter.Subscribe <App, Location>(
                this,
                Constants.MessageAddTourPlanLocation,
                async(app, location) => await this.OnMessageAddTourPlanLocation(location));

            MessagingCenter.Subscribe <App, MapPoint>(this, Constants.MessageZoomToLocation, async(app, location) => await this.OnMessageZoomToLocation(location));
            MessagingCenter.Subscribe <App, Track>(this, Constants.MessageZoomToTrack, async(app, track) => await this.OnMessageZoomToTrack(track));
            MessagingCenter.Subscribe <App>(this, Constants.MessageUpdateMapSettings, this.OnMessageUpdateMapSettings);
            MessagingCenter.Subscribe <App>(this, Constants.MessageUpdateMapLocations, this.OnMessageUpdateMapLocations);
            MessagingCenter.Subscribe <App>(this, Constants.MessageUpdateMapTracks, this.OnMessageUpdateMapTracks);
        }
Beispiel #18
0
        public SearchFilersPage()
        {
            Utils.SetupPage(this);
            BuildLayout();

            locator = Xamarin.Forms.DependencyService.Get <IGeolocator>();
            locator.PositionChanged += (o, arg) =>
            {
                locator.StopListening();
                if (arg.Position != null)
                {
                    LocationFilter = new LocationFilter()
                    {
                        Lat    = arg.Position.Latitude,
                        Lon    = arg.Position.Longitude,
                        Radius = RADIUS
                    };
                    LocationAddress = "Current location";
                }
            };
            locator.PositionError += (o, arg) =>
            {
                locator.StopListening();
            };
            locator.StopListening();
            locator.StartListening(0, 0);
        }
Beispiel #19
0
        public GeoLocator()
        {
            locator = CrossGeolocator.Current;
            locator.PositionChanged += PositionChanged;

            Listen();
        }
Beispiel #20
0
        private async Task <XLabs.Platform.Services.Geolocation.Position> GetCurrentPosition()
        {
            IGeolocator geolocator = Resolver.Resolve <IGeolocator>();

            XLabs.Platform.Services.Geolocation.Position result = null;

            if (geolocator.IsGeolocationEnabled)
            {
                try {
                    if (!geolocator.IsListening)
                    {
                        geolocator.StartListening(1000, 1000);
                    }

                    var task = await geolocator.GetPositionAsync(10000);

                    result = task;

                    System.Diagnostics.Debug.WriteLine("[GetPosition] Lat. : {0} / Long. : {1}", result.Latitude.ToString("N4"), result.Longitude.ToString("N4"));
                }
                catch (Exception e) {
                    System.Diagnostics.Debug.WriteLine("Error : {0}", e);
                }
            }

            return(result);
        }
Beispiel #21
0
 private void geolocator_UnrecoverableError(IGeolocator sender, GeolocationErrorEventArgs args)
 {
     if (GeolocatorUnrecoverableError != null)
     {
         GeolocatorUnrecoverableError(this, args);
     }
 }
Beispiel #22
0
        async Task GetPosition()
        {
            // Inicia o Acelelometro
            var device = Resolver.Resolve <IDevice>();

            Debug.WriteLine(device.FirmwareVersion);


            this.geolocator = DependencyService.Get <IGeolocator> ();
            //geolocator.PositionError += OnPositionError;
            //geolocator.PositionChanged += OnPositionChanged;

            if (!geolocator.IsListening)
            {
                geolocator.StartListening(minTime: 1000, minDistance: 0);
            }

            var position = await geolocator.GetPositionAsync(timeout : 10000);

            string message = string.Format("Latitude: {0} | Longitude: {1}", position.Latitude, position.Longitude);

            Debug.WriteLine(message);

            device.Accelerometer.ReadingAvailable += getEixos;
        }
Beispiel #23
0
 private Geolocator()
 {
     locator = Xamarin.Forms.DependencyService.Get <IGeolocator>();
     //locator.DesiredAccuracy = 1000;
     locator.PositionChanged += Locator_PositionChanged;
     locator.PositionError   += Locator_PositionError;
 }
Beispiel #24
0
 public SagslistePage()
 {
     cache      = Resolver.Resolve <ISimpleCache>();
     geolocator = Resolver.Resolve <IGeolocator>();
     sager      = new ObservableCollection <Group <string, Sag> >();
     InitializeComponent();
 }
		void Setup(){
			if (this.geolocator != null)
				return;
            this.geolocator = DependencyService.Get<IGeolocator> ();
            this.geolocator.PositionError += OnListeningError;
			this.geolocator.PositionChanged += OnPositionChanged;
		}
        public LocationService()
        {
            locator = CrossGeolocator.Current;
            locator.DesiredAccuracy = 75;

            maps = CrossExternalMaps.Current;
        }
        async Task GetPosition()
        {
            if (geolocator == null)
            {
                geolocator = DependencyService.Get <IGeolocator>() ?? Resolver.Resolve <IGeolocator>();
            }

            await this.geolocator.GetPositionAsync(timeout : 10000)
            .ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    PositionStatus = ((GeolocationException)t.Exception.InnerException).Error.ToString();
                }
                else if (t.IsCanceled)
                {
                    PositionStatus = "Cancelado";
                }
                else
                {
                    PositionStatus = t.Result.Timestamp.ToString("G");
                    App.Latitude   = t.Result.Latitude;
                    App.Longitude  = t.Result.Longitude;
                }
            });
        }
        public async void MapViewInit()
        {
            CLLocationManager manager = new CLLocationManager();

            manager.RequestWhenInUseAuthorization();

            IGeolocator locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 50;

            Position position = await locator.GetPositionAsync(timeoutMilliseconds : 20000);

            Console.WriteLine("Position Status: {0}", position.Timestamp);
            Console.WriteLine("Position Latitude: {0}", position.Latitude);
            Console.WriteLine("Position Longitude: {0}", position.Longitude);

            CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(position.Latitude, position.Longitude);

            //CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(22.617193, 120.3032346);

            CenterLocation = map.CenterCoordinate = mapCenter;

            map.Region = MKCoordinateRegion.FromDistance(mapCenter, 1000, 1000);

            //map.ShowsUserLocation = true;

            CustomMapViewDelegate customDelegate = new CustomMapViewDelegate();

            customDelegate.OnRegionChanged += MapViewOnRegionChanged;
            map.Delegate = customDelegate;
        }
Beispiel #29
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();
            var hasPermission = await Utils.CheckPermissions(Permission.Location);

            if (!hasPermission)
            {
                return;
            }

            if (CrossGeolocator.Current.IsListening)
            {
                return;
            }

            await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true);

            locator = CrossGeolocator.Current;
            locator.PositionChanged += Locator_PositionChanged;


            if (OrientationSensor.IsMonitoring)
            {
                OrientationSensor.Stop();
            }
            else
            {
                OrientationSensor.Start(SensorSpeed.Normal);
            }

            OrientationSensor.ReadingChanged += OrientationSensor_ReadingChanged;;
        }
Beispiel #30
0
 public bool CheckService()
 {
     this.locator = CrossGeolocator.Current;
     this.locator.DesiredAccuracy = desiredAccuracyInMeters;
     this.Validate();
     return(this.CurrentInfo.Status == PositionResult.Statuses.OK);
 }
        protected async override void OnElementChanged(ElementChangedEventArgs <View> e)
        {
            if ((MapTapRenderer)Element != null)
            {
                if (Control != null)
                {
                    Control.RemoveGestureRecognizer(_tapRecogniser);
                }
                base.OnElementChanged(e);
                if (Control != null && ((MapTapRenderer)Element).IsEnabled)
                {
                    Control.AddGestureRecognizer(_tapRecogniser);
                }

                locationG = CrossGeolocator.Current;
                locationG.DesiredAccuracy = 100;

                try
                {
                    position = await locationG.GetPositionAsync(TimeSpan.FromSeconds(10));

                    await((MapTapRenderer)Element).ChangePosition(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude));

                    ((MapTapRenderer)Element).SetLocation(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
 public CrossLocationProvider()
 {
     locator = CrossGeolocator.Current;
     locator.AllowsBackgroundUpdates = true;
     locator.DesiredAccuracy         = 100;
     locator.PositionChanged        += OnChanged;
 }
		void Setup ()
		{
			if (_geolocator != null)
				return;

			_geolocator = DependencyService.Get<IGeolocator> ();
			_geolocator.PositionError += GeolocatorOnPositionError;
		}
Beispiel #34
0
		void Setup()
		{
			if (this.geolocator != null)
				return;
			this.geolocator = DependencyService.Get<IGeolocator> ();
			if(!this.geolocator.IsListening)
				this.geolocator.StartListening (1000, 5);
			
		}
		public GeoCoordinatesViewModel ()
		{
			Locator = CrossGeolocator.Current;
			Locator.DesiredAccuracy = 50;
			//Locator.StartListeningAsync (1, 0);

			Locator.PositionChanged += (object sender, PositionEventArgs e) => {
				Latitude = e.Position.Latitude.ToString();
				Longitude = e.Position.Longitude.ToString();
			};

		}
Beispiel #36
0
 public void EnableGPSTracking(AccessRights rights)
 {
     Console.WriteLine ("EnableGPSTracking rights.IsGPSTracking {0}",rights.IsGPSTracking);
     if (rights.IsGPSTracking) {
         locator = CrossGeolocator.Current;
         if (locator.IsGeolocationAvailable) {
             if (!locator.IsListening) {
                 GetMyLocation ();
             }
         }
     }
 }
        public AddGeofenceViewModel(IGeofenceManager geofences,
                                    IUserDialogs dialogs,
                                    IViewModelManager viewModelMgr,
                                    IGeolocator geolocator)
        {
            this.Add = ReactiveCommand.CreateAsyncTask(
                this.WhenAny(
                    x => x.RadiusMeters,
                    x => x.Latitude,
                    x => x.Longitude,
                    x => x.Identifer,
                    (radius, lat, lng, id) =>
                    {
                        if (radius.Value < 100)
                            return false;

                        if (lat.Value < -90 || lat.Value > 90)
                            return false;

                        if (lng.Value < -180 || lng.Value > 180)
                            return false;

                        if (id.Value.IsEmpty())
                            return false;

                        return true;
                    }
                ),
                async x =>
                {
                    geofences.StartMonitoring(new GeofenceRegion
                    {
                        Identifier = this.Identifer,
                        Center = new Position(this.Latitude, this.Longitude),
                        Radius = Distance.FromMeters(this.RadiusMeters)
                    });
                    await viewModelMgr.PopNav();
                }
            );
            this.UseCurrentLocation = ReactiveCommand.CreateAsyncTask(async x =>
            {
                try
                {
                    var current = await geolocator.GetPositionAsync(5000);
                    this.Latitude = current.Latitude;
                    this.Longitude = current.Longitude;
                }
                catch
                {
                }
            });
        }
		void SetupGeolocator()
		{
			if (this._geolocator != null)
				return;
			else {
				this._geolocator = new Geolocator ();
			}
			//this._geolocator = DependencyService.Get<IGeolocator> ();
			this._geolocator.PositionError += OnListeningError;
			this._geolocator.PositionChanged += OnPositionChanged;

			this._geolocator.StartListening (500, 1);
		}
Beispiel #39
0
		void SetupGeolocator()
		{
			if (this._geolocator != null)
				return;
			else {
				this._geolocator = new Geolocator ();
			}
			
			this._geolocator.PositionError += OnListeningError;
			this._geolocator.PositionChanged += OnPositionChanged;

			this._geolocator.StartListening (500, 1);
		}
		public async void Geolocate(IGeolocator locator)
		{
			try
			{
				var position = await locator.GetPositionAsync (10000);

				((App)App.Current).Latitude = position.Latitude;
				((App)App.Current).Longitude = position.Longitude;

				System.Diagnostics.Debug.WriteLine("I've got coordinates!");

				if(position.Latitude == 0 && position.Longitude == 0)
					((App)App.Current).LogError("GetPosition", "Координаты успешно получены, но нулевые!", "", new {});

				Navigate();
			}
			catch(GeolocationException e1)
			{
				if (e1.Error == GeolocationError.PositionUnavailable)
				{
					UseGeoError (e1);
					Navigate();
				}
				else
				{
					App.IOSAppDelegate.Confirm ("Определение погоды", "Для определения точных погодных условий включите, пожалуйста, службу геолокации в настройках. Если Вы пропустите этот шаг, то местоположение будет задано по умолчанию (СПБ). Если Вы уже включили геолокацию, нажмите \"Повторить\".",
						async (int n) => {
							if(n == 0)
							{
								UseGeoError (e1, false);
								Navigate();
							}
							else
							{
								Geolocate(locator);
							}
						}, "Пропустить", "Повторить");
				}
			}
			catch(Exception e2)
			{
				UseGeoError (e2);
				Navigate();
			}



		}
Beispiel #41
0
        private GpsReceiver()
        {
            _readingIsComing = false;
            _readingWait = new ManualResetEvent(false);
            _reading = null;
            _readingTimeoutMS = 120000;
            _locator = CrossGeolocator.Current;
            _listenerHeadings = new List<Tuple<EventHandler<PositionEventArgs>, bool>>();
            _locator.PositionChanged += (o, e) =>
            {
                SensusServiceHelper.Get().Logger.Log("GPS position has changed.", LoggingLevel.Verbose, GetType());

                if (PositionChanged != null)
                    PositionChanged(o, e);
            };
        }
		public UpdateLocationPage ()
		{
			locator = CrossGeolocator.Current;
			locator.DesiredAccuracy = 5;

			longitude = new Label ();
			latitude = new Label ();

			Content = new StackLayout {
				HorizontalOptions = LayoutOptions.Center,
				VerticalOptions = LayoutOptions.Center,
				Children = { 
					longitude,
					latitude
				}
			};
		}
Beispiel #43
0
        private GpsReceiver()
        {
            _readingIsComing = false;
            _readingWait = new ManualResetEvent(false);
            _reading = null;
            _readingTimeoutMS = 120000;
            _minimumTimeHintMS = 5000;
            _locator = CrossGeolocator.Current;
            _locator.AllowsBackgroundUpdates = true;
            _locator.PausesLocationUpdatesAutomatically = false;
            _locator.DesiredAccuracy = 50;  // setting this too low appears to result in very delayed GPS fixes.
            _listenerHeadings = new List<Tuple<EventHandler<PositionEventArgs>, bool>>();

            _locator.PositionChanged += (o, e) =>
            {
                SensusServiceHelper.Get().Logger.Log("GPS position has changed.", LoggingLevel.Verbose, GetType());

                if (PositionChanged != null)
                    PositionChanged(o, e);
            };
        }
Beispiel #44
0
 public SiteService(IGeolocator geolocator, ISiteStorage siteStorage, IArtportalenService artportalenService)
 {
     _geolocator = geolocator;
     _siteStorage = siteStorage;
     _artportalenService = artportalenService;
 }
 /// <summary>
 /// Method that does the initial gps setup
 /// </summary>
 public void SetupGps()
 {
     _locator = DependencyService.Get<IGeolocator>();
     if (_locator.DesiredAccuracy != Definitions.Accuracy)
     {
         _locator.DesiredAccuracy = Definitions.Accuracy;
     }
     _cancelSource = new CancellationTokenSource();
     _locator.PositionChanged += PositionChanged;
     _locator.PositionError += PositionError;
 }
Beispiel #46
0
		public LocationManager ()
		{ 
			locator=CrossGeolocator.Current;  
		}   
Beispiel #47
0
 public Location()
 {
     this._geolocator = DependencyService.Get<IGeolocator>();
 }
Beispiel #48
0
 public InstagramVM(IGeolocator locationProvider)
 {
     locationProvider.Locations.Subscribe((loc) => )
 }
        //private string _parameterText;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            _locator = CrossGeolocator.Current;
            // New in iOS 9 allowsBackgroundLocationUpdates must be set if you are running a background agent to track location. I have exposed this on the Geolocator via:
            // disable because it drill down the battery very quickly
            _locator.AllowsBackgroundUpdates = false;
            _locator.DesiredAccuracy = 50;
            _locator.PositionChanged -= Locator_PositionChanged;
            _locator.PositionChanged += Locator_PositionChanged;

            // parse params to show any shared location if it exists
            ParseIntent();

            var tintManager = new SystemBarTintManager(this);
            // set the transparent color of the status bar, 30% darker
            tintManager.SetTintColor(Color.ParseColor("#30000000"));
            tintManager.SetNavigationBarTintEnabled(true);
            tintManager.StatusBarTintEnabled = true;

            // prevent the soft keyboard from pushing the view up
            Window.SetSoftInputMode(SoftInput.AdjustNothing);

            // prepare icons for location / compass button
            var iconGenerator = new IconGenerator(this);
            iconGenerator.SetBackground(ResourcesCompat.GetDrawable(Resources, Resource.Drawable.ic_location, null));
            _iconUserLocation = iconGenerator.MakeIcon();
            iconGenerator.SetBackground(ResourcesCompat.GetDrawable(Resources, Resource.Drawable.ic_compass, null));
            _iconCompass = iconGenerator.MakeIcon();
            //var uiOptions = (int)this.Window.DecorView.SystemUiVisibility;
            //var newUiOptions = (int)uiOptions;
            //newUiOptions &= ~(int)SystemUiFlags.LowProfile;
            //newUiOptions &= ~(int)SystemUiFlags.Fullscreen;
            //newUiOptions &= ~(int)SystemUiFlags.HideNavigation;
            //newUiOptions &= ~(int)SystemUiFlags.Immersive;
            //newUiOptions |= (int)SystemUiFlags.ImmersiveSticky;
            //this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility)newUiOptions;
            //Window.SetFlags(WindowManagerFlags.LayoutNoLimits, WindowManagerFlags.LayoutNoLimits);

            var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
            //toolbar.Background.SetAlpha(200);
            ViewCompat.SetElevation(toolbar, 6f);
            SetSupportActionBar(toolbar);

            //Enable support action bar to display hamburger and back arrow
            // http://stackoverflow.com/questions/28071763/toolbar-navigation-hamburger-icon-missing
            _drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
            //_drawerToggle = new CustomActionBarDrawerToggle(this, _drawerLayout, toolbar, Resource.String.ApplicationName, Resource.String.ApplicationName);
            //_drawerToggle.DrawerIndicatorEnabled = true;
            _drawerLayout.SetDrawerListener(new CustomDrawerToggle(this));
            //Enable support action bar to display hamburger


            var burgerImage = FindViewById<ImageButton>(Resource.Id.burgerImage);
            burgerImage.SetOnClickListener(new HomeButtonClickListener(this));

            // SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
            SupportActionBar.SetHomeButtonEnabled(false);
            SupportActionBar.SetDisplayHomeAsUpEnabled(false);
            SupportActionBar.SetDisplayShowCustomEnabled(false);

            navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
            navigationView.SetNavigationItemSelectedListener(new NavigationItemSelectedListener(this));

            _bikesButton = FindViewById<FloatingActionButton>(Resource.Id.bikesButton);
            _bikesButton.BackgroundTintList = ColorStateList.ValueOf(Resources.GetColor(Resource.Color.primary_light));
            _bikesButton.Click += BikesButton_Click;

            _parkingButton = FindViewById<FloatingActionButton>(Resource.Id.parkingButton);
            _parkingButton.BackgroundTintList = ColorStateList.ValueOf(Resources.GetColor(Resource.Color.primary_light));
            _parkingButton.Click += ParkingButton_Click;

            _locationButton = FindViewById<FloatingActionButton>(Resource.Id.locationButton);
            _locationButton.BackgroundTintList = ColorStateList.ValueOf(Color.White);
            _locationButton.SetColorFilter(Color.Gray);

            _searchProgressBar = FindViewById<ProgressBar>(Resource.Id.searchProgressBar);

            // Doesn't work on Kitkat 4.4, use SetColorFilter instead
            //_locationButton.ImageTintList = ColorStateList.ValueOf(Color.Black);
            _locationButton.Click += LocationButton_Click;

            _tileButton = FindViewById<FloatingActionButton>(Resource.Id.tileButton);
            _tileButton.BackgroundTintList = ColorStateList.ValueOf(Color.White);
            _tileButton.SetColorFilter(Color.DarkGray);
            _tileButton.Click += TileButton_Click;
            var parent = (View)_tileButton.Parent;

            // Gets the parent view and posts a Runnable on the UI thread. 
            // This ensures that the parent lays out its children before calling the getHitRect() method.
            // The getHitRect() method gets the child's hit rectangle (touchable area) in the parent's coordinates.
            parent.Post(() =>
            {
                var touchRect = new Rect();
                _tileButton.GetHitRect(touchRect);
                touchRect.Top -= 200;
                touchRect.Left -= 200;
                touchRect.Bottom += 200;
                touchRect.Right += 200;


                parent.TouchDelegate = new TouchDelegate(touchRect, _tileButton);
            });

            _currentTileName = FindViewById<TextView>(Resource.Id.currentTileName);
            _currentTileNameAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.placeholder);
            _disappearTileNameAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.disappearAnimation);
            _currentTileNameAnimation.AnimationEnd += _currentTileNameAnimation_AnimationEnd;

            UnStickUserLocation();

            AutoCompleteSearchPlaceTextView = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteSearchPlaceTextView);
            AutoCompleteSearchPlaceTextView.ItemClick += AutoCompleteSearchPlaceTextView_ItemClick;
            googlePlacesAutocompleteAdapter = new GooglePlacesAutocompleteAdapter(this, Android.Resource.Layout.SimpleDropDownItem1Line);
            AutoCompleteSearchPlaceTextView.Adapter = googlePlacesAutocompleteAdapter;


            Observable.FromEventPattern(AutoCompleteSearchPlaceTextView, "TextChanged")
                .Throttle(TimeSpan.FromMilliseconds(300))
                .Where(x => AutoCompleteSearchPlaceTextView.Text.Length >= 2)
                .Subscribe(async x =>
                {
                    try
                    {
                        RunOnUiThread(() =>
                        {
                            _searchProgressBar.Visibility = ViewStates.Visible;
                        });

                        using (var client = new HttpClient(new NativeMessageHandler()))
                        {
                            var response = await client.GetAsync(strAutoCompleteGoogleApi + AutoCompleteSearchPlaceTextView.Text + "&key=" + strGoogleApiKey).ConfigureAwait(false);
                            var responseBodyAsText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            var predictions = JsonConvert.DeserializeObject<PlaceApiModel>(responseBodyAsText).predictions.ToList();
                            googlePlacesAutocompleteAdapter.Results = predictions;
                            if (AutoCompleteSearchPlaceTextView.Text.Length >= 2)
                            {
                                RunOnUiThread(() =>
                                {
                                    googlePlacesAutocompleteAdapter.NotifyDataSetChanged();
                                    EndPlacesSearch();
                                });
                            }
                        }
                    }
                    catch
                    {
                        RunOnUiThread(() =>
                        {
                            EndPlacesSearch();
                        });
                    }
                });


            //navigationView.NavigationItemSelected += (sender, e) =>
            //{
            //    e.MenuItem.SetChecked(true);
            //    //react to click here and swap fragments or navigate
            //    drawerLayout.CloseDrawers();
            //};

            // trigger the creation of the injected dependencies
            _settingsService = SimpleIoc.Default.GetInstance<ISettingsService>();
            _favoritesService = SimpleIoc.Default.GetInstance<IFavoritesService>();
        }
 public LocationTestService()
 {
     locator = CrossGeolocator.Current;
     locator.DesiredAccuracy = 10;
 }
Beispiel #51
0
 private void GetMyLocation()
 {
     Console.WriteLine ("Start MyLocation");
     locator = CrossGeolocator.Current;
     if (!locator.IsGeolocationEnabled) {
         enableGPS ();
     }
     locator.DesiredAccuracy = 20;
     locator.AllowsBackgroundUpdates = true;
     locator.PositionChanged+= Locator_PositionChanged;
     locator.PositionError+= Locator_PositionError;
     locator.StartListeningAsync(300000, 100, false); //5 min , 100 meter
     Console.WriteLine ("IsGeolocationAvailable {0}",locator.IsGeolocationAvailable);
     Console.WriteLine ("IsGeolocationEnabled {0}",locator.IsGeolocationEnabled);
     Console.WriteLine ("IsListening {0}",locator.IsListening);
 }
 /// <summary>
 /// Method that handles cleanup of the viewmodel
 /// </summary>
 public void Dispose()
 {
     Definitions.GpsIsActive = false;
     _parentPage.Dispose();
     Unsubscribe();
     HandleStopGpsMessage();
     _stopErrorTimer = true; // stop timer;
     if (_cancelSource != null)
     {
         _cancelSource.Cancel();
     }
     _locator = null;
 }
		async Task GetPosition ()
		{
			// Inicia o Acelelometro
			var device = Resolver.Resolve<IDevice>();
			Debug.WriteLine (device.FirmwareVersion);


			this.geolocator = DependencyService.Get<IGeolocator> ();
			//geolocator.PositionError += OnPositionError;
			//geolocator.PositionChanged += OnPositionChanged;

			if (!geolocator.IsListening)
				geolocator.StartListening(minTime: 1000, minDistance: 0);

			var position = await geolocator.GetPositionAsync (timeout: 10000);

			string message = string.Format ("Latitude: {0} | Longitude: {1}", position.Latitude, position.Longitude);

			Debug.WriteLine (message);

			device.Accelerometer.ReadingAvailable += getEixos;


		}
 public MainViewModel()
 {
     _geolocator = DependencyService.Get<IGeolocator>();
     _ws = new WeatherService();
     GetGeolocationAndWeather();
 }