/// <summary> /// Finds the nearest restaurant. /// </summary> /// <returns>The nearest restaurant.</returns> /// <param name="location">Location.</param> public async static Task<string> FindNearestRestaurantAsync(CLLocation location) { // Search for restaurants near our location. string restaurant = string.Empty; try { var searchRequest = new MKLocalSearchRequest { NaturalLanguageQuery = "food", Region = new MKCoordinateRegion(new CLLocationCoordinate2D(location.Coordinate.Latitude, location.Coordinate.Longitude), new MKCoordinateSpan(0.3f, 0.3f)) }; var localSearch = new MKLocalSearch(searchRequest); var localSearchResponse = await localSearch.StartAsync(); if(localSearchResponse.MapItems != null && localSearchResponse.MapItems.Length > 0) { var mapItem = localSearchResponse.MapItems[0]; restaurant = mapItem.Name; } } catch(Exception ex) { //Console.WriteLine("Error searching restaurants: " + ex); } return restaurant; }
public void QueryForRecords (CLLocation location, Action<List<CKRecord>> completionHandler) { var radiusInKilometers = NSNumber.FromFloat (5f); var predicate = NSPredicate.FromFormat ("distanceToLocation:fromLocation:(location, %@) < %f", new NSObject[] { location, radiusInKilometers }); var query = new CKQuery (ItemRecordType, predicate) { SortDescriptors = new [] { new NSSortDescriptor ("creationDate", false) } }; var queryOperation = new CKQueryOperation (query) { DesiredKeys = new [] { NameField } }; var results = new List<CKRecord> (); queryOperation.RecordFetched = (record) => results.Add (record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine ("An error occured: {0}", error.Description); return; } DispatchQueue.MainQueue.DispatchAsync (() => completionHandler (results)); }; publicDatabase.AddOperation (queryOperation); }
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { _helper.Locations.Add (newLocation); if (_helper.LocationAdded != null) _helper.LocationAdded (_helper, new LocationEventArgs (newLocation)); }
public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); viewIsDisplayed = true; var region = LocationTriggerCreator.TargetRegion; if (region != null) { var centerLocation = new CLLocation (region.Center.Latitude, region.Center.Longitude); geocoder.ReverseGeocodeLocation (centerLocation, (placemarks, error) => { // The geocoder took too long, we're not on this view any more. if (!viewIsDisplayed) return; if (error != null) { DisplayError (error); return; } if (placemarks != null) { var mostLikelyPlacemark = placemarks.FirstOrDefault (); if (mostLikelyPlacemark != null) { CNMutablePostalAddress address = CreatePostalAddress (mostLikelyPlacemark); var addressFormatter = new CNPostalAddressFormatter (); string addressString = addressFormatter.GetStringFromPostalAddress (address); localizedAddress = addressString.Replace ("\n", ", "); var section = NSIndexSet.FromIndex (2); TableView.ReloadSections (section, UITableViewRowAnimation.Automatic); } } }); } TableView.ReloadData (); }
public override void LocationsUpdated(CLLocationManager manager, CLLocation[] locations) { Task.Run (async () => {await AppDelegate.FlicService.RefreshPendingConnections();}); foreach(var loc in locations) { Console.WriteLine(loc); } }
public static JsonArray GetPoiInformation(CLLocation userLocation, int numberOfPlaces) { if (userLocation == null) return null; var pois = new List<JsonObject> (); for (int i = 0; i < numberOfPlaces; i++) { var loc = GetRandomLatLonNearby (userLocation.Coordinate.Latitude, userLocation.Coordinate.Longitude); var p = new Dictionary<string, JsonValue>(){ { "id", i.ToString() }, { "name", "POI#" + i.ToString() }, { "description", "This is the description of POI#" + i.ToString() }, { "latitude", loc[0] }, { "longitude", loc[1] }, { "altitude", 100f } }; pois.Add (new JsonObject (p.ToList())); } var vals = from p in pois select (JsonValue)p; return new JsonArray (vals); }
public static double LatitudeRangeForLocation(CLLocation aLocation) { const double M = 6367000.0; const double metersToLatitude = 1.0/((Math.PI/180.0d)*M); const double accuracyToWindowScale = 2.0; return aLocation.HorizontalAccuracy*metersToLatitude*accuracyToWindowScale; }
async partial void SaveRecord (MonoTouch.UIKit.UIButton sender) { if (nameTextField.Text.Length < 1) { nameTextField.ResignFirstResponder (); return; } var saveLocation = new CLLocation (pin.Coordinate.Latitude, pin.Coordinate.Longitude); var record = await CloudManager.AddRecordAsync (nameTextField.Text, saveLocation); if (record == null) { Console.WriteLine ("Error: null returned on save"); return; } nameTextField.Text = string.Empty; nameTextField.ResignFirstResponder (); var alert = UIAlertController.Create ("CloudKitAtlas", "Saved record", UIAlertControllerStyle.Alert); alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (act) => { DismissViewController (true, null); })); PresentViewController (alert, true, null); }
public void LocationManagerDidUpdateToLocationFromLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { // Ignore updates where nothing we care about changed if (oldLocation != null && newLocation.Coordinate.longitude == oldLocation.Coordinate.longitude && newLocation.Coordinate.latitude == oldLocation.Coordinate.latitude && newLocation.HorizontalAccuracy == oldLocation.HorizontalAccuracy) { return; } // Load the HTML for displaying the Google map from a file and replace the // format placeholders with our location data NSError error; NSString htmlString = NSString.StringWithFormat( NSString.StringWithContentsOfFileEncodingError( NSBundle.MainBundle.PathForResourceOfType("HTMLFormatString", @"html"), NSStringEncoding.NSUTF8StringEncoding,out error), newLocation.Coordinate.latitude, newLocation.Coordinate.longitude, LatitudeRangeForLocation(newLocation), LongitudeRangeForLocation(newLocation)); // Load the HTML in the WebView and set the labels this.webView.MainFrame.LoadHTMLStringBaseURL(htmlString, null); this.locationLabel.StringValue = NSString.StringWithFormat("%f, %f", newLocation.Coordinate.latitude, newLocation.Coordinate.longitude); this.accuracyLabel.StringValue = NSString.StringWithFormat("%f", newLocation.HorizontalAccuracy); }
public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); var what = new EntryElement ("What ?", "e.g. pizza", String.Empty); var where = new EntryElement ("Where ?", "here", String.Empty); var section = new Section (); if (CLLocationManager.LocationServicesEnabled) { lm = new CLLocationManager (); lm.LocationsUpdated += delegate (object sender, CLLocationsUpdatedEventArgs e) { lm.StopUpdatingLocation (); here = e.Locations [e.Locations.Length - 1]; var coord = here.Coordinate; where.Value = String.Format ("{0:F4}, {1:F4}", coord.Longitude, coord.Latitude); }; section.Add (new StringElement ("Get Current Location", delegate { lm.StartUpdatingLocation (); })); } section.Add (new StringElement ("Search...", async delegate { await SearchAsync (what.Value, where.Value); })); var root = new RootElement ("MapKit Search Sample") { new Section ("MapKit Search Sample") { what, where }, section }; window.RootViewController = new UINavigationController (new DialogViewController (root, true)); window.MakeKeyAndVisible (); return true; }
// constructor from CoreLocation location internal Geoposition(CLLocation location) { Coordinate = new Geocoordinate(); if (location != null) { Coordinate.Point = new Geopoint(new BasicGeoposition() { Latitude = location.Coordinate.Latitude, Longitude = location.Coordinate.Longitude, Altitude = location.Altitude }); Coordinate.Accuracy = location.HorizontalAccuracy; if (!double.IsNaN(location.VerticalAccuracy)) { Coordinate.AltitudeAccuracy = location.VerticalAccuracy; } #if __IOS__ || __MAC__ if (!double.IsNaN(location.Course) && location.Course != -1) { Coordinate.Heading = location.Course; } if (!double.IsNaN(location.Speed) && location.Speed != -1) { Coordinate.Speed = location.Speed; } #endif Coordinate.Timestamp = InTheHand.DateTimeOffsetHelper.FromNSDate(location.Timestamp); } }
public static void UpdateLocation(GPSLocate ms, CLLocation newLocation) { ms.LblAltitude.Text = newLocation.Altitude.ToString () + " meters"; ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString () + "º"; ms.LblLatitude.Text = newLocation.Coordinate.Latitude.ToString () + "º"; ms.LblCourse.Text = newLocation.Course.ToString () + "º"; ms.LblSpeed.Text = newLocation.Speed.ToString () + " meters/s"; // get the distance from here to paris ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km"; var x1 =Convert.ToDouble( "40.023408"); var y1 =Convert.ToDouble( "40.643127"); var x2 =Convert.ToDouble( "30.753657"); var y2 = Convert.ToDouble("30.038635"); var longdute =newLocation.Coordinate.Longitude; var latidute = newLocation.Coordinate.Latitude; ms.checkIt.Clicked+= (sender, e) => { if (longdute > x2 && longdute < x1 && latidute > y2 && latidute < y1) new UIAlertView("Ankara Dışındasın", "Konum : " + longdute + " " + latidute, null, "OK", null).Show(); else new UIAlertView("Ankara İçerisindesin", "Konum : " + longdute + " " + latidute, null, "OK", null).Show(); }; }
double latitudeRangeForLocation(CLLocation location) { const double M = 6367000.0; // approximate average meridional radius of curvature of earth const double metersToLatitude = 1.0 / ((Math.PI / 180.0) * M); const double accuracyToWindowScale = 2.0; return location.HorizontalAccuracy * metersToLatitude * accuracyToWindowScale; }
public async Task<CKRecord> AddRecordAsync (string name, CLLocation location) { var newRecord = new CKRecord (ItemRecordType); newRecord [NameField] = (NSString)name; newRecord [LocationField] = location; return await publicDatabase.SaveRecordAsync (newRecord); }
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { Console.WriteLine ("New location data = {0}", newLocation.Description ()); _helper.Locations.Add (newLocation); if (_helper.LocationAdded != null) _helper.LocationAdded (_helper, new EventArgs ()); }
partial void QueryRecords (UIBarButtonItem sender) { var queryLocation = new CLLocation (pin.Coordinate.Latitude, pin.Coordinate.Longitude); CloudManager.QueryForRecords (queryLocation, records => { results = records; TableView.ReloadData (); }); }
public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { Console.WriteLine("{0},{1}", newLocation.Coordinate.Latitude, newLocation.Coordinate.Longitude); if ((DateTime.Now - ((DateTime)newLocation.Timestamp)) > TimeSpan.FromMinutes(3)) { return; } reallyFoundLocation(newLocation); }
// called for iOS6 and later public override void LocationsUpdated (CLLocationManager manager, CLLocation[] locations) { CLLocation currentLocation = locations [0]; MApplication.getInstance ().latitude = currentLocation.Coordinate.Latitude; MApplication.getInstance ().longitude = currentLocation.Coordinate.Longitude; #if DEBUG Console.Out.WriteLine ("LocationsUpdated : ( {0} , {1})", MApplication.getInstance ().latitude,MApplication.getInstance ().longitude); #endif }
/// <summary> /// There was a significant location change /// </summary> /// <param name='newLoc'> /// New location. /// </param> private void locationChanged(CLLocation newLoc) { if (!UserPreferences.PreferCurrentLocation) { return; } // var allStops = BusDB_GTFS_SQL.Instance.getAllBusStops (); // allStops = allStops.OrderBy (stop => stop.location, new LocationComparer (newLoc)); // var closest = ((BusStop)allStops.First ()); // DisplayedStop = closest as BusStop?; // UserPreferences.DefaultStopId = closest.stopId;//update the default stop (careful about loops!) UserPreferences.DefaultStopId = BusDB_GTFS_SQL.Instance.getClosestStop(newLoc).Value.stopId; }
static public void UpdateLocation (CLLocation newLocation, CLLocationManager locManager, GetLocationActions locActions, UITextField textField) { Console.WriteLine(newLocation.Coordinate.Longitude.ToString () + "º"); Console.WriteLine(newLocation.Coordinate.Latitude.ToString () + "º"); //FireEvent OnLocationChanged (textField, locActions, newLocation.Coordinate.Latitude.ToString (), newLocation.Coordinate.Longitude.ToString ()); if (CLLocationManager.LocationServicesEnabled) locManager.StopUpdatingLocation (); if (CLLocationManager.HeadingAvailable) locManager.StopUpdatingHeading (); }
public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { manager.Delegate = null; manager.StopUpdatingLocation(); var parameters = new Dictionary <string, string>() { { "Lat", newLocation.Coordinate.Latitude.ToString() }, { "Lon", newLocation.Coordinate.Longitude.ToString() } }; iApp.Navigate(callback, parameters); }
/*public override void DidEnterBackground (UIApplication application) * { * Console.WriteLine ("App entering background state."); * } * * public override void WillEnterForeground (UIApplication application) * { * Console.WriteLine ("App will enter foreground"); * }*/ public void StoreGPSLocation(CLLocation location) { if (location != null) { GPSLocationData locationData = new GPSLocationData(); locationData.Altitude = location.Altitude; locationData.Course = location.Course; locationData.Speed = location.Speed; locationData.Latitude = location.Coordinate.Latitude; locationData.Longitude = location.Coordinate.Longitude; this.userGPSLocationData.Add(locationData); } }
//This will keep going in the background and the foreground public void PrintLocation(object sender, LocationUpdatedEventArgs e) { CLLocation location = e.Location; Console.WriteLine("Altitude: " + location.Altitude + " meters"); Console.WriteLine("Longitude: " + location.Coordinate.Longitude); Console.WriteLine("Latitude: " + location.Coordinate.Latitude); Console.WriteLine("Course: " + location.Course); Console.WriteLine("Speed: " + location.Speed); latitude = location.Coordinate.Latitude; longitude = location.Coordinate.Longitude; }
//Caution: If radius is too large results will be HUGE! //radius in meters public IEnumerable<BusStop> getAllBusStops(CLLocation aboutLoc, double radius) { List<BusStop> stops = new List<BusStop>(30); using (LumenWorks.Framework.IO.Csv.CsvReader csv = new LumenWorks.Framework.IO.Csv.CsvReader(getReader("stops.txt"),true)) { while (csv.ReadNextRecord()){ CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"])); if (loc.DistanceFrom(aboutLoc)<=radius) stops.Add(new BusStop(csv["stop_name"],int.Parse(csv["stop_id"]), loc)); loc.Dispose(); } return stops; } }
public void HandleLocationChanged(object sender, LocationUpdatedEventArgs e) { // handle foreground updates CLLocation location = e.Location; LblAltitude.Text = location.Altitude + " meters"; LblLongitude.Text = location.Coordinate.Longitude.ToString(); LblLatitude.Text = location.Coordinate.Latitude.ToString(); LblCourse.Text = location.Course.ToString(); LblSpeed.Text = location.Speed.ToString(); Console.WriteLine("UI updated"); }
//returns if given sculpture location close enough to user location. public bool checkDistance(CLLocation sculpture, CLLocation current) { double meters = current.DistanceFrom(sculpture); if (meters <= 3) { return(true); } else { return(false); } }
void UpdateLocation(CLLocation location) { var region = new MKCoordinateRegion( location.Coordinate, new MKCoordinateSpan(1.0, 1.0) ); coordinates = location.Coordinate; if (!visited) { mapView.SetRegion(region, true); } }
/// <summary> /// Whenever the GPS sends a new location, update text in label /// and increment the 'count' of updates AND reset the map to that location /// </summary> public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { //MKCoordinateSpan span = new MKCoordinateSpan(0.2,0.2); //MKCoordinateRegion region = new MKCoordinateRegion(newLocation.Coordinate,span); //_appd.mylocation = newLocation; //_mapview.SetRegion(region, true); double distanceToConference = MapHelper.Distance(new Coordinate(_appd.MyLocation), new Coordinate(newLocation.Coordinate), UnitsOfLength.Miles); _appd.labelDistance.Text = String.Format("{0} miles from Hero's!", Math.Round(distanceToConference, 0)); Console.WriteLine("Distance: {0}", distanceToConference); //Console.WriteLine("Location updated"); }
private List <CLLocation> DecodePolyLine(string encoded) { var array = new List <CLLocation> { }; encoded = encoded.Replace(@"\\\\", @"\\"); int lat = 0; int lng = 0; int index = 0; while (index < encoded.Length) { int b; int shift = 0; int result = 0; do { b = encoded[index++] - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) == 1 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded[index++] - 63; result |= (b & 0x1f) << shift; shift += 5; }while (b >= 0x20); int dlng = ((result & 1) == 1 ? ~(result >> 1) : (result >> 1)); lng += dlng; double latitude = lat * 1e-5; double longitude = lng * 1e-5; Console.WriteLine("Latitude: {0}", latitude); Console.WriteLine("Longitude: {0}", longitude); var location = new CLLocation(latitude, longitude); array.Add(location); } return(array); }
public async Task <GeoLocation> GetCurrentLocation() { // must manually request authorization post iOS 8 if (_is8orGreater) { if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) { _authorizationChanged = new TaskCompletionSource <object> (); _locMgr.RequestWhenInUseAuthorization(); await _authorizationChanged.Task; } } if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.Status == CLAuthorizationStatus.Authorized) { _locationRecieved = new TaskCompletionSource <CLLocation> (); _locMgr.StartUpdatingLocation(); CLLocation loc = await _locationRecieved.Task.TimeoutAfter(1000); return(loc == null ? null : new GeoLocation(loc.Coordinate.Latitude, loc.Coordinate.Longitude)); } // will get prompted at this point in pre iOS 8 else if (!_is8orGreater && CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) { _authorizationChanged = new TaskCompletionSource <object> (); _locMgr.StartUpdatingLocation(); await _authorizationChanged.Task; if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.Status == CLAuthorizationStatus.Authorized) { _locationRecieved = new TaskCompletionSource <CLLocation> (); CLLocation loc = await _locationRecieved.Task.TimeoutAfter(1000); return(loc == null ? null : new GeoLocation(loc.Coordinate.Latitude, loc.Coordinate.Longitude)); } } return(null); }
public void DidUpdateUserLocation(MKMapView mapView, MKUserLocation userLocation) { if (userLocation != null) { Console.WriteLine("location: " + userLocation.Coordinate.Latitude + " " + userLocation.Coordinate.Longitude); if (!ViewModel.IsNavigating || !ViewModel.HasStaredNavigation) { return; } if (currentStepIndex < ViewModel.Routes.Count - 1) { RouteItem nextItem = ViewModel.Routes [currentStepIndex + 1]; CLLocation nexLocation = new CLLocation(nextItem.Lat, nextItem.Long); double distanceToNext = userLocation.Location.DistanceFrom(nexLocation); Console.WriteLine("distance to next steps " + distanceToNext); RouteItem currentItem = ViewModel.Routes [currentStepIndex]; CLLocation currentLocation = new CLLocation(currentItem.Lat, currentItem.Long); double distanceToCurrent = userLocation.Location.DistanceFrom(currentLocation); double distanceCurrentToNext = nexLocation.DistanceFrom(currentLocation); if (distanceToNext < distanceCurrentToNext && distanceToCurrent > 5 && distanceToNext < 100) { Console.WriteLine("move to next steps"); collectionRoutes.SetContentOffset(new CGPoint(collectionRoutes.Frame.Width * (currentStepIndex + 1), 0), true); DrawStepForIndex(currentStepIndex + 1, false); } else if (currentStepIndex > 0) { RouteItem prevItem = ViewModel.Routes [currentStepIndex - 1]; CLLocation prevLocation = new CLLocation(prevItem.Lat, prevItem.Long); double distanceToPrev = userLocation.Location.DistanceFrom(prevLocation); double distancePrevToCurrent = prevLocation.DistanceFrom(currentLocation); if (distanceToPrev < 5 && distanceToCurrent > distancePrevToCurrent) { // user go back to prev step collectionRoutes.SetContentOffset(new CGPoint(collectionRoutes.Frame.Width * (currentStepIndex - 1), 0), true); DrawStepForIndex(currentStepIndex - 1, false); } } } } }
//Metodo de busqueda de la tienda mas cercana. public ProductSearchDetailService nearestStore(CLLocation location, List <ProductSearchDetailService> stores) { Console.WriteLine("" + location.Coordinate.Latitude); ProductSearchDetailService nearStore = stores.ElementAt(0); foreach (ProductSearchDetailService store in stores) { if ((location.DistanceFrom(new CLLocation(Double.Parse(store.tienda_latitud), Double.Parse(store.tienda_longitud)))) < (location.DistanceFrom(new CLLocation(Double.Parse(nearStore.tienda_latitud), Double.Parse(nearStore.tienda_longitud))))) { nearStore = store; } } return(nearStore); }
// iOS 9 <=, fire when recieve notification foreground public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler) { Messaging.SharedInstance.AppDidReceiveMessage(userInfo); // Generate custom event NSString[] keys = { new NSString("Event_type") }; NSObject[] values = { new NSString("Recieve_Notification") }; var parameters = NSDictionary <NSString, NSObject> .FromObjectsAndKeys(keys, values, keys.Length); // Send custom event //Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters); if (application.ApplicationState == UIApplicationState.Active) { var aps_d = userInfo["aps"] as NSDictionary; var alert_d = aps_d["alert"] as NSDictionary; try { NSNumberFormatter formatter = new NSNumberFormatter { NumberStyle = NSNumberFormatterStyle.Decimal }; var mLat = userInfo["lat"] as NSString; var mLng = userInfo["lng"] as NSString; //NSNumber lat = (formatter.NumberFromString(mLat)); //NSNumber lng = (formatter.NumberFromString(mLng)); double lat = Convert.ToDouble(mLat); double lng = Convert.ToDouble(mLng); CLLocation notifLoc = new CLLocation(lat, lng); var distance = notifLoc.DistanceFrom(curLocation); Console.WriteLine($"Distance: {distance}"); //Console.WriteLine($"lat: {lat}, lng:{lng}"); } catch (NullReferenceException e) { //TODO: log this maybe? Console.WriteLine(e); } try { var body = alert_d["body"] as NSString; var title = alert_d["title"] as NSString; DebugAlert(title, body); } catch (NullReferenceException) { //TODO: here? } } completionHandler(UIBackgroundFetchResult.NewData); }
public BusStop? getClosestStop(CLLocation aboutLoc) { int closestId = -1; double closestDist=double.MaxValue; using (CsvReader csv = new CsvReader(getReader("stops.txt"),true)) { while (csv.ReadNextRecord()){ CLLocation loc = new CLLocation(double.Parse(csv["stop_lat"]), double.Parse(csv["stop_lon"])); if (loc.DistanceFrom(aboutLoc)<=closestDist) closestId=int.Parse(csv["stop_id"]); loc.Dispose(); } } return (closestId==-1)?null:getStopInfo(closestId); }
internal static Location ToLocation(this CLLocation location) => new Location { Latitude = location.Coordinate.Latitude, Longitude = location.Coordinate.Longitude, Altitude = location.VerticalAccuracy < 0 ? default(double?) : location.Altitude, Accuracy = location.HorizontalAccuracy, Timestamp = location.Timestamp.ToDateTime(), #if __iOS__ || __WATCHOS__ Course = location.Course < 0 ? default(double?) : location.Course, Speed = location.Speed < 0 ? default(double?) : location.Speed, #endif IsFromMockProvider = DeviceInfo.DeviceType == DeviceType.Virtual };
// extract CLLocation from dict public CLLocation GetLocationFrom(Dictionary <string, object> dict) { CLLocation location = null; var loc = dict["location"] as Dictionary <string, double>; if (loc != null) { var lat = loc["lat"] as double?; var lng = loc["lng"] as double?; location = new CLLocation(lat.Value, lng.Value); } return(location); }
static Task<IEnumerable<string>> GetAddressesForPositionAsync(Position position) { var location = new CLLocation(position.Latitude, position.Longitude); var geocoder = new CLGeocoder(); var source = new TaskCompletionSource<IEnumerable<string>>(); geocoder.ReverseGeocodeLocation(location, (placemarks, error) => { if (placemarks == null) placemarks = new CLPlacemark[0]; IEnumerable<string> addresses = placemarks.Select(p => ABAddressFormatting.ToString(p.AddressDictionary, false)); source.SetResult(addresses); }); return source.Task; }
/// <summary> /// Convert iOS location to Geo Location that we are using in the library. /// </summary> private Geolocation ConvertLocationToGeolocation(CLLocation location) { return(new Geolocation() { Coordinate = new Geocoordinate() { Latitude = location.Coordinate.Latitude, Longitude = location.Coordinate.Longitude, Altitude = location.Altitude, Accuracy = (location.HorizontalAccuracy + location.VerticalAccuracy) / 2 }, UpdateDateTime = ConvertLocationTimeToDateTime(location.Timestamp) }); }
public override void ViewDidLoad() { base.ViewDidLoad(); var geocoder = new CLGeocoder(); locationManager = new CLLocationManager(); locationManager.RequestWhenInUseAuthorization(); //locationManager.RequestLocation(); // Only should be called once locationMap.ShowsUserLocation = true; MKCoordinateRegion region; MKCoordinateSpan span; region.Center = locationMap.UserLocation.Coordinate; span.LatitudeDelta = 0.005; span.LongitudeDelta = 0.005; region.Span = span; locationMap.SetRegion(region, true); locationMap.MapType = MKMapType.Standard; var searchResultsController = new chooseLocationResultViewController(locationMap); var searchUpdater = new SearchResultsUpdator(); searchUpdater.UpdateSearchResults += searchResultsController.Search; //add the search controller searchController = new UISearchController(searchResultsController) { SearchResultsUpdater = searchUpdater }; searchController.SearchBar.SizeToFit(); searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Prominent; searchController.SearchBar.Placeholder = "Enter a search query"; searchController.HidesNavigationBarDuringPresentation = false; NavigationItem.TitleView = searchController.SearchBar; DefinesPresentationContext = true; // When the user wants to choose the location manually locationMap.RegionChanged += (sender, e) => { if (setLocation == true) { var coordinate = locationMap.CenterCoordinate; var coor = new CLLocation(coordinate.Latitude, coordinate.Longitude); geocoder.ReverseGeocodeLocation(coor, HandleCLGeocodeCompletionHandler); } }; }
private static MvxGeoLocation CreateLocation(CLLocation location) { var position = new MvxGeoLocation {Timestamp = location.Timestamp.ToDateTimeUtc()}; var coords = position.Coordinates; coords.Altitude = location.Altitude; coords.Latitude = location.Coordinate.Latitude; coords.Longitude = location.Coordinate.Longitude; coords.Speed = location.Speed; coords.Accuracy = location.HorizontalAccuracy; coords.AltitudeAccuracy = location.VerticalAccuracy; return position; }
public override void ViewDidLoad() { base.ViewDidLoad(); RouteViews = new Dictionary <string, CSRouteView>(); // load the points from local resource (file) var filePath = NSBundle.MainBundle.PathForResource("route", "csv", "MapLineSharp", ""); var fileContents = System.IO.File.ReadAllText(filePath); var pointStrings = fileContents.Split('\n'); var points = new List <CLLocation>(); foreach (var ps in pointStrings) { // break the string down into latitude and longitude fields var latLonArr = ps.Split(','); double latitude = Convert.ToDouble(latLonArr[0]); double longitude = Convert.ToDouble(latLonArr[1]); CLLocation currentLocation = new CLLocation(latitude, longitude); points.Add(currentLocation); } // // Create our map view and add it as as subview. // _mapView = new MKMapView(); _mapView.Frame = new RectangleF(0, 0, this.View.Frame.Width, this.View.Frame.Height); View.AddSubview(_mapView); _mapView.Delegate = new MapViewDelegate(this); // CREATE THE ANNOTATIONS AND ADD THEM TO THE MAP // first create the route annotation CSRouteAnnotation routeAnnotation = new CSRouteAnnotation(points); _mapView.AddAnnotation(routeAnnotation); CSMapAnnotation annotation = null; annotation = new CSMapAnnotation(points[0].Coordinate, CSMapAnnotationType.Start, "Start Point"); _mapView.AddAnnotation(annotation); annotation = new CSMapAnnotation(points[points.Count - 1].Coordinate, CSMapAnnotationType.End, "End Point"); _mapView.AddAnnotation(annotation); //TODO:create the image annotation _mapView.SetRegion(routeAnnotation.Region, false); }
public override void Draw(RectangleF rect) { CSRouteAnnotation routeAnnotation = RouteView.Annotation as CSRouteAnnotation; if (!this.Hidden && routeAnnotation.Points != null && routeAnnotation.Points.Count > 0) { CGContext context = UIGraphics.GetCurrentContext(); if (routeAnnotation.LineColor != null) { routeAnnotation.LineColor = UIColor.Blue; } context.SetStrokeColorWithColor(routeAnnotation.LineColor.CGColor); context.SetRGBFillColor(0.0f, 0.0f, 1.0f, 1.0f); // Draw them with a 2.0 stroke width so they are a bit more visible context.SetLineWidth(5.0f); context.SetAlpha(0.40f); for (int idx = 0; idx < routeAnnotation.Points.Count; idx++) { CLLocation location = routeAnnotation.Points[idx]; PointF point = RouteView.MapView.ConvertCoordinate(location.Coordinate, this); //Debug.WriteLine("Point: {0}, {1}", point.X, point.Y); if (idx == 0) { context.MoveTo(point.X, point.Y); } else { context.AddLineToPoint(point.X, point.Y); } } context.StrokePath(); // debug. Draw the line around our view. /* * CGContextMoveToPoint(context, 0, 0); * CGContextAddLineToPoint(context, 0, self.frame.size.height); * CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height); * CGContextAddLineToPoint(context, self.frame.size.width, 0); * CGContextAddLineToPoint(context, 0, 0); * CGContextStrokePath(context); */ } }
public string LocateLot() { CLLocation location = Manager.returnLocation(); if (location == null) { location = new CLLocation(30.272249, -81.508828); } CLLocation lot14_1 = new CLLocation(30.268352, -81.513324); CLLocation lot14_2 = new CLLocation(30.269416, -81.513954); //Art Center Lots CLLocation lot1_1 = new CLLocation(30.267611, -81.508983); CLLocation lot1_2 = new CLLocation(30.266722, -81.508586); //Library Lot CLLocation lot2 = new CLLocation(30.268751, -81.509305); //Student Union Lot CLLocation lot4 = new CLLocation(30.272128, -81.508174); Dictionary <String, double> list = new Dictionary <String, double>(); var distanceToLot14_1 = location.DistanceFrom(lot14_1); list.Add("lot14_1", distanceToLot14_1); var distanceToLot14_2 = location.DistanceFrom(lot14_2); list.Add("lot14_2", distanceToLot14_2); var distanceToLot1_1 = location.DistanceFrom(lot1_1); list.Add("lot1_1", distanceToLot1_1); var distanceToLot1_2 = location.DistanceFrom(lot1_2); list.Add("lot1_2", distanceToLot1_2); var distanceToLot2 = location.DistanceFrom(lot2); list.Add("lot2_1", distanceToLot2); var distanceToLot4 = location.DistanceFrom(lot4); list.Add("lot4_1", distanceToLot4); var min = list.Aggregate((l, r) => l.Value < r.Value ? l : r); return(min.Key); }
public override void ViewDidLoad() { base.ViewDidLoad(); mUserTripDataManager = new UserTripDataManager(); mLocationManager = new CLLocationManager(); mLocationManager.DesiredAccuracy = 100; mLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { mCurrentLocationUpdateCounter++; EnableCurrentLocation(); CLLocation location = e.Locations[e.Locations.Length - 1]; mCurrentLocation = e.Locations[e.Locations.Length - 1].Coordinate; mCityString = ""; mStateString = ""; var geocoder = new CLGeocoder(); geocoder.ReverseGeocodeLocation(location, (CLPlacemark[] placemarks, NSError error) => { if ((placemarks != null) && (placemarks.Length > 0)) { mStateString = placemarks[0].AdministrativeArea; mCityString = placemarks[0].Locality; } }); if (mCurrentLocationUpdateCounter > 5) { mLocationManager.StopUpdatingLocation(); } }; txtStartLocation.ShouldReturn += (textField) => { txtEndLocation.BecomeFirstResponder(); return(true); }; txtEndLocation.ShouldReturn += (textField) => { textField.ResignFirstResponder(); return(true); }; setupConnectorView(); txtDate.Text = DateTime.Now.AddMinutes(5).ToString("g"); }
public static Position ToRxPosition(this CLLocation location) { return(new Position( coordinate: location.Coordinate.ToRxCoordinate(), accuracy: Accuracy.FromMeters(location.HorizontalAccuracy, location.VerticalAccuracy), altitide: new Distance(location.Altitude), timestamp: (DateTime)location.Timestamp )); IRxPosition provider = new iOSRxPosition(); provider.Position.Subscribe( onNext: pos => Console.WriteLine(pos.Coordinate.Latitude), onError: ex => Console.WriteLine("LocationServicesAccessDenied thrown, no access to location")); }
private void HandleLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e) { CLLocation location = e.Locations[e.Locations.Length - 1]; DateTime time = DateTime.SpecifyKind(location.Timestamp, DateTimeKind.Unspecified); var args = new LocationEventArgs(location.Coordinate.Latitude, location.Coordinate.Longitude, time, location.Speed, location.Course, 0, location.Altitude); OnLocationChanged(args); if (_interval != TimeSpan.Zero && _timer == null) { _manager.StopUpdatingLocation(); _timer = new Timer(TurnOnLocationManager, null, (int)_interval.TotalMilliseconds, 0); } }
public PhotoPostViewController (UINavigationController msp, UIImage image, CLLocation photoLocation, string locationMapPhotoCapture) : this() { this._image = image; this._MSP = msp; LocationMapPhotoCapture = locationMapPhotoCapture; PhotoLocation = photoLocation; // Add the views //NSNotificationCenter.DefaultCenter.AddObserver ("UIKeyboardWillShowNotification", KeyboardWillShow); this.root = CreateRoot (); }
public PhotoPostViewController (UINavigationController msp, UIImage image, Tweet tweet) : this() { this._image = image; this._MSP = msp; this.eventImage = tweet.Image; this.postOptions = tweet.Options; this.isForEvent = true; PhotoLocation = new CLLocation(eventImage.Latitude, eventImage.Longitude); this.root = CreateRoot (); Description.Value = eventImage.Name; Keywords.AddRange(tweet.Keywords); }
double DegreeBearing(CLLocation loc1, CLLocation loc2) { ; double fLat = ToRad(loc1.Coordinate.Latitude); double fLng = ToRad(loc1.Coordinate.Longitude); double tLat = ToRad(loc2.Coordinate.Latitude); double tLng = ToRad(loc2.Coordinate.Longitude); double dLon = tLng - fLng; double y = Math.Sin(dLon) * Math.Cos(tLat); double x = Math.Cos(fLat) * Math.Sin(tLat) - Math.Sin(fLat) * Math.Cos(tLat) * Math.Cos(dLon); double radian = Math.Atan2(y, x); return(radian); }
public void OnLocationChanged(object sender, LocationUpdatedEventArgs e) { // Handle foreground updates CLLocation location = e.Location; //LblAltitude.Text = location.Altitude + " meters"; LatLabel.Text = location.Coordinate.Latitude.ToString(); LonLabel.Text = location.Coordinate.Longitude.ToString(); LastSentLabel.Text = Manager.GetLastLocationString(); //LblCourse.Text = location.Course.ToString(); //LblSpeed.Text = location.Speed.ToString(); //Console.WriteLine("foreground updated"); }
/// <summary> /// Whenever the GPS sends a new location, update text in label /// and increment the 'count' of updates AND reset the map to that location /// </summary> public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { //MKCoordinateSpan span = new MKCoordinateSpan(0.2,0.2); //MKCoordinateRegion region = new MKCoordinateRegion(newLocation.Coordinate,span); //_appd.mylocation = newLocation; //_mapview.SetRegion(region, true); double distanceToConference = MapHelper.Distance(new Coordinate(_appd.ConferenceLocation), new Coordinate(newLocation.Coordinate), UnitsOfLength.Miles); _appd.labelDistance.TextAlignment = UITextAlignment.Center; _appd.labelDistance.Text = String.Format("{0} miles from Monospace!", Math.Round(distanceToConference, 0)); Debug.WriteLine("Distance: {0}", distanceToConference); // only use the first result manager.StopUpdatingLocation(); }
void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e) { currentLocation = e.Locations.LastOrDefault (); if (pin != null) return; pin = new MKPointAnnotation (); pin.SetCoordinate (currentLocation.Coordinate); map.AddAnnotation (pin); map.ShowAnnotations (new [] { pin }, false); locationManager.StopUpdatingLocation (); }
public void DidUpdateLocation(CLLocation clLoc) { Location loc = new Location() { Speed = clLoc.Speed, Altitude = clLoc.Altitude, Longitude = clLoc.Coordinate.Longitude, Latitude = clLoc.Coordinate.Latitude, Orientation = clLoc.Course, Utc = DateTime.UtcNow, Accuracy = clLoc.HorizontalAccuracy }; OnLocationUpdate(loc); }
private static MvxGeoLocation CreateLocation(CLLocation location) { var position = new MvxGeoLocation { Timestamp = location.Timestamp.ToDateTimeUtc() }; var coords = position.Coordinates; #warning should some of these coords fields be nullable? coords.Altitude = location.Altitude; coords.Latitude = location.Coordinate.Latitude; coords.Longitude = location.Coordinate.Longitude; coords.Speed = location.Speed; coords.Accuracy = location.HorizontalAccuracy; coords.AltitudeAccuracy = location.VerticalAccuracy; return position; }
private void LocationUpdated(object sender, CLLocationsUpdatedEventArgs e) { if (arrived) { return; } if (!(e?.Locations?.Length > 0)) { Console.WriteLine("No locations"); return; } CLLocation lastLoc = e.Locations[e.Locations.Length - 1]; lastDistance = (float)lastLoc.DistanceFrom(new CLLocation(target.Lat, target.Long)); string distanceString = "Arrived!"; if (lastDistance >= 1000) { distanceString = string.Format("{0} km", (lastDistance / 1000).ToString("N2")); } else if (lastDistance >= 10) { distanceString = string.Format("{0} metres", lastDistance.ToString("N0")); } DistanceLabel.Text = distanceString; AccuracyLabel.Text = string.Format("Accuracy: within {0} metres", (lastLoc.HorizontalAccuracy * 2).ToString("N0")); if (!startedAnim) { startedAnim = true; Animate(); } if (lastDistance < 10) { arrived = true; locationManager.StopUpdatingLocation(); AppUtils.ShowSimpleDialog( this, "Finished!", "You\'ve arrived at the destination!", "Got it", (act) => { ReturnWithData(true.ToString()); }); } }
void handleLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e) { Log("handleLocationsUpdated"); ClLocationManager.LocationsUpdated -= handleLocationsUpdated; ClLocationManager.StopUpdatingLocation(); Log("StopUpdatingLocation"); // If it's a relatively recent event, turn off updates to save power. var location = e.Locations.LastOrDefault(); if (location != null) { var timestamp = location.Timestamp.ToDateTime(); var timedelta = DateTime.UtcNow.Subtract(timestamp); var timeDeltaSeconds = Math.Abs(timedelta.TotalSeconds); Log($"Location is {Math.Abs (timedelta.TotalSeconds)} seconds old"); // location was retrieved less than 15 seconds ago if (timeDeltaSeconds < 15) { Location = location; if (!ClLocationTcs.TrySetResult(location)) { Log("ClLocationTcs Failed to Set Result"); } else { Log("ClLocationTcs Set Result"); } } else { Log($"Location was too old: ({timedelta})"); ClLocationManager.LocationsUpdated += handleLocationsUpdated; ClLocationManager.StartUpdatingLocation(); Log("StartUpdatingLocation"); } } }
public override void ViewDidLoad() { base.ViewDidLoad (); RouteViews = new Dictionary<string,CSRouteView>(); // load the points from local resource (file) var filePath = NSBundle.MainBundle.PathForResource("route", "csv", "MapLineSharp",""); var fileContents = System.IO.File.ReadAllText(filePath); var pointStrings = fileContents.Split('\n'); var points = new List<CLLocation>(); foreach (var ps in pointStrings) { // break the string down into latitude and longitude fields var latLonArr = ps.Split(','); double latitude = Convert.ToDouble(latLonArr[0]); double longitude = Convert.ToDouble(latLonArr[1]); CLLocation currentLocation = new CLLocation(latitude, longitude); points.Add(currentLocation); } // // Create our map view and add it as as subview. // _mapView = new MKMapView(); _mapView.Frame = new RectangleF (0, 0, this.View.Frame.Width, this.View.Frame.Height); View.AddSubview(_mapView); _mapView.Delegate = new MapViewDelegate(this); // CREATE THE ANNOTATIONS AND ADD THEM TO THE MAP // first create the route annotation CSRouteAnnotation routeAnnotation = new CSRouteAnnotation(points); _mapView.AddAnnotation(routeAnnotation); CSMapAnnotation annotation = null; annotation = new CSMapAnnotation (points[0].Coordinate, CSMapAnnotationType.Start, "Start Point"); _mapView.AddAnnotation (annotation); annotation = new CSMapAnnotation (points[points.Count - 1].Coordinate, CSMapAnnotationType.End, "End Point"); _mapView.AddAnnotation (annotation); //TODO:create the image annotation _mapView.SetRegion (routeAnnotation.Region, false); }
internal Position ToPosition(CLLocation location) { DateTime time = (new DateTime(2001, 1, 1, 0, 0, 0)).AddSeconds(location.Timestamp.SecondsSinceReferenceDate); //TODO Review -> DateTime time = DateTime.SpecifyKind(location.Timestamp, DateTimeKind.Unspecified); return new Position() { Accuracy = location.HorizontalAccuracy, Altitude = location.Altitude, AltitudeAccuracy = location.VerticalAccuracy, Heading = location.Course, Latitude = location.Coordinate.Latitude, Longitude = location.Coordinate.Longitude, Speed = location.Speed, Timestamp = time }; }
// Method is called whenever there is a change in location public void locationUpdated(CLLocationsUpdatedEventArgs e) { // Create our Location Coordinates var coords = new Coordinates(); // Get a list of our locations found var locations = e.Locations; // Extract our Latitude and Longitude values from our locations array coords.latitude = locations[locations.Length - 1].Coordinate.Latitude; coords.longitude = locations[locations.Length - 1].Coordinate.Longitude; // Then, convert both our Latitude and Longitude values to a CLLocation object. newLocation = new CLLocation(coords.latitude, coords.longitude); MyLocation(this, coords); }
public override void ViewDidAppear (bool animated) { double lat, lng; if(string.IsNullOrEmpty(Longitude)){ if (CLLocationManager.LocationServicesEnabled){ locationManager.StartUpdatingLocation(); SetInfo(Utils.Translate("localizingposition")); } else MessageBox.Show(Utils.Translate("error_nogps"), Utils.Translate("error_nogps_details")); } else if(double.TryParse(Latitude, out lat) && double.TryParse(Longitude, out lng)) { CLLocation loc = new CLLocation(lat, lng); locationManagerDelegate.SetLocation(loc, Title, Utils.Translate("pin_dragtochange")); } base.ViewDidAppear (animated); }