Exemplo n.º 1
0
        /// ------------------------------------------------------------------------------------------------
        /// ------------------------------------------------------------------------------------------------
        #region Private Functions

        #region Get Current Location

        public async Task <Plugin.Geolocator.Abstractions.Position> GetCurrentLocation()
        {
            try
            {
                var locator = CrossGeolocator.Current;
                //locator.AllowsBackgroundUpdates = true;
                //locator.DesiredAccuracy = 50;
                _posistion = await locator.GetPositionAsync(1000);
            }

            catch (Plugin.Geolocator.Abstractions.GeolocationException geoException)
            {
                AppContext.AppContext.CurrentLocation = null;
                if (geoException.Message.Contains("Unavailable"))
                {
                    await SplitView.DisplayAlert(" GPS Disabled ", " Please enable the GPS to access your current location ", "OK", null);
                }
                if (geoException.Message.Contains("Unauthorized"))
                {
                    await SplitView.DisplayAlert("Get Device Location", " Please grant permission for this application to access your current location ", "OK", null);
                }
                _posistion = null;
            }
            catch (Exception ex)
            {
                LogTracking.LogTrace(ex.ToString());
                AppContext.AppContext.CurrentLocation = null;
            }
            return(_posistion);
        }
Exemplo n.º 2
0
        public async Task UpdateLocationAsync(Plugin.Geolocator.Abstractions.Position position, Address address, string accessToken)
        {
            try
            {
                var client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

                var location = new GeoContacts.SharedModels.LocationUpdate
                {
                    Country  = address.CountryCode,
                    Position = new Microsoft.Azure.Documents.Spatial.Point(position.Longitude, position.Latitude),
                    State    = address.AdminArea,
                    Town     = address.Locality
                };

                var json    = Newtonsoft.Json.JsonConvert.SerializeObject(location);
                var content = new System.Net.Http.StringContent(json);
                var resp    = await client.PostAsync(CommonConstants.FunctionUrl, content);

                var respBody = await resp.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"ERROR: {ex.Message}");
            }
        }
Exemplo n.º 3
0
 public PointOfInterest(string name, string type, Position position)
     : this()
 {
     _name = name ?? "";
     _type = type ?? "";
     _position = position;
 }
Exemplo n.º 4
0
        /*---------------------------------*/
        /*Map functions and event handeling*/
        public async void InitMapAndTracking()
        {
            //Get the current user location
            DBPosition = LastPosition = await GetUserStartLocation();

            //Get the style of the selected map
            var styleFile = await ChangeMapStyle();

            await Task.Run(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    //Changing the style of the map
                    CustomMap.MapStyle = GoogleMaps.MapStyle.FromJson(styleFile);

                    //Standard Map settings
                    CustomMap.UiSettings.ZoomControlsEnabled     = false;
                    CustomMap.UiSettings.MyLocationButtonEnabled = true;

                    //move the users position on the map
                    CustomMap.InitialCameraUpdate = GoogleMaps.CameraUpdateFactory.NewPositionZoom(new GoogleMaps.Position(DBPosition.Latitude, DBPosition.Longitude), 17.5);
                });
            });

            Current.CustomMap = CustomMap;

            //Store the long and lat data in the CU variable
            Current.CU.Latitude  = DBPosition.Latitude;
            Current.CU.Longitude = DBPosition.Longitude;

            await GetPlaces();      //Calls the function to get all the places nearby
            await StartListening(); //Calls the function that will listen for location changes (every second)
        }
Exemplo n.º 5
0
        protected override void OnAppearing()
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                if (_geolocator.IsGeolocationEnabled)
                {
                    _position = await _geolocator.GetLastKnownLocationAsync();
                    if (_position == null)
                    {
                        _position = await _geolocator.GetPositionAsync();
                    }
                    var formsMapPosition = new Xamarin.Forms.Maps.Position(_position.Latitude, _position.Longitude);
                    var mapSpan          = MapSpan.FromCenterAndRadius(formsMapPosition, Distance.FromKilometers(1.5));
                    _map.MoveToRegion(mapSpan);

                    Incidents = await AdaptatonEndpoint.Instance.GetIncidents();
                    foreach (var incident in Incidents)
                    {
                        _map.Pins.Add(new Pin
                        {
                            Position = new Xamarin.Forms.Maps.Position((double)incident.Latitude,
                                                                       (double)incident.Longitude),
                            Label = incident.Id
                        });
                    }
                }
                else
                {
                    await DisplayAlert("Un momento", "Debes activar tu GPS para usar la aplicación.", "OK");
                }
            });
        }
        private async void buttonClicked(object sender, EventArgs e)
        {
            IGeolocator locator = CrossGeolocator.Current;
            locator.DesiredAccuracy = 50;

            if (locator.IsGeolocationAvailable)
            {
                if (locator.IsGeolocationEnabled)
                {
                    try
                    {
                        position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
                        latLabel.Text = "Latitude: " + position.Latitude;
                        lonLabel.Text = "Longitude: " + position.Longitude;

                        System.Diagnostics.Debug.WriteLine("TimeStamp: " + position.Timestamp);
                    }
                    catch (GeolocationException ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.InnerException);
                        await DisplayAlert("Error", "Unauthorized", "OK");
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.InnerException);
                    }
                }
                else
                    await DisplayAlert("Error", "Geo sensors is not turned on.\nPlease turn on it.", "OK");

            }
            else
                await DisplayAlert("Error", "This device does not have any geo sensors or enough permission to use it.", "OK");
        }
