/// <summary> /// On Google play services Connection handling /// </summary> /// <param name="connectionHint"></param> async public void OnConnected(Bundle connectionHint) { FusedLocationProviderClient localClient = null; // must lock here to ensure initialization is complete before this callback is executed by another thread. // accessing the member var `mFusedLocationProviderClient` within the lock ensures variable publishing. // the local scoped variable can reference the member instance then `await` syntax used outside the lock. lock (Lock) { localClient = mFusedLocationProviderClient; } var location = await localClient.GetLastLocationAsync(); SetLastKnownLocation(location); if (CurrentRequestType == RequestType.Add) { AddGeofences(); StartLocationUpdates(); } else if (CurrentRequestType == RequestType.Clear) { RemoveGeofences(); } else if (CurrentRequestType == RequestType.Delete) { if (mRequestedRegionIdentifiers != null) { RemoveGeofences(mRequestedRegionIdentifiers); } } CurrentRequestType = RequestType.Default; System.Diagnostics.Debug.WriteLine("Connection obtained, starting service"); }
// get My Location async void GetMyLocation() { if (!CheckLocationPermission()) { return; } mLastLocation = await LocationClient.GetLastLocationAsync(); if (mLastLocation != null) { LatLng myposition = new LatLng(mLastLocation.Latitude, mLastLocation.Longitude); mainMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(myposition, 20)); // get Address Address address = await ReverseGeocodeCurrentLocation(myposition); DisplayAddress(address); MarkerOptions options = new MarkerOptions() .SetPosition(myposition) .SetIcon(null) // .SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.greenmarker)) .SetTitle(Governorate) .SetSnippet(_addressText) .Draggable(true); mainMap.AddMarker(options); } }
async Task GetLastLocationFromDevice() { getLastLocationButton.SetText(Resource.String.getting_last_location); var location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { latitude.SetText(Resource.String.location_unavailable); longitude.SetText(Resource.String.location_unavailable); speed.SetText(Resource.String.location_unavailable); provider.SetText(Resource.String.could_not_get_last_location); } else { latitude.Text = Resources.GetString(Resource.String.latitude_string, location.Latitude); longitude.Text = Resources.GetString(Resource.String.longitude_string, location.Longitude); speed.Text = Resources.GetString(Resource.String.speed_string, location.Speed * 3.6); provider.Text = Resources.GetString(Resource.String.provider_string, location.Provider); getLastLocationButton.SetText(Resource.String.get_last_location_button_text); fileLogger.LogInformation($"{DateTime.Now} - Lat: {location.Latitude} , Long: {location.Longitude} , Speed: {location.Speed * 3.6}"); } //var timer = new System.Threading.Timer(async(e) => //{ // var location = await fusedLocationProviderClient.GetLastLocationAsync(); // if (location != null) // { // fileLogger.LogInformation($"{DateTime.Now} - Lat: {location.Latitude} , Long: {location.Longitude} , Speed: {location.Speed * 3.6}"); // } //}, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(1000)); }
/// <summary> /// On Google play services Connection handling /// </summary> /// <param name="connectionHint"></param> async public void OnConnected(Bundle connectionHint) { Android.Locations.Location location = await mFusedLocationProviderClient.GetLastLocationAsync(); SetLastKnownLocation(location); if (CurrentRequestType == RequestType.Add) { AddGeofences(); StartLocationUpdates(); } else if (CurrentRequestType == RequestType.Clear) { RemoveGeofences(); } else if (CurrentRequestType == RequestType.Delete) { if (mRequestedRegionIdentifiers != null) { RemoveGeofences(mRequestedRegionIdentifiers); } } CurrentRequestType = RequestType.Default; System.Diagnostics.Debug.WriteLine("Connection obtained, starting service"); }
public async Task <LocationModel> GetCurrentLocation() { try { IsGooglePlayServicesInstalled(); if (CurrentLocation != null) { return(CurrentLocation); } ConnectService(); Location location = await fusedLocationProviderClient.GetLastLocationAsync(); CurrentLocation = new LocationModel { Lat = location.Latitude, Long = location.Longitude, IsAvailable = true }; } catch (System.Exception) { CurrentLocation = new LocationModel { Lat = 0, Long = 0, IsAvailable = false }; } return(CurrentLocation); }
async Task <Xamarin.Essentials.Location> GetLastLocation() { try { //var location = locationManager.GetLastKnownLocation(LocationManager.GpsProvider); var location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location != null) { Toast.MakeText(CrossCurrentActivity.Current.Activity, "Accuracy => " + location.Accuracy, ToastLength.Long); return(new Xamarin.Essentials.Location { Accuracy = location.Accuracy, Altitude = location.Altitude, Latitude = location.Latitude, Longitude = location.Longitude, Speed = location.Speed }); } else { Log.Info("GPS STATUS", "Trouble retrieving location"); } } catch (Exception ex) { Log.Error("GPS EXCEPTION", ex.StackTrace); } return(null); }
private async void OnClickGetLastLocation(object sender, EventArgs eventArgs) { string Tag = "LastLocation"; var lastLocationTask = fusedLocationProviderClient.GetLastLocationAsync(); try { await lastLocationTask; if (lastLocationTask.IsCompleted && lastLocationTask.Result != null) { Location location = lastLocationTask.Result; if (location == null) { log.Info(Tag, "Last Location is null."); } else { log.Info("Longitude,Latitude", $"{location.Longitude},{location.Latitude}"); } } else { log.Error(Tag, $"GetLastLocationAsync failed: {lastLocationTask.Exception.Message}"); } } catch (Exception e) { log.Error(Tag, $"GetLastLocationAsync exception: {e.Message}"); } }
async Task GetLastLocationFromDevice() { getLastLocationButton.SetText(Resource.String.getting_last_location); var location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { latitude.SetText(Resource.String.location_unavailable); longitude.SetText(Resource.String.location_unavailable); provider.SetText(Resource.String.could_not_get_last_location); } else { var currentCulture = System.Globalization.CultureInfo.InstalledUICulture; var numberFormat = (System.Globalization.NumberFormatInfo)currentCulture.NumberFormat.Clone(); numberFormat.NumberDecimalSeparator = "."; latitude.Text = Resources.GetString(Resource.String.latitude_string, location.Latitude); longitude.Text = Resources.GetString(Resource.String.longitude_string, location.Longitude); globalLocationLat = location.Latitude.ToString().Replace(',', '.'); globalLocationLong = location.Longitude.ToString().Replace(',', '.'); provider.Text = Resources.GetString(Resource.String.provider_string, location.Provider); getLastLocationButton.SetText(Resource.String.get_last_location_button_text); } }
private async Task LoadLocation() { Permission permissionId; if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { permissionId = Activity.CheckSelfPermission(permission); } else { permissionId = (int)Permission.Granted; } LatLng latlngall = new LatLng(0.0, 0.0); if (permissionId == (int)Permission.Granted) { Location location = await fusedLocationProviderClient.GetLastLocationAsync(); //latlngall = new LatLng(19.4715, -99.2495); //latlngall = new LatLng(20.65524, -105.22744999999999); latlngall = new LatLng(location.Latitude, location.Longitude); _userLocation.Latitude = latlngall.Latitude; _userLocation.Longitude = latlngall.Longitude; CurrentPosition = latlngall; } else { await LoadLocation(); } }
/// <summary> /// Loads all of the needed elements /// </summary> /// <param name="savedInstanceState"></param> protected override void OnCreate(Bundle savedInstanceState) { try { base.OnCreate(savedInstanceState); Forms.Init(this, savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); finalOrder = new FinalOrder(); fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this); var location = fusedLocationProviderClient.GetLastLocationAsync(); MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map); mapFragment.GetMapAsync(this); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private async void GetLocation() { if (!CheckPermission()) { Toast.MakeText(this, "No permission", ToastLength.Long).Show(); return; } lastLocation = await locationClient.GetLastLocationAsync(); }
async Task getLastLocationFromDevice(FusedLocationProviderClient fusedLocationProviderClient) { currentLocation = await fusedLocationProviderClient.GetLastLocationAsync(); if (currentLocation == null) { // Seldom happens, but should code that handles this scenario } }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.CustomMap); _toolbar = FindViewById <Toolbar>(Resource.Id.tv_cm_toolbar); SetSupportActionBar(_toolbar); SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.SetHomeButtonEnabled(true); _setPlaceButton = FindViewById <Button>(Resource.Id.btn_cm_setCoordinates); PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)FragmentManager.FindFragmentById(Resource.Id.place_autocomplete_fragment); var content = Intent.GetStringExtra("place"); _isEditable = Intent.GetBooleanExtra("isEditable", false); if (!_isEditable) { autocompleteFragment.View.Visibility = ViewStates.Gone; _setPlaceButton.Visibility = ViewStates.Gone; } else { autocompleteFragment.SetOnPlaceSelectedListener(this); autocompleteFragment.SetBoundsBias(new LatLngBounds( new LatLng(4.5931, -74.1552), new LatLng(4.6559, -74.0837))); _setPlaceButton.Click += SetPlaceButton_Click; } if (!string.IsNullOrWhiteSpace(content)) { _markerPosition = JsonConvert.DeserializeObject <Coordinates>(content); } _fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this); _mapFragment = FragmentManager.FindFragmentByTag("map") as MapFragment; if (_mapFragment == null) { Location location = await _fusedLocationProviderClient.GetLastLocationAsync(); var myPosition = new LatLng(location.Latitude, location.Longitude);// (20.5, 20.5); GoogleMapOptions mapOptions = new GoogleMapOptions() .InvokeMapType(GoogleMap.MapTypeNormal) .InvokeZoomControlsEnabled(true) .InvokeMapToolbarEnabled(true) .InvokeCamera(new CameraPosition(myPosition, 10, 0, 0)) .InvokeCompassEnabled(true); FragmentTransaction fragTx = FragmentManager.BeginTransaction(); _mapFragment = MapFragment.NewInstance(mapOptions); fragTx.Add(Resource.Id.map, _mapFragment, "map"); fragTx.Commit(); } _mapFragment.GetMapAsync(this); }
public async Task <LocationResult> GetLastLocationFromDevice() { var loc = new LocationResult(); var location = await fusedLocationProviderClient.GetLastLocationAsync(); loc.latitude = location.Latitude; loc.longitude = location.Longitude; return(loc); }
private async void LocateMe_ClickHandler(object sender, EventArgs e) { if (!MainActivity.IsLocationEnabled || !MainActivity.IsLocationAccessGranted) { return; } Location location = await FusedLocationProviderClient.GetLastLocationAsync(); MoveToLocation(location); }
public Task <Location> GetLocationAsync() { if (fusedLocationProviderClient != null) { return(fusedLocationProviderClient.GetLastLocationAsync()); } else { return(Task.FromResult(locationManager.GetLastKnownLocation(locationProvider))); } }
public async Task <Maybe <WeatherLocation> > GetLastLocation() { var location = await _locationProvider.GetLastLocationAsync(); if (location != null) { var weather = new WeatherLocation(location.Latitude, location.Longitude); return(Maybe <WeatherLocation> .Some(weather)); } return(Maybe <WeatherLocation> .None); }
/// <summary> /// When map is connected, gets current location, searches for nearest cafes and puts markers on the map /// </summary> /// <param name="map">our map</param> public async void OnMapReady(GoogleMap map) { try { TryToGetPermissions(); map.MapType = GoogleMap.MapTypeNormal; map.UiSettings.ZoomControlsEnabled = true; map.UiSettings.CompassEnabled = true; var currentLocation = await fusedLocationProviderClient.GetLastLocationAsync(); lat = currentLocation.Latitude; lon = currentLocation.Longitude; LatLng location = new LatLng(lat, lon); CameraPosition.Builder builder = CameraPosition.InvokeBuilder(); builder.Target(location); builder.Zoom(16); builder.Bearing(155); CameraPosition cameraPosition = builder.Build(); CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition); map.MoveCamera(cameraUpdate); MarkerOptions markerOpt1 = new MarkerOptions(); markerOpt1.SetPosition(new LatLng(lat, lon)); markerOpt1.SetTitle("My Position"); map.AddMarker(markerOpt1); var result = await NearByPlaceSearch(nearbyQuery, lat.ToString().Replace(",", "."), lon.ToString().Replace(",", "."), radius, typeSearch, typeSearch, ""); var listData = new ObservableCollection <SearchData.Result>(); if (result != null) { foreach (var item in result) { listData.Add(item); } System.Diagnostics.Debug.WriteLine("Total result: " + listData.Count); } map.InfoWindowClick += MapOnInfoWindowClick; AddLocationMarkers(map, listData); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public async Task <Location> GetLastLocationFromDevice() { Location location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { return(null); } else { return(location); } }
public override void AddView(AView child) { if (child is CoordinatorLayout) { base.AddView(child); return; } ((ViewGroup)child).LayoutParameters = new CoordinatorLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent); MainViewGroup = (ViewGroup)child; AndroidCoordinatorLayout.FindViewById <RelativeLayout>(Resource.Id.map_holder) .AddView(child); for (var i = 0; i < MainViewGroup.ChildCount; i++) { AView foundChild = MainViewGroup.GetChildAt(i); if (!(foundChild is CyclesMapRenderer cyclesMapRenderer)) { continue; } CyclesMapView = cyclesMapRenderer; CyclesMapView.MapReady += async sender => { if (!MainActivity.IsLocationAccessGranted || !MainActivity.IsLocationEnabled) { return; } Location lastLocation = await FusedLocationProviderClient.GetLastLocationAsync(); if (lastLocation == null) { return; } var addressResultReceiver = new MapPageRendererAddressResultReceiver(new Handler(), this); StartAddressIntentService(addressResultReceiver, lastLocation); var latLng = new LatLng(lastLocation.Latitude, lastLocation.Longitude); CameraPosition.Builder builder = CameraPosition.InvokeBuilder(); builder.Target(latLng); builder.Zoom(18); CameraPosition cameraPosition = builder.Build(); CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition); CyclesMapView.AnimateCamera(cameraUpdate); }; } }
private async Task GetLastLocation() { Android.Locations.Location location1 = await fusedLocationProviderClient.GetLastLocationAsync(); //if (location1 != null) //{ TextView txtLocation1 = FindViewById <TextView>(P6Test.Resource.Id.oldLocation); TextView txtLocation2 = FindViewById <TextView>(P6Test.Resource.Id.NewLocation); TextView speed = FindViewById <TextView>(P6Test.Resource.Id.speed); TextView updates = FindViewById <TextView>(P6Test.Resource.Id.updates); var position = location1; var test = CrossGeolocator.Current; test.DesiredAccuracy = 20; var position1 = test.GetPositionAsync(); if (i == 0) { oldLocation = new Xamarin.Essentials.Location(position.Latitude, position.Longitude); newLocation = new Xamarin.Essentials.Location(position.Latitude, position.Longitude); txtLocation1.Text = position.Latitude.ToString("#.###") + " : " + position.Longitude.ToString("#.###"); i = 1; updates.Text = i.ToString(); } else { oldLocation = newLocation; newLocation = new Xamarin.Essentials.Location(position.Latitude, position.Longitude); if (txtLocation2.Text.Equals("")) { txtLocation1.Text = txtLocation1.Text; } else { txtLocation1.Text = txtLocation2.Text; } txtLocation2.Text = position.Latitude.ToString("#.###") + " : " + position.Longitude.ToString("#.###"); //distance.Text = Location.CalculateDistance(oldLocation, newLocation, DistanceUnits.Kilometers).ToString() + " km"; updates.Text = i.ToString(); var speedkmh = position.Speed * 3.6; speed.Text = speedkmh.ToString("#.####") + " km/h"; } i++; //} }
async void GetLastLocationButtonOnClick(object sender, EventArgs eventArgs) { if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Permission.Granted) { await GetLastLocationFromDevice(); } else { RequestLocationPermission(RC_LAST_LOCATION_PERMISSION_CHECK); } var location = await fusedLocationProviderClient.GetLastLocationAsync(); // Get the MAC Address String macAddress = GetMACAddress2(); if (macAddress.Length > 17) { macAddress = macAddress.Substring(0, 17); } macAddressText.Text = macAddress; // Get the battery level int batteryLevel = GetBatteryLevel(); batteryLevelText.Text = batteryLevel.ToString(); if (location is null) { // Post the data PostData(macAddress.Replace(':', '-'), -36.00000, 174.000000, batteryLevel); } else { // Post the data PostData(macAddress.Replace(':', '-'), location.Latitude, location.Longitude, batteryLevel); } }
async void GetMyLocation() { if (!CheckLocationPermission()) { return; } mLastLocation = await locationClient.GetLastLocationAsync(); if (mLastLocation != null) { LatLng myposition = new LatLng(mLastLocation.Latitude, mLastLocation.Longitude); mainMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(myposition, 17)); } }
//Getting location for measurement public async Task <Android.Locations.Location> GetLastLocationFromDevice() { // This method assumes that the necessary run-time permission checks have succeeded. Android.Locations.Location location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { return(new Android.Locations.Location("Location didn't work")); } else { return(location); } }
async void DisplayLocation() { if (LocationProviderClient == null) { LocationProviderClient = LocationServices.GetFusedLocationProviderClient(this); } myLastLocation = await LocationProviderClient.GetLastLocationAsync(); if (myLastLocation != null) { myposition = new LatLng(myLastLocation.Latitude, myLastLocation.Longitude); map.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myposition, 15)); } }
async void GetMyLocation() { if (!CheckLocationPermission()) { return; } myLastLoc = await locApiClient.GetLastLocationAsync(); if (myLastLoc != null) { LatLng myposition = new LatLng(myLastLoc.Latitude, myLastLoc.Longitude); mainMap.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myposition, 18)); } }
private async void setCamOnMyLoc() { Location location = await fused.GetLastLocationAsync(); LatLng latlng = new LatLng(location.Latitude, location.Longitude); CameraPosition.Builder builder = CameraPosition.InvokeBuilder(); builder.Target(latlng); builder.Zoom(15); CameraPosition cameraPosition = builder.Build(); CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition); Map.AnimateCamera(cameraUpdate); //Map.MoveCamera(cameraUpdate); }
public async Task <Shared.Models.Location?> GetCurrentLocation() { if (!HasLocationPermissions()) { throw new UnauthorizedAccessException(); } var androidLocation = await _fusedLocationProviderClient.GetLastLocationAsync(); if (androidLocation == null) { return(null); } return(new Shared.Models.Location(androidLocation.Longitude, androidLocation.Latitude)); }
async Task GetLastLocationFromDevice() { // This method assumes that the necessary run-time permission checks have succeeded. //getLastLocationButton.SetText(Resource.String.getting_last_location); Android.Locations.Location location = await fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { // Seldom happens, but should code that handles this scenario } else { // Do something with the location coords = new LatLng(location.Latitude, location.Longitude); } }
private async Task GetLastLocationFromDevice() { // This method assumes that the necessary run-time permission checks have succeeded. //txtResult.SetText(Resource.String.getting_last_location); Android.Locations.Location location = await _fusedLocationProviderClient.GetLastLocationAsync(); if (location == null) { // Seldom happens, but should code that handles this scenario } else { // Do something with the location //Log.Debug("Sample", "The latitude is " + location.Latitude); } }