private async Task AddPinMap() { if (checkRegistro != null) { Plugin.Geolocator.Abstractions.Position pos = await compGPS.GetCurrentLocation(); if (pos != null && pos.Latitude != 0 && pos.Longitude != 0) { Position _position = new Position(pos.Latitude, pos.Longitude); var MyPos = new Pin() { Position = _position, Label = "MINHA POSIÇÃO" }; map.Pins.Clear(); map.Pins.Add(MyPos); map.InitialCameraUpdate = CameraUpdateFactory.NewCameraPosition(new CameraPosition(_position, 15D, 0d, 0d)); map.MoveToRegion(MapSpan.FromCenterAndRadius(MyPos.Position, Distance.FromMeters(2000)), true); } else { map.InitialCameraUpdate = CameraUpdateFactory.NewCameraPosition(new CameraPosition(new Position(-17.7920769, -50.9238804), 13D, 0d, 0d)); } } }
public MainTabPage() { CrossGeolocator.Current.DesiredAccuracy = 1; CrossGeolocator.Current.AllowsBackgroundUpdates = true; CrossGeolocator.Current.PositionChanged += Current_PositionChanged; CrossConnectivity.Current.ConnectivityChanged += ConnectivityChanged; _mapPage = new DriverMapPage(); _orderListPage = new OrderListPage(); _timer = DependencyService.Get <ITimer>(DependencyFetchTarget.NewInstance); _timer.Tick += TimerTick; _timer.Interval = 5000; if (!CrossGeolocator.Current.IsGeolocationEnabled) { ShowLocationError(); _showError = true; var position = new Plugin.Geolocator.Abstractions.Position(); position.Longitude = 103.85; position.Latitude = 1.35; _mapPage.UpdateMapRegion(position); } else { StartListner(); } Title = "FOOD DELIVERY"; Children.Add(_mapPage); Children.Add(_orderListPage); Children.Add(new OrdersCompletedPage()); Children.Add(new ChatPage()); }
async void GetLocation() { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; Plugin.Geolocator.Abstractions.Position position = null; try { position = await locator.GetPositionAsync(10000); } catch (Exception e) { position = null; //TODO TURN OFF THE SPINNER //SHOW THE ERROR MESSAGE LABEL } AppData appData = (AppData)BindingContext; labelStatus.Text = "Your location:"; if (position != null) { appData.MasterViewModel.PlantList.TargetPlant.Lat = position.Latitude; appData.MasterViewModel.PlantList.TargetPlant.Lng = position.Longitude; ReverseGeocode(); } EnableUserCounty(); labelNotInArea.IsVisible = appData.MasterViewModel.PlantList.TargetPlant.NativeTo_None; //IS THERE A WAY FOR THIS TO KNOW THAT THE ERROR OCCURRED? labelTip.IsVisible = !appData.MasterViewModel.PlantList.TargetPlant.NativeTo_None; }
Plugin.Geolocator.Abstractions.Position position; // = viewModelOne.CurrentPosition; //public void OnPositionChanged() //{ // CrossGeolocator.Current.PositionChanged += Current_PositionChanged; //} private void Current_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e) { MyMap.Pins.Clear(); position = e.Position; MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromKilometers(1.00))); AddPin(); }
async void InitializeLocationManagerAsync() { Plugin.Geolocator.Abstractions.Position f = await Plugin.Geolocator.CrossGeolocator.Current.GetPositionAsync(); _local = f.Latitude; _local2 = f.Longitude; }
private void GetCurrentPosition() { Task.Run(async() => { try { var crossGeolocator = CrossGeolocator.Current; if (!crossGeolocator.IsGeolocationAvailable || !crossGeolocator.IsGeolocationEnabled) { await DisplayAlert("title", "Not available or enabled", "Close"); } else { crossGeolocator.DesiredAccuracy = 100; Plugin.Geolocator.Abstractions.Position position = await crossGeolocator.GetLastKnownLocationAsync(); if (position != null) { Console.WriteLine($"Current Location: {position.Latitude}, {position.Longitude}"); AddPin("current location", "person 01", new Position(position.Latitude, position.Longitude)); } else { await DisplayAlert("title", "Unable to get location", "Close"); } } } catch (Exception ex) { await DisplayAlert("title", $"Unable to get location: {ex}", "Close"); } }); }
private void MoveMap(Plugin.Geolocator.Abstractions.Position position) { var center = new Position(position.Latitude, position.Longitude); var span = new MapSpan(center, 0.2, 0.2); LocationsMap.MoveToRegion(span); }
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); locarionsMap.MoveToRegion(span); }
async Task GetLocation() { try { var hasPermission = await Models.PluginPermission.CheckPermissions(Permission.Location); if (!hasPermission) { return; } var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 500; var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10)); if (position == null) { await DisplayAlert("Uh oh", "Null GPS.", "OK"); return; } savedPosition = position; } catch (Exception) { await DisplayAlert("Uh oh", "Something went wrong. Try turning on your GPS.", "OK"); await Navigation.PushAsync(new CartPage()); } }
async void GetAddress(Plugin.Geolocator.Abstractions.Position po) { try { var resAddress = await GooglePlacesHelper.GetAddress(po.Latitude, po.Longitude); if (resAddress != null && resAddress.results.Count > 0) { Traverse(resAddress); //ServicioModel.Lat = po.Latitude; //ServicioModel.Lang = po.Longitude; var place = resAddress.results[0]; Device.BeginInvokeOnMainThread(() => { _direccion.Text = place.formatted_address; _direccion.IsVisible = true; _loadingAddress.IsVisible = false; }); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
async void cdDrive(object sender, System.EventArgs e) { System.Diagnostics.Debug.WriteLine(" Clicked send location Button"); try { cdCallAPI mycallAPI = new cdCallAPI(); Plugin.Geolocator.Abstractions.Position mypos = await mycallAPI.GetCurrentPosition(); string cPosLat = mypos.Latitude.ToString(); string cPosLong = mypos.Longitude.ToString(); String mailSubject = "Student " + plogaccount.FirstName + " " + plogaccount.LastName + " location details"; String mailBody = "Location of student " + plogaccount.FirstName + " " + plogaccount.LastName + " " + cPosLat + " " + cPosLong; var myresult = mycallAPI.cdSendEmail(mailSubject, plogaccount.Attr1, mailBody); System.Diagnostics.Debug.WriteLine(" Result is " + myresult.ToString()); Status.Text = "Sent location " + cPosLat + " " + cPosLong + " to " + plogaccount.Attr1 + " Successfully"; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(" Result is " + ex); await DisplayAlert("Failed to get data. Please try later.", "Failed to get data. Please try later.", "OK"); } }
public MapPage() { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; var location = locator.GetPositionAsync(TimeSpan.FromTicks(10000)); Plugin.Geolocator.Abstractions.Position location1 = locator.GetPositionAsync(TimeSpan.FromTicks(10000)).Result; Position position = new Position(location1.Latitude, location1.Longitude); Map mymap = new Map(); mymap.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMiles(3))); Content = new StackLayout { Padding = new Thickness(5, 20, 5, 0), HorizontalOptions = LayoutOptions.Fill, Children = { mymap } }; }
public bool CheckSpeed(Plugin.Geolocator.Abstractions.Position pos) { if (pos.Speed > MPH) { mTimerStarted = false; mTimerLength = 0; var text = "http://35.9.22.105/historical-data/" + mLotOrder[mGoingTo].ToString() + "/0"; var uri = new Uri(text); var response = client.GetAsync(uri); mLotParked = ""; return(false); } else { mTimerLength += .5; if (mTimerLength > TimerMax) { var text = "http://35.9.22.105/historical-data/" + mLotOrder[mGoingTo].ToString() + "/1"; var uri = new Uri(text); var response = client.GetAsync(uri); mParked = true; return(false); } return(true); } }
/// <summary> /// コンストラクタ /// </summary> /// <param name="p"></param> public Position(Plugin.Geolocator.Abstractions.Position p) { // DateTimeOffset から DateTime へ変換(DateTimeOffsetは時差を考慮する場合に使用する構造体) TimeStamp = p.Timestamp.DateTime; Latitude = p.Latitude; Longitude = p.Longitude; }
async void OnLoadCommandExecuted() { try { if (!Edit) { Place.Radius = 1000; if (_lastPosition == null) { _lastPosition = await CrossGeolocator.Current.GetLastKnownLocationAsync(); if (_lastPosition == null) { _lastPosition = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(8), null, true); } } if (_lastPosition == null) { return; } Place.Latitude = Convert.ToDouble(_lastPosition?.Latitude); Place.Longitude = Convert.ToDouble(_lastPosition?.Longitude); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Error getting current position: {ex.Message}"); } }
public async void getLocation() { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; var position1 = locator.GetPositionAsync(timeoutMilliseconds: 10000); Plugin.Geolocator.Abstractions.Position position = position1.Result; if (position == null) { return; } var prefs = Android.App.Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private); viktem.UserName = prefs.GetString("PrefName", null); viktem.FBID = prefs.GetString("PrefId", null); viktem.StartDate = DateTime.Parse(position.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")); viktem.Latitude = "" + position.Latitude; viktem.Longitude = "" + position.Longitude; // Victim.Adress = "" + possibleAddresses.FirstOrDefault(); }
public void PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs arg) { if ((LocFlag == LocationFlag.Start || LocFlag == LocationFlag.InBackground) && (RouteCoordinates.Count == 0 || arg.Position.Timestamp.Ticks != RouteCoordinates.Last().Timestamp.Ticks)) //first element can be null, so dont use it { RouteCoordinates.Add(new Plugin.Geolocator.Abstractions.Position(arg.Position)); LastCoordinates.Add(new Plugin.Geolocator.Abstractions.Position(arg.Position)); DrawPoint = new Plugin.Geolocator.Abstractions.Position(arg.Position); switch (Device.RuntimePlatform) { case Device.iOS: case Device.Android: if (VisibleRegion != null) { this.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(arg.Position.Latitude, arg.Position.Longitude), VisibleRegion.Radius)); } break; case Device.UWP: //Implementation in native map break; } } }
// El método MoveMap() centra el mapa en la posción que le pasemos: puede ser la del usuario actualmente // ó una posición general (madrid), en caso de que el usuario no haya dado permisos. private void MoveMap(Plugin.Geolocator.Abstractions.Position position) { var mapCenter = new Position(position.Latitude, position.Longitude); var mapSpan = new MapSpan(mapCenter, 0.01, 0.01); locationMap.MoveToRegion(mapSpan); }
/// <summary> /// Function to get the current position. Returns 0,0 on failure. /// </summary> /// <param name="timeoutSeconds">Timeout for the GPS call. Default 20 seconds.</param> /// <returns>Current position of the device.</returns> public static async Task <Position> GetCurrentPosition(int timeoutSeconds = 20) { try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 100; Plugin.Geolocator.Abstractions.Position position = await locator.GetLastKnownLocationAsync(); if (position != null) { //got a cahched position, so let's use it. return(new Position(position.Latitude, position.Longitude)); } if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled) { //not available or enabled throw new Exception("Geolocation not available or not enabled."); } position = await locator.GetPositionAsync(TimeSpan.FromSeconds(timeoutSeconds), null, true); } catch (Exception e) { if (!e.Message.Contains("Geolocation not")) { OutputException(e); } } return(new Position(0, 0)); }
public MasterDetailPage1Detail() { InitializeComponent(); Instance = this; myMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(36.713001, 3.178525), Xamarin.Forms.Maps.Distance.FromKilometers(10000))); var locator = CrossGeolocator.Current; if (SelectMap == 1) { locator.DesiredAccuracy = 10; } Task.Run(async() => { position = await locator.GetPositionAsync(); SelectMap = 0; // await StartListening(); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { myMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Xamarin.Forms.Maps.Distance.FromMiles(1))); var pin = new Pin { Position = new Position(position.Latitude, position.Longitude), Label = "أنت هنا !", }; myMap.Pins.Add(pin); AffichePin(); }); }); }
protected async override void OnAppearing() { base.OnAppearing(); // Show the logo MessagingService.Current.SendMessage(MessageKeys.ChangeToolbar, true); // On Droid this wraps behind the other views. if (Device.RuntimePlatform == Device.Android) { Grid.SetRowSpan(mapView, 3); if (ToolbarItems.Count > 1) { var firstItem = ToolbarItems.FirstOrDefault(); ToolbarItems.Remove(firstItem); } } try { // Set the map to your current location. var locator = CrossGeolocator.Current; Plugin.Geolocator.Abstractions.Position position = await locator.GetPositionAsync(TimeSpan.FromSeconds(5), null, true); if (position != null) { mapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromMiles(10)).WithZoom(16)); } } catch { // No biggie if you don't allow location, only here for show purposes. } }
public async void GetPosition() { Plugin.Geolocator.Abstractions.Position position = null; try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 100; position = await locator.GetLastKnownLocationAsync(); if (position != null) { _position = new Position(position.Latitude, position.Longitude); //got a cahched position, so let's use it. return; } if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled) { //not available or enabled return; } position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true); } catch (Exception ex) { throw ex; //Display error as we have timed out or can't get location. } _position = new Position(position.Latitude, position.Longitude); if (position == null) { return; } }
public async Task <IResponseData <Direction> > GetDirectionAsync(Plugin.Geolocator.Abstractions.Position start, Plugin.Geolocator.Abstractions.Position destination, List <Plugin.Geolocator.Abstractions.Position> waypoints = null) { var pointA = $"{start.Latitude.DoubleToString ()},{start.Longitude.DoubleToString ()}"; var pointB = $"{destination.Latitude.DoubleToString ()},{destination.Longitude.DoubleToString ()}"; List <string> points = new List <string> (); IResponseData <GoogleDirectionModels> result; if (waypoints != null && waypoints.Count != 0) { waypoints.ForEach(waypoint => points.Add($"{waypoint.Latitude.DoubleToString ()},{waypoint.Longitude.DoubleToString ()}")); result = await _googleApiService.GetDirectionAsync(pointA, pointB, points); } else { result = await _googleApiService.GetDirectionAsync(pointA, pointB); } if (result.IsSuccess) { if (result.Data.routes.Count == 0) { // TODO: as resource return(new ResponseData <Direction> (null, false, "No routs found")); } var polylinePoints = DecodePolyline(result.Data.routes[0].overview_polyline.points); var direction = new Direction(polylinePoints); return(new ResponseData <Direction> (direction, true)); } return(new ResponseData <Direction> (null, false, result.ErrorMessage)); }
//============================================================================== //============================== FCT SECONDAIRES =============================== //============================================================================== private static async Task <Plugin.Geolocator.Abstractions.Position> GetCurrentLocation() { Plugin.Geolocator.Abstractions.Position myPos = null; try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 100; myPos = await locator.GetLastKnownLocationAsync(); if (myPos != null) { return(myPos); } else { Console.WriteLine("Erreur, la dernière position connue est nulle ! "); return(null); } } catch (Exception e) { Console.WriteLine("Unable to get location : " + e.Message); return(null); } }
private void MoveMap(Position position) { var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude); var span = new Xamarin.Forms.Maps.MapSpan(center, 0.005, 0.005);// 1 - oznacza ile stóp w lewo i w góre ustawia się mapa od lokalizacji locationsMap.MoveToRegion(span); }
protected override async void OnMapReady(GoogleMap nativeMap, Map map) { map.MyLocationButtonClicked += (sender, args) => { PedirGps(); }; var status = await Utils.PedirPermissaoLocalizacao(); if (status == PermissionStatus.Granted) { Map.MyLocationEnabled = true; Map.UiSettings.MyLocationButtonEnabled = true; Plugin.Geolocator.Abstractions.Position posicao = await Utils.PedirLocalizacao(); if (posicao != null) { Map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(posicao.Latitude, posicao.Longitude), Distance.FromMiles(0.1))); } else { PedirGps(); } } base.OnMapReady(nativeMap, map); }
/// <summary> /// Method that runs when the "Find my location" button is pressed. /// It finds the current position of the device and uses other method to translate it to an address. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OnFind(object sender, EventArgs e) { MyMap.Pins.Clear(); //Clear all previous pins that were on the map. var locator = CrossGeolocator.Current; // Create the geo locator pos = await locator.GetPositionAsync(timeoutMilliseconds : 10000); // Get the current fused position from the device's GPS HW position = new Position(pos.Latitude, pos.Longitude); // Instantiate the Position with the data obtained from the device reverseGeocodedOutputLabel.Text = "Searching.."; // Verification for user, that the device is searching for location. latitude.Text = "Latitude: " + pos.Latitude; // Update label. longitude.Text = "Longitude: " + pos.Longitude; // Update label. fromLatitude = pos.Latitude.ToString(); // Store the value for later access. fromLongitude = pos.Longitude.ToString(); // Store the value for later access. pin = new Pin /* Create new Pin on the map - Start location */ { Type = PinType.Place, Position = position, Label = "Start location", Address = "Your taxi will pick you up here." }; MyMap.Pins.Add(pin); // Add the pin to the map. DecodeAddress(position); // Decode the GPS Coordinates into an address *** More info in method description *** try { double km = 10.0; //CalcApproxKm(position, destinationPosition); MapSpan span = MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(km)); MyMap.MoveToRegion(span); // Move the map to the selected region. } catch (Exception) { MapSpan span = MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(5)); MyMap.MoveToRegion(span); // Move the map to the selected region. throw; } }
private async void ChecagemServidorDisponivelAsync() { Plugin.Geolocator.Abstractions.Position pos = await GetCurrentPosition(); CrossSettings.Current.Set("UltimaLocalizacaoValida", pos); BuscaPosicao(pos); }
public async void GetUserLocation() { try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 100; locationEnabled = true; if (!locator.IsGeolocationAvailable) { locationEnabled = false; await Application.Current.MainPage.DisplayAlert("Error", "Please enable location permissions for eventizr.", "Dismiss"); } else { if (!locator.IsGeolocationEnabled) { locationEnabled = false; await Application.Current.MainPage.DisplayAlert("Error", "Please enable location.", "Dismiss"); } else { position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10), null, true); SetMapLocation(position.Latitude, position.Longitude); } } } catch (Exception) { await Application.Current.MainPage.DisplayAlert("Error", "Couldn't get your location.", "Dismiss"); locationEnabled = false; } }
public async Task <ReversedGeocode> GetReversedGeocodeForLatLngAsync(Position position) { var json = await _httpClient.GetStringAsync($"{Uri}azureMaps?query={position.ToPositionString()}"); var result = JsonConvert.DeserializeObject <ReversedGeocode>(json); return(result); }