Exemplo n.º 7
0
        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);
            }
        }
Exemplo n.º 8
0
        private void MoveMap(Plugin.Geolocator.Abstractions.Position position)
        {
            var span = (MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
                                                    Distance.FromMiles(1)));

            locationsMap.MoveToRegion(span);
        }
Exemplo n.º 9
0
 public AddNewCasePointOnMapView(IMapView mapview, GeoLocation.Position casePosition)
 {
     try
     {
         _mapview      = mapview;
         _casePosition = casePosition;
         InitializeComponent();
         AppContext.AppContext.NewRecordInProgress = true;
         Tapgestures();
         if (Device.OS == TargetPlatform.Android)
         {
             SplitView.MapView?.ClearPin();
             MoveMapPosition();
             AndroidMapView.HideLocator();
             var googleMap = (AndroidMapView)SplitView.MapView;
             GlMapView.Children.Clear();
             GlMapView.Children.Add(googleMap, 0, 0);
         }
         else
         {
             var formsMap = (WindowsMapView)mapview;
             GlMapView.Children.Add(formsMap, 0, 0);
         }
         MoveToPosition += MoveMapPosition;
         _slowmethod     = SlowConnectionAlert;
         _token          = CancellationToken.None;
         SlowConnection();
     }
     catch (Exception ex)
     {
         LogTracking.LogTrace(ex.ToString());
     }
 }
Exemplo n.º 10
0
        private void MoveMap(Plugin.Geolocator.Abstractions.Position position)
        {
            var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude); //koordinatlari aliyoruz.ekranin merkezinde olacak.
            var span   = new MapSpan(center, 0.1, 0.1);                                          //sayisal degerler haritanin ne kadar uzaktan acilmasi gerektigini belirtir.

            locationsMap.MoveToRegion(span);                                                     //istenilen bolgeye haritanin gitmesini sagliyoruz.
        }
Exemplo n.º 11
0
        public static async Task <bool> getCurrentDeviceLatitudeLongitude()
        {
            int gotLocation = 0;

            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 100;


                if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
                {
                    var position = await locator.GetPositionAsync(TimeSpan.FromMilliseconds(1500));

                    currentDeviceLatitude  = position.Latitude;
                    currentDeviceLongitude = position.Longitude;

                    // App.UserPreferences.SetString("LastKnownLongitude", currentDeviceLongitude.ToString());
                    // App.UserPreferences.SetString("LastKnownLatitude", currentDeviceLatitude.ToString());

                    if (currentDeviceLatitude != 0 && currentDeviceLongitude != 0)
                    {
                        gotLocation = 1;
                    }
                }

                else if (locator.IsGeolocationEnabled)
                {
                    Plugin.Geolocator.Abstractions.Position Lastknownpositions = await locator.GetLastKnownLocationAsync();

                    if (Lastknownpositions != null)
                    {
                        currentDeviceLatitude  = Lastknownpositions.Latitude;
                        currentDeviceLongitude = Lastknownpositions.Longitude;
                    }


                    gotLocation = 1;
                }

                if (LocationService.currentDeviceLatitude == 0 && LocationService.currentDeviceLongitude == 0)
                {
                    gotLocation = 0;
                }

                if (gotLocation == 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception exNew)
            {
                Debug.Write(exNew);
                return(false);
            }
        }
Exemplo n.º 12
0
        private void CrossGeolocator_Current_PositionChanged(object sender, PositionEventArgs e)
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                Models.Location local = new Models.Location();

                Plugin.Geolocator.Abstractions.Position position = e.Position;

                if (Cposition != e.Position)
                {
                    Cposition = e.Position;
                    mainmap.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(1)).WithZoom(2));

                    loader.IsVisible  = false;
                    mainmap.IsVisible = true;

                    local.Lat = position.Latitude;
                    local.Lng = position.Longitude;


                    if (Trip.Key != null)
                    {
                        _firebaseDatabase.UpdateTripDriverLocation(Trip.Key, local);

                        if (Trip.Status == "Started")
                        {
                            _firebaseDatabase.UpdateTripLocation(Trip.Key, local);
                        }
                    }
                }
            });
        }
        protected override void OnAppearing()
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                if (_geolocator.IsGeolocationEnabled)
                {
                    _position = await _geolocator.GetLastKnownLocationAsync();
                    if (_position == null)
                    {
                        _position = await _geolocator.GetPositionAsync();
                    }
                    var formsMapPosition = new Xamarin.Forms.Maps.Position(_position.Latitude, _position.Longitude);
                    var mapSpan          = MapSpan.FromCenterAndRadius(formsMapPosition, Distance.FromKilometers(1));
                    _map.MoveToRegion(mapSpan);

                    MyPositionPin = new Pin
                    {
                        Address  = "Mi ubicación",
                        Position = formsMapPosition,
                        Type     = PinType.Generic,
                        Label    = "Mi ubicación"
                    };
                    _map.Pins.Add(MyPositionPin);
                }
                else
                {
                    await DisplayAlert("Un momento", "Debes activar tu GPS para usar la aplicación.", "OK");
                }
            });
        }
Exemplo n.º 14
0
 private void moveMapToPosition(Plugin.Geolocator.Abstractions.Position position)
 {
     mapView.MoveToRegion(
         MapSpan.FromCenterAndRadius(
             new Xamarin.Forms.GoogleMaps.Position(position.Latitude, position.Longitude), Distance.FromMiles(1)));
     System.Diagnostics.Debug.WriteLine("Map Moved");
 }
        private void MoveMap(Plugin.Geolocator.Abstractions.Position position)
        {
            var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
            var span   = new Xamarin.Forms.Maps.MapSpan(center, 1, 1);

            locationsMap.MoveToRegion(span);
        }
        async void SetLocationOnMap()
        {
            var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

            if (status != PermissionStatus.Granted)
            {
                await DependencyService.Get <IPermissionServices>().GetPermission(this);
            }

            var      locator = CrossGeolocator.Current;
            TimeSpan ts      = TimeSpan.FromTicks(1000000);

            Plugin.Geolocator.Abstractions.Position position = await locator.GetPositionAsync(ts);

            IEnumerable <Address> addresses = await locator.GetAddressesForPositionAsync(position, "AIzaSyDminfXt_CoSb9UTXpPFZwQIG2lDduDMjs");

            Address address = addresses.FirstOrDefault();

            //Address address = (addresses.ToArray())[0];
            entryHelperRegSearch3.Placeholder = address.FeatureName + "," + address.SubLocality + "," + address.Locality;
            var pin = new Pin()
            {
                Type     = PinType.Place,
                Position = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
                Label    = address.FeatureName,
                Address  = address.FeatureName + "," + address.SubLocality + "," + address.Locality,
                Id       = "1"
            };

            mapHelperRegister.Pins.Add(pin);
            //Pin pin = mapRegister.Pins.FirstOrDefault();

            mapHelperRegister.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(0.2)));
            mapHelperRegister.IsShowingUser = true;
        }
Exemplo n.º 17
0
        async Task <Plugin.Geolocator.Abstractions.Position> GetCurrentLocation()
        {
            Plugin.Geolocator.Abstractions.Position position = null;
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 100;

                if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
                {
                    position = await locator.GetLastKnownLocationAsync();

                    if (position == null)
                    {
                        position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);
                    }

                    if (position != null)
                    {
                        var output = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}",
                                                   position.Timestamp, position.Latitude, position.Longitude,
                                                   position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);

                        Debug.WriteLine(output);
                    }
                }
            }
            catch (Exception ex)
            {
                //Display error as we have timed out or can't get location.
            }

            return(position);
        }
Exemplo n.º 18
0
 // Update GPS location displays and database
 private async void updateGPSDataList(Plugin.Geolocator.Abstractions.Position position)
 {
     Debug.WriteLine("Position changed: " + position.Latitude);
     Debug.WriteLine("Position changed: " + position.Longitude);
     StaticDataModel.Lattitude = position.Latitude;
     StaticDataModel.Longitude = position.Longitude;
 }
Exemplo n.º 19
0
 public override void Stop()
 {
     lock (_locker)
     {
         base.Stop();
         _previousPosition = null;  // reset previous location so it doesn't get used when this probe is restarted.
     }
 }
Exemplo n.º 20
0
 public static CurrentLocationPost GeolocatorToDataContract(this Geo.Position position)
 {
     return(new CurrentLocationPost()
     {
         Latitude = position.Latitude,
         Longitude = position.Longitude
     });
 }
 public async override void OnNavigatingTo(NavigationParameters parameters)
 {
     if (CrossConnectivity.Current.IsConnected)
     {
         LocationFinder finder = new LocationFinder();
         _position = await finder.GetCurrentLocation();
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// update map region for display
        /// </summary>
        public void UpdateMapRegion(Plugin.Geolocator.Abstractions.Position position)
        {
            CurrentPosition = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
            MapCenter       = CurrentPosition;
            Distance distance = MapRegion != null ? MapRegion.Radius : Distance.FromKilometers(30);

            MapRegion = MapSpan.FromCenterAndRadius(CurrentPosition, distance);
        }
Exemplo n.º 23
0
        // bespoke method for moving map (refactored here) 7-63
        private void MoveMap(Plugin.Geolocator.Abstractions.Position position)
        {
            var centre = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
            var span   = new Xamarin.Forms.Maps.MapSpan(centre, 1, 1);      // 1 degree of lat & lng is the region to span around the centre

            locationsMap.MoveToRegion(span);
            // For region, supply region centre, and degrees of lat & lng to show as a region around/spanning centre
        }
Exemplo n.º 24
0
        void UpdateWorkFieldAndObj(Plugin.Geolocator.Abstractions.Position oldValue, Plugin.Geolocator.Abstractions.Position newValue)
        {
            var conventer  = new WorkoutConventer();
            var surveyTime = (DateTime.Now.Ticks - startWorkout.Ticks + lastInterval.Ticks) / 10000000;//measurement approximate accuracy//seconds

            WorkoutData     = conventer.ValueObject(new MapPreparedData(WorkoutData), oldValue, newValue, NumberOfPoint, surveyTime);
            NewWorkoutPoint = newValue;
            RefreshWorkFieldAndObj(newValue);
        }
Exemplo n.º 25
0
        /*
         * async void SetLocationOnMap()
         * {
         *  var locator = CrossGeolocator.Current;
         *  TimeSpan ts = TimeSpan.FromTicks(1000000);
         *  Plugin.Geolocator.Abstractions.Position position = await locator.GetPositionAsync(ts);
         *  IEnumerable<Address> addresses =  await locator.GetAddressesForPositionAsync(position, "AIzaSyDminfXt_CoSb9UTXpPFZwQIG2lDduDMjs");
         *  Address address = addresses.FirstOrDefault();
         *  //Address address = (addresses.ToArray())[0];
         *  entryRegSearch3.Placeholder = address.FeatureName + "," + address.SubLocality + "," + address.Locality;
         *  var pin = new Pin()
         *  {
         *      Type = PinType.Place,
         *      Position = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
         *      Label = address.FeatureName,
         *      Address = address.FeatureName + "," + address.SubLocality + "," + address.Locality,
         *      Id = "1"
         *  };
         * // mapRegister.Pins.Add(pin);
         *  //Pin pin = mapRegister.Pins.FirstOrDefault();
         *
         * // mapRegister.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(0.2)));
         * // mapRegister.IsShowingUser = true;
         * }
         */

        async void SetLocationOnMap()
        {
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationAlways);

                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
                    {
                        //await DisplayAlert("Need location", "Helpa need that location", "OK");
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);

                    if (results.ContainsKey(Permission.Location))
                    {
                        status = results[Permission.Location];
                    }
                }

                if (status == PermissionStatus.Granted)
                {
                    await DependencyService.Get <IPermissionServices>().CheckAndTurnOnGPS(this);

                    Plugin.Geolocator.Abstractions.Position position = await CrossGeolocator.Current.GetPositionAsync();

                    var addr = await CrossGeolocator.Current.GetAddressesForPositionAsync(new Plugin.Geolocator.Abstractions.Position(position.Latitude, position.Longitude), "AIzaSyDminfXt_CoSb9UTXpPFZwQIG2lDduDMjs");

                    var a   = addr.FirstOrDefault();
                    var loc = a.FeatureName + "," + a.SubLocality + "," + a.Locality + "," + a.CountryName + "," + a.PostalCode;

                    mapRegister.Pins.Clear();
                    mapRegister.Pins.Add(new Pin()
                    {
                        Type     = PinType.Place,
                        Position = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
                        Label    = a.FeatureName,
                        Address  = a.FeatureName + "," + a.SubLocality + "," + a.Locality,
                        Id       = "1"
                    });

                    mapRegister.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(0.2)));
                    mapRegister.IsShowingUser = true;
                    //MessagingCenter.Send<Register2, string>(this, "Current Address", loc);
                }
                else if (status != PermissionStatus.Unknown)
                {
                    //await DisplayAlert("Location Denied", "Please allow location permission to get your location for Helpa app in Device setting", "OK");
                }
            }
            catch (Exception ex)
            {
                //await DisplayAlert("Error", ex.Message, "OK");
            }
        }
Exemplo n.º 26
0
        private void MoveMap(Plugin.Geolocator.Abstractions.Position position)
        {
            //get the center in lat, long
            var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);

            //get the span of the map with the center
            var mapspan = new Xamarin.Forms.Maps.MapSpan(center, 0.0015d, 0.0015d);

            //now move to the region
            customMap.MoveToRegion(mapspan);
        }
Exemplo n.º 27
0
 /*Used to calculate the distance between the users current position and the place*/
 public async Task CalculateDistance(Geolocator.Position CurrentPosition)
 {
     await Task.Run(() =>
     {
         //Used to re-calculate the distance for each place in the list
         foreach (Place place in Current.Places)
         {
             place.Distance = 6371 * Math.Acos(Math.Cos(ConvertToRadians(CurrentPosition.Latitude)) * Math.Cos(ConvertToRadians(place.Latitude)) * Math.Cos(ConvertToRadians(place.Longitude) - ConvertToRadians(CurrentPosition.Longitude)) + Math.Sin(ConvertToRadians(CurrentPosition.Latitude)) * Math.Sin(ConvertToRadians(place.Latitude)));
         }
     });
 }
Exemplo n.º 28
0
        public void CheckLocation()
        {
            position = new Plugin.Geolocator.Abstractions.Position();
            var locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 50;
            Task.Run(async() => {
                position = await locator.GetPositionAsync(TimeSpan.FromMilliseconds(1000));
                Debug.WriteLine(position.Latitude);
            });
        }
        private async void GetLocation()
        {
            if (hasLocationPermission)
            {
                var locator  = CrossGeolocator.Current;
                var position = await locator.GetPositionAsync();

                mainPosition = position;
                MoveMap(position);
            }
        }
Exemplo n.º 30
0
        private async Task<Position> FetchLocation()
        {
            try
            {
                _lastPosition = await _geolocator.GetPositionAsync(timeoutMilliseconds: 10000);
            }
            catch (Exception e)
            {
            }

            return _lastPosition;
        }
Exemplo n.º 31
0
        private async void SetLocationAsync()
        {
            if (IsLocationAvailable() && hasLocationPermission)
            {
                var      geolocator = CrossGeolocator.Current;
                Position position   = await geolocator.GetPositionAsync();

                MoveMap(position);

                SetVenuesPinsAsync(position);
            }
        }
Exemplo n.º 32
0
        public static double GetDistance(Plugin.Geolocator.Abstractions.Position pos1, Plugin.Geolocator.Abstractions.Position pos2, Xamarin.Forms.GoogleMaps.DistanceType type)
        {
            double R    = (type == Xamarin.Forms.GoogleMaps.DistanceType.Miles) ? 3960 : 6371;
            double dLat = ToRadian(pos2.Latitude - pos1.Latitude);
            double dLon = ToRadian(pos2.Longitude - pos1.Longitude);
            double a    = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                          Math.Cos(ToRadian(pos1.Latitude)) * Math.Cos(ToRadian(pos2.Latitude)) *
                          Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R * c;

            return(d);
        }
Exemplo n.º 33
0
        public MapView(Plugin.Geolocator.Abstractions.Position _position)
        {
            InitializeComponent();
            this.Title = "Location";
            position   = _position;

            location = LoginPage.Location;

            openingLocation = LoginPage.locationLabel;

            mapView.HeightRequest = App.ScreenHeight;
            mapView.WidthRequest  = App.ScreenWidth;
        }
Exemplo n.º 34
0
        public async Task <Plugin.Geolocator.Abstractions.Position> getDetailPlace(string id)
        {
            var detail = await _service.getDetailPlaceInfo(id).ConfigureAwait(false);

            var location  = detail["result"]["geometry"]["location"];
            var latitude  = double.Parse(location["lat"].ToString());
            var longitude = double.Parse(location["lng"].ToString());
            var position  = new Plugin.Geolocator.Abstractions.Position();

            position.Latitude  = latitude;
            position.Longitude = longitude;
            return(position);
        }
Exemplo n.º 35
0
        public SpeedDatum(DateTimeOffset timestamp, Position previousPosition, Position currentPosition)
            : base(timestamp, 0)
        {
            double distanceKM;
            double timeHours;
            _kph = SpeedDatum.CalculateSpeedKPH(previousPosition, currentPosition, out distanceKM, out timeHours);

            if (previousPosition.Accuracy >= 0 && currentPosition.Accuracy >= 0)
            {
                double maximumDistanceKM = distanceKM + previousPosition.Accuracy / 1000f + currentPosition.Accuracy / 1000f;
                double maximumSpeedKPH = maximumDistanceKM / timeHours;
                Accuracy = (float)(maximumSpeedKPH - _kph);
            }
        }
Exemplo n.º 36
0
    public Position(Position position)
    {
      if (position == null)
        throw new ArgumentNullException("position");

      Timestamp = position.Timestamp;
      Latitude = position.Latitude;
      Longitude = position.Longitude;
      Altitude = position.Altitude;
      AltitudeAccuracy = position.AltitudeAccuracy;
      Accuracy = position.Accuracy;
      Heading = position.Heading;
      Speed = position.Speed;
    }
Exemplo n.º 37
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 void OnLocationChanged(Location location)
        {
            if (location.Provider != this.activeProvider)
            {
                if (this.activeProvider != null && this.manager.IsProviderEnabled(this.activeProvider))
                {
                    LocationProvider pr = this.manager.GetProvider(location.Provider);
                    TimeSpan lapsed = GetTimeSpan(location.Time) - GetTimeSpan(this.lastLocation.Time);

                    if (pr.Accuracy > this.manager.GetProvider(this.activeProvider).Accuracy
                      && lapsed < timePeriod.Add(timePeriod))
                    {
                        location.Dispose();
                        return;
                    }
                }

                this.activeProvider = location.Provider;
            }

            var previous = Interlocked.Exchange(ref this.lastLocation, location);
            if (previous != null)
                previous.Dispose();

            var p = new Position();
            if (location.HasAccuracy)
                p.Accuracy = location.Accuracy;
            if (location.HasAltitude)
                p.Altitude = location.Altitude;
            if (location.HasBearing)
                p.Heading = location.Bearing;
            if (location.HasSpeed)
                p.Speed = location.Speed;

            p.Longitude = location.Longitude;
            p.Latitude = location.Latitude;
            p.Timestamp = GeolocatorImplementation.GetTimestamp(location);

            var changed = PositionChanged;
            if (changed != null)
                changed(this, new PositionEventArgs(p));
        }
Exemplo n.º 39
0
        public ListeningSpeedProbe()
        {
            _positionChangedHandler = (o, e) =>
            {
                if (e.Position == null)
                    return;

                lock (_locker)
                {
                    SensusServiceHelper.Get().Logger.Log("Received position change notification.", LoggingLevel.Verbose, GetType());

                    if (_previousPosition == null)
                        _previousPosition = e.Position;
                    else if (e.Position.Timestamp > _previousPosition.Timestamp)  // it has happened (rarely) that positions come in out of order...drop any such positions.
                    {
                        StoreDatum(new SpeedDatum(e.Position.Timestamp, _previousPosition, e.Position));
                        _previousPosition = e.Position;
                    }
                }
            };
        }
Exemplo n.º 40
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);
            };
        }
Exemplo n.º 41
0
 protected override sealed void StopListening()
 {
     GpsReceiver.Get().RemoveListener(_positionChangedHandler);
     _previousPosition = null;
 }
Exemplo n.º 42
0
 protected override sealed void StartListening()
 {
     _previousPosition = null;
     GpsReceiver.Get().AddListener(_positionChangedHandler, false);
 }
Exemplo n.º 43
0
        /// <summary>
        /// Calculates distance (KM) given two lat-lon positions (http://www.movable-type.co.uk/scripts/latlong.html)
        /// </summary>
        /// <returns>Distance in KM.</returns>
        /// <param name="previousPosition">Previous position.</param>
        /// <param name="currentPosition">Current position.</param>
        public static double CalculateDistanceKM(Position previousPosition, Position currentPosition)
        {
            double φ1 = DegreesToRadians(previousPosition.Latitude);
            double φ2 = DegreesToRadians(currentPosition.Latitude);
            double Δφ = DegreesToRadians(currentPosition.Latitude - previousPosition.Latitude);
            double Δλ = DegreesToRadians(currentPosition.Longitude - previousPosition.Longitude);

            double a = Math.Pow(Math.Sin(Δφ / 2), 2) +
                Math.Cos(φ1) *
                Math.Cos(φ2) *
                Math.Pow(Math.Sin(Δλ / 2), 2);

            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            return 6371 * c;
        }
Exemplo n.º 44
0
 protected override void InternalStart()
 {
     lock (_locker)
     {
         _previousPosition = null;  // do this before starting the base-class poller so it doesn't race to grab a stale previous location.
         base.InternalStart();
     }
 }
Exemplo n.º 45
0
        /// <summary>
        /// Gets a GPS reading, reusing an old one if it isn't too old. Will block the current thread while waiting for a GPS reading. Should not
        /// be called from the main / UI thread, since GPS runs on main thread (will deadlock).
        /// </summary>
        /// <returns>The reading.</returns>
        /// <param name="maxReadingAgeForReuseMS">Maximum age of old reading to reuse (milliseconds).</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public Position GetReading(int maxReadingAgeForReuseMS, CancellationToken cancellationToken)
        {  
            lock (_locker)
            {

                try
                {
                    SensusServiceHelper.Get().AssertNotOnMainThread(GetType() + " GetReading");
                }
                catch (Exception)
                {
                    return null;
                }

                if (SensusServiceHelper.Get().ObtainPermission(Permission.Location) != PermissionStatus.Granted)
                    return null;

                // reuse existing reading if it isn't too old
                if (_reading != null && maxReadingAgeForReuseMS > 0)
                {
                    double readingAgeMS = (DateTimeOffset.UtcNow - _reading.Timestamp).TotalMilliseconds;
                    if (readingAgeMS <= maxReadingAgeForReuseMS)
                    {
                        SensusServiceHelper.Get().Logger.Log("Reusing previous GPS reading, which is " + readingAgeMS + "ms old (maximum = " + maxReadingAgeForReuseMS + "ms).", LoggingLevel.Verbose, GetType());
                        return _reading;
                    }
                }

                if (_readingIsComing)
                    SensusServiceHelper.Get().Logger.Log("A GPS reading is coming. Will wait for it.", LoggingLevel.Debug, GetType());
                else
                {
                    _readingIsComing = true;  // tell any subsequent, concurrent callers that we're taking a reading
                    _readingWait.Reset();  // make them wait

                    new Thread(async () =>
                        {
                            try
                            {
                                SensusServiceHelper.Get().Logger.Log("Taking GPS reading.", LoggingLevel.Debug, GetType());

                                DateTimeOffset readingStart = DateTimeOffset.UtcNow;
                                _locator.DesiredAccuracy = SensusServiceHelper.Get().GpsDesiredAccuracyMeters;
                                Position newReading = await _locator.GetPositionAsync(timeoutMilliseconds: _readingTimeoutMS, token: cancellationToken);
                                DateTimeOffset readingEnd = DateTimeOffset.UtcNow;

                                if (newReading != null)
                                {                                   
                                    // create copy of new position to keep return references separate, since the same Position object is returned multiple times when a change listener is attached.
                                    _reading = new Position(newReading);                                   

                                    SensusServiceHelper.Get().Logger.Log("GPS reading obtained in " + (readingEnd - readingStart).TotalSeconds + " seconds.", LoggingLevel.Verbose, GetType());
                                }
                            }
                            catch (Exception ex)
                            {
                                SensusServiceHelper.Get().Logger.Log("GPS reading failed:  " + ex.Message, LoggingLevel.Normal, GetType());
                                _reading = null;
                            }

                            _readingWait.Set();  // tell anyone waiting on the shared reading that it is ready
                            _readingIsComing = false;  // direct any future calls to this method to get their own reading

                        }).Start();
                }
            }

            _readingWait.WaitOne(_readingTimeoutMS);

            if (_reading == null)
                SensusServiceHelper.Get().Logger.Log("GPS reading is null.", LoggingLevel.Normal, GetType());

            return _reading;
        }
        internal static Position GetPosition(GeoPosition<GeoCoordinate> position)
        {
            if (position.Location.IsUnknown)
                return null;

            var p = new Position();
            p.Accuracy = position.Location.HorizontalAccuracy;
            p.Longitude = position.Location.Longitude;
            p.Latitude = position.Location.Latitude;

            if (!Double.IsNaN(position.Location.VerticalAccuracy) && !Double.IsNaN(position.Location.Altitude))
            {
                p.AltitudeAccuracy = position.Location.VerticalAccuracy;
                p.Altitude = position.Location.Altitude;
            }

            if (!Double.IsNaN(position.Location.Course))
                p.Heading = position.Location.Course;

            if (!Double.IsNaN(position.Location.Speed))
                p.Speed = position.Location.Speed;

            p.Timestamp = position.Timestamp.ToUniversalTime();

            return p;
        }
Exemplo n.º 47
0
 public double KmDistanceTo(Position position)
 {
     return SpeedDatum.CalculateDistanceKM(_position, position);
 }
		private void UpdatePosition (CLLocation location)
		{
			Position p = (this.position == null) ? new Position () : new Position (this.position);
			
			if (location.HorizontalAccuracy > -1)
			{
				p.Accuracy = location.HorizontalAccuracy;
				p.Latitude = location.Coordinate.Latitude;
				p.Longitude = location.Coordinate.Longitude;
			}
			
			if (location.VerticalAccuracy > -1)
			{
				p.Altitude = location.Altitude;
				p.AltitudeAccuracy = location.VerticalAccuracy;
			}
			
			if (location.Speed > -1)
				p.Speed = location.Speed;

            var dateTime = location.Timestamp.ToDateTime().ToUniversalTime();
            p.Timestamp = new DateTimeOffset (dateTime);
			
			this.position = p;
			
			OnPositionChanged (new PositionEventArgs (p));

			location.Dispose();
		}
        private void Finish(Location location)
        {
            var p = new Position();
            if (location.HasAccuracy)
                p.Accuracy = location.Accuracy;
            if (location.HasAltitude)
                p.Altitude = location.Altitude;
            if (location.HasBearing)
                p.Heading = location.Bearing;
            if (location.HasSpeed)
                p.Speed = location.Speed;

            p.Longitude = location.Longitude;
            p.Latitude = location.Latitude;
            p.Timestamp = GeolocatorImplementation.GetTimestamp(location);

            if (this.finishedCallback != null)
                this.finishedCallback();

            this.completionSource.TrySetResult(p);
        }
Exemplo n.º 50
0
        public override void ResetForSharing()
        {
            base.ResetForSharing();

            _previousPosition = null;
        }
        private static Position GetPosition(Geoposition position)
        {
            var pos = new Position
            {
                Accuracy = position.Coordinate.Accuracy,
                Latitude = position.Coordinate.Point.Position.Latitude,
                Longitude = position.Coordinate.Point.Position.Longitude,
                Timestamp = position.Coordinate.Timestamp.ToUniversalTime(),
            };

            if (position.Coordinate.Heading != null)
                pos.Heading = position.Coordinate.Heading.Value;

            if (position.Coordinate.Speed != null)
                pos.Speed = position.Coordinate.Speed.Value;

            if (position.Coordinate.AltitudeAccuracy.HasValue)
                pos.AltitudeAccuracy = position.Coordinate.AltitudeAccuracy.Value;

            pos.Altitude = position.Coordinate.Point.Position.Altitude;

            return pos;
        }
		private void OnUpdatedHeading (object sender, CLHeadingUpdatedEventArgs e)
		{
			if (e.NewHeading.TrueHeading == -1)
				return;

			Position p = (this.position == null) ? new Position () : new Position (this.position);

			p.Heading = e.NewHeading.TrueHeading;

			this.position = p;
			
			OnPositionChanged (new PositionEventArgs (p));
		}
Exemplo n.º 53
0
        protected override IEnumerable<Datum> Poll(CancellationToken cancellationToken)
        {
            lock (_locker)
            {
                SpeedDatum datum = null;

                Position currentPosition = GpsReceiver.Get().GetReading(cancellationToken);

                if (currentPosition == null)
                    throw new Exception("Failed to get GPS reading.");
                else
                {
                    if (_previousPosition == null)
                        _previousPosition = currentPosition;
                    else if (currentPosition.Timestamp > _previousPosition.Timestamp)  // it has happened (rarely) that positions come in out of order...drop any such positions.
                    {
                        datum = new SpeedDatum(currentPosition.Timestamp, _previousPosition, currentPosition);
                        _previousPosition = currentPosition;
                    }
                }

                if (datum == null)
                    return new Datum[] { };  // datum will be null on the first poll and where polls return locations out of order (rare). these should count toward participation.
                else
                    return new Datum[] { datum };
            }
        }
Exemplo n.º 54
0
    public PositionEventArgs(Position position)
    {
      if (position == null)
        throw new ArgumentNullException("position");

      Position = position;
    }
Exemplo n.º 55
0
        public static double CalculateSpeedKPH(Position previousPosition, Position currentPosition, out double distanceKM, out double timeHours)
        {
            distanceKM = CalculateDistanceKM(previousPosition, currentPosition);
            timeHours = new TimeSpan(currentPosition.Timestamp.Ticks - previousPosition.Timestamp.Ticks).TotalHours;

            return distanceKM / timeHours;
        }
        /// <inheritdoc/>
        private void OnListenerPositionChanged(object sender, PositionEventArgs e)
        {
            if (!IsListening) // ignore anything that might come in afterwards
                return;

            lock (positionSync)
            {
                lastPosition = e.Position;

                var changed = PositionChanged;
                if (changed != null)
                    changed(this, e);
            }
        }
Exemplo n.º 57
0
        public GetGeoCS()
        {
            button = new Button
            {
                Text = "Get Geolocator"
            };
            button.Clicked += async (sender, e) =>
            {
                IGeolocator locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 50;

                if (locator.IsGeolocationAvailable)
                {
                    if (locator.IsGeolocationEnabled)
                    {
                        try
                        {
                            position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
                            latLabel.Text = "Latitude: " + position.Latitude;
                            lonLabel.Text = "Longitude: " + position.Longitude;

                            System.Diagnostics.Debug.WriteLine("TimeStamp: " + position.Timestamp);
                        }
                        catch (GeolocationException ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.InnerException);
                            await DisplayAlert("Error", "Unauthorized", "OK");
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.InnerException);
                        }
                    }
                    else
                        await DisplayAlert("Error", "Geo sensors is not turned on.\nPlease turn on it.", "OK");

                }
                else
                    await DisplayAlert("Error", "This device does not have any geo sensors or enough permission to use it.", "OK");


            };

            latLabel = new Label
            {
                Text = "Latitude: "
            };
            lonLabel = new Label
            {
                Text = "Longitude: "
            };

            
            Content = new StackLayout
            {
                Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 10),
                Children = {
                    button,
                    latLabel,
                    lonLabel
                }
            };
        }