예제 #1
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            locMan = new CLLocationManager();
            locMan.RequestWhenInUseAuthorization();
            locMan.RequestAlwaysAuthorization();
            // Geocode a city to get a CLCircularRegion,
            // and then use our location manager to set up a geofence
            button.TouchUpInside += (o, e) => {
                // clean up monitoring of old region so they don't pile up
                if (region != null)
                {
                    locMan.StopMonitoring(region);
                }

                // Geocode city location to create a CLCircularRegion - what we need for geofencing!
                var taskCoding = geocoder.GeocodeAddressAsync("Cupertino");
                taskCoding.ContinueWith((addresses) => {
                    CLPlacemark placemark = addresses.Result [0];
                    region = (CLCircularRegion)placemark.Region;
                    locMan.StartMonitoring(region);
                });
            };


            // This gets called even when the app is in the background - try it!
            locMan.RegionEntered += (sender, e) => {
                Console.WriteLine("You've entered the region");
            };

            locMan.RegionLeft += (sender, e) => {
                Console.WriteLine("You've left the region");
            };
        }
        async Task AddPins()
        {
            b_SearchButton.Enabled = false;
            for (int i = 0; i < AppDelegate.allStores.Count; i++)
            {
                t_SearchNavBarText.Title = i + "";
                Store store = AppDelegate.allStores[i];
                try
                {
                    CLPlacemark[] placemarks = await geoCoder.GeocodeAddressAsync(store.Address + " " + store.City);

                    store.Lon = placemarks[0].Location.Coordinate.Longitude;
                    store.Lat = placemarks[0].Location.Coordinate.Latitude;

                    m_SearchMap.AddAnnotations(new MKPointAnnotation()
                    {
                        Title      = store.Producer,
                        Coordinate = new CLLocationCoordinate2D(placemarks[0].Location.Coordinate.Latitude, placemarks[0].Location.Coordinate.Longitude)
                    });
                }
                catch
                {
                }
            }
            b_SearchButton.Enabled = true;
        }
        private async void OnSearchButtonClicked(string text)
        {
            searchBar.ResignFirstResponder();
            SearchCityIndicator.StartAnimating();

            try
            {
                var geocoder       = new CLGeocoder();
                var placemarkArray = await geocoder.GeocodeAddressAsync(searchBar.Text);

                if (placemarkArray.Length > 0)
                {
                    var firstPosition     = placemarkArray[0];
                    var locationLatitude  = firstPosition.Location.Coordinate.Latitude;
                    var locationLongitude = firstPosition.Location.Coordinate.Longitude;
                    var locationName      = firstPosition.Name;
                    if (!string.IsNullOrEmpty(locationName))
                    {
                        if (UserSettings.IsFavoriteAlreadyInList(locationName))
                        {
                            //Display Alert
                            var okAlertController = UIAlertController.Create("City Name",
                                                                             "is already in List.", UIAlertControllerStyle.Alert);
                            okAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                            PresentViewController(okAlertController, true, null);
                        }
                        else
                        {
                            var loc = new Location
                            {
                                name      = locationName,
                                latitude  = locationLatitude,
                                longitude = locationLongitude
                            };

                            InvokeOnMainThread(() =>
                            {
                                favorites.Add(loc);
                                UserSettings.SaveFavorites(favorites);

                                // update table view
                                AddLocationTableView.Source = new AddLocationTableViewSource(favorites, this);
                                AddLocationTableView.ReloadData();
                            });
                        }
                    }
                    searchBar.Text        = "";
                    searchBar.Placeholder = "Enter a City";
                }
            }
            catch (Exception ex)
            {
                //Display Alert
                var okAlertController = UIAlertController.Create("Could not find location",
                                                                 "Please try again", UIAlertControllerStyle.Alert);
                okAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                PresentViewController(okAlertController, true, null);
            }
            SearchCityIndicator.StopAnimating();
        }
        static async Task <CLLocationCoordinate2D?> FindCoordinates(NavigationAddress address)
        {
            CLPlacemark[] placemarks       = null;
            var           placemarkAddress =
                new MKPlacemarkAddress
            {
                City        = address.City.OrEmpty(),
                Country     = address.Country.OrEmpty(),
                CountryCode = address.CountryCode.OrEmpty(),
                State       = address.State.OrEmpty(),
                Street      = address.Street.OrEmpty(),
                Zip         = address.Zip.OrEmpty()
            };

            try
            {
                using (var coder = new CLGeocoder())
                    placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to obtain geo Location from address: " + ex);
            }

            var result = placemarks?.FirstOrDefault()?.Location?.Coordinate;

            if (result == null)
            {
                throw new Exception("Failed to obtain geo Location from address.");
            }

            return(result);
        }
예제 #5
0
        public async Task <Address[]> GetAddressesAsync(string addressString)
        {
            var geocoder   = new CLGeocoder();
            var placemarks = await geocoder.GeocodeAddressAsync(addressString);

            return(placemarks.Select(Convert).ToArray());
        }
예제 #6
0
        internal static async Task PlatformOpenMapsAsync(Placemark placemark, MapsLaunchOptions options)
        {
            var address = new MKPlacemarkAddress
            {
                CountryCode = placemark.CountryCode,
                Country     = placemark.CountryName,
                State       = placemark.AdminArea,
                Street      = placemark.Thoroughfare,
                City        = placemark.Locality,
                Zip         = placemark.PostalCode
            };

            var coder = new CLGeocoder();

            CLPlacemark[] placemarks = null;
            try
            {
                placemarks = await coder.GeocodeAddressAsync(address.Dictionary);
            }
            catch
            {
                Debug.WriteLine("Unable to get geocode address from address");
                return;
            }

            if ((placemarks?.Length ?? 0) == 0)
            {
                Debug.WriteLine("No locations exist, please check address.");
            }

            await OpenPlacemark(new MKPlacemark(placemarks[0].Location.Coordinate, address), options);
        }
예제 #7
0
        public static async Task <IEnumerable <Location> > GetLocationsAsync(string address)
        {
            using (var geocoder = new CLGeocoder())
            {
                var positionList = await geocoder.GeocodeAddressAsync(address);

                return(positionList?.ToLocations());
            }
        }
        async Task <List <Place> > Search()
        {
            while (completer.Searching)
            {
                await Task.Delay(50);
            }
            if (completer.Results == null || completer.Results.Length == 0)
            {
                return(new List <Place>());
            }

            var results = new List <Place>();

            foreach (var item in completer.Results)
            {
                var result = new Place();

                result.Name           = item.Title;
                result.Address        = item.Subtitle;
                result.HasCoordinates = false;
                result.Tag            = item;

                results.Add(result);
            }

            if (FetchCoordinates)
            {
                var geocoder = new CLGeocoder();
                foreach (var item in results)
                {
                    try
                    {
                        var placemarks = await geocoder.GeocodeAddressAsync(item.Address);

                        var placemark = placemarks.FirstOrDefault();
                        if (placemark != null)
                        {
                            //item.Name = placemark.Name;
                            if (placemark.Location != null)
                            {
                                item.HasCoordinates = true;
                                item.Latitude       = placemark.Location.Coordinate.Latitude;
                                item.Longitude      = placemark.Location.Coordinate.Longitude;
                            }
                            //if (placemark.PostalAddress != null)
                            //    item.Address = MapKitPlaces.GetAddress(placemark.PostalAddress);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return(results);
        }
예제 #9
0
        public async Task FromLocation(DeliveryAddress address)
        {
            //geocode address string
            var geocoder = new CLGeocoder();

            var placemark = await geocoder.GeocodeAddressAsync($"{address.Line1}, {address.City}, {address.State}");

            if (placemark.FirstOrDefault() is CLPlacemark topResult)
            {
                _coordinate = topResult.Location.Coordinate;
                _title      = "Delivery";
                _subtitle   = $"{address}";
            }
        }
예제 #10
0
        public IEnumerable <Address> ValidateAddress(string address)
        {
            var coder   = new CLGeocoder();
            var results = new List <Address>();

            var task = Task.Factory.StartNew(() => {
                CLPlacemark[] r = coder.GeocodeAddressAsync(address).Result;
                Console.WriteLine(string.Format("it ran! {0}", r.Length));
                results.AddRange(OnCompletion(r));
            });

            task.Wait(TimeSpan.FromSeconds(10));
            return(results);
        }
예제 #11
0
		public IEnumerable<Address> ValidateAddress (string address)
        {
            var coder = new CLGeocoder();
            var results = new List<Address>();

			var task = Task.Factory.StartNew (() => {
				CLPlacemark[] r = coder.GeocodeAddressAsync (address).Result;
				Console.WriteLine (string.Format ("it ran! {0}", r.Length));
				results.AddRange (OnCompletion (r));
			});

			task.Wait (TimeSpan.FromSeconds (10));
            return results;
        }
예제 #12
0
        async void GeocodeToConsoleAsync(string address)
        {
            try {
                var geoCoder   = new CLGeocoder();
                var placemarks = await geoCoder.GeocodeAddressAsync(address);

                foreach (var placemark in placemarks)
                {
                    Console.WriteLine($"{address} : {placemark.Location.Coordinate.ToString()}");
                }
            } catch {
                Console.WriteLine($"{address} : Not found");
            }
        }
        /// <summary>
        /// Retrieve positions for address.
        /// </summary>
        /// <param name="address">Desired address</param>
        /// <param name="mapKey">Map Key required only on UWP</param>
        /// <returns>Positions of the desired address</returns>
        public async Task<IEnumerable<Position>> GetPositionsForAddressAsync(string address, string mapKey = null)
        {
            if (address == null)
                throw new ArgumentNullException(nameof(address));

            using (var geocoder = new CLGeocoder())
            {
                var positionList = await geocoder.GeocodeAddressAsync(address);
                return positionList.Select(p => new Position
                {
                    Latitude = p.Location.Coordinate.Latitude,
                    Longitude = p.Location.Coordinate.Longitude
                });
            }
        }
예제 #14
0
        public IEnumerable<Address> ValidateAddress (string address)
        {
            var coder = new CLGeocoder();
            var results = new List<Address>();
            var task = Task.Factory.StartNew(async ()=>
                {
                    var r = await coder.GeocodeAddressAsync(address).ConfigureAwait(false);
                    Console.WriteLine("it ran!" + r.Length);
                    results.AddRange(OnCompletion(r));
                    reset.Set();
                });
            reset.WaitOne(TimeSpan.FromSeconds(10));
//            var task = await coder.GeocodeAddressAsync(address);
//            results = OnCompletion(task);
            return results;
        }
예제 #15
0
파일: Main.cs 프로젝트: antonioantunez7/UAQ
        static void inicializaGeolocalizacion()
        {
            /*Se crean las variables de geolocalizacion*/
            CLGeocoder geocoder = new CLGeocoder();
            //CLCircularRegion region;19.285116, -99.675914
            CLCircularRegion  region = new CLCircularRegion(new CLLocationCoordinate2D(+19.285116, -99.675914), 100129.46, "Casa de toño");//19.273600, -99.675620
            CLLocationManager locMan;

            /*Se crean las variables de geolocalizacion*/


            locMan = new CLLocationManager();
            locMan.RequestWhenInUseAuthorization();
            locMan.RequestAlwaysAuthorization();
            // Geocode a city to get a CLCircularRegion,
            // and then use our location manager to set up a geofence

            // clean up monitoring of old region so they don't pile up
            Console.Write("Soy la region");
            Console.Write(region);
            Console.Write("termino soy la region");
            if (region != null)
            {
                locMan.StopMonitoring(region);
            }

            // Geocode city location to create a CLCircularRegion - what we need for geofencing!
            var taskCoding = geocoder.GeocodeAddressAsync("Cupertino");

            taskCoding.ContinueWith((addresses) => {
                CLPlacemark placemark = addresses.Result[0];
                region = (CLCircularRegion)placemark.Region;
                Console.Write("\nInicio el monitoreo ..........");
                locMan.StartMonitoring(region);
                Console.Write("\nTermino el monitoreo ..........");
            });


            // This gets called even when the app is in the background - try it!
            locMan.RegionEntered += (sender, e) => {
                Console.WriteLine("You've entered the region");
            };

            locMan.RegionLeft += (sender, e) => {
                Console.WriteLine("You've left the region");
            };
        }
예제 #16
0
        public IEnumerable <Address> ValidateAddress(string address)
        {
            var coder   = new CLGeocoder();
            var results = new List <Address>();
            var task    = Task.Factory.StartNew(async() =>
            {
                var r = await coder.GeocodeAddressAsync(address).ConfigureAwait(false);
                Console.WriteLine("it ran!" + r.Length);
                results.AddRange(OnCompletion(r));
                reset.Set();
            });

            reset.WaitOne(TimeSpan.FromSeconds(10));
//            var task = await coder.GeocodeAddressAsync(address);
//            results = OnCompletion(task);
            return(results);
        }
예제 #17
0
        internal static async Task PlatformOpenMapsAsync(Placemark placemark, MapLaunchOptions options)
        {
#if __IOS__
            var address = new MKPlacemarkAddress
            {
                CountryCode = placemark.CountryCode,
                Country     = placemark.CountryName,
                State       = placemark.AdminArea,
                Street      = placemark.Thoroughfare,
                City        = placemark.Locality,
                Zip         = placemark.PostalCode
            }.Dictionary;
#else
            var address = new NSMutableDictionary
            {
                [CNPostalAddressKey.City]           = new NSString(placemark.Locality ?? string.Empty),
                [CNPostalAddressKey.Country]        = new NSString(placemark.CountryName ?? string.Empty),
                [CNPostalAddressKey.State]          = new NSString(placemark.AdminArea ?? string.Empty),
                [CNPostalAddressKey.Street]         = new NSString(placemark.Thoroughfare ?? string.Empty),
                [CNPostalAddressKey.PostalCode]     = new NSString(placemark.PostalCode ?? string.Empty),
                [CNPostalAddressKey.IsoCountryCode] = new NSString(placemark.CountryCode ?? string.Empty)
            };
#endif

            var           coder = new CLGeocoder();
            CLPlacemark[] placemarks;
            try
            {
                placemarks = await coder.GeocodeAddressAsync(address);
            }
            catch
            {
                Debug.WriteLine("Unable to get geocode address from address");
                return;
            }

            if ((placemarks?.Length ?? 0) == 0)
            {
                Debug.WriteLine("No locations exist, please check address.");
            }

            await OpenPlacemark(new MKPlacemark(placemarks[0].Location.Coordinate, address), options);
        }
예제 #18
0
        public static async Task <double[]> GetCoordonateFromName(string address)
        {
            CLPlacemark result;

            try
            {
                var geocoder = new CLGeocoder();
                var a        = await geocoder.GeocodeAddressAsync(address);

                result = a.FirstOrDefault();
            }
            catch
            {
                return(new[] { 0.0, 0.0 });
            }

            return(result != null
                ? new[] { result.Location.Coordinate.Latitude, result.Location.Coordinate.Longitude }
                : new[] { 0.0, 0.0 });
        }
        async void GeocodeToUpdateMap(string address)
        {
            b_SearchButton.Enabled = false;
            var geoCoder = new CLGeocoder();

            try
            {
                CLPlacemark[] placemarks = await geoCoder.GeocodeAddressAsync(address);

                UpdateMap(placemarks[0].Location.Coordinate);

                await AddPins();

                UpdateSearchLocation(new CLLocationCoordinate2D(placemarks[0].Location.Coordinate.Latitude, placemarks[0].Location.Coordinate.Longitude));
            }
            catch
            {
                UIAlertController okAlertController = UIAlertController.Create("ERROR", "Invalid address, try again", UIAlertControllerStyle.Alert);
            }
            b_SearchButton.Enabled = true;
        }
        async Task <string> GeocodeToConsoleAsync(string address)
        {
            var geoCoder = new CLGeocoder();

            CLPlacemark[] placemarks = null;
            try
            {
                placemarks = await geoCoder.GeocodeAddressAsync(address);
            }
            catch
            {
                if (!methods.IsConnected())
                {
                    InvokeOnMainThread(() =>
                    {
                        NoConnectionViewController.view_controller_name = GetType().Name;
                        this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                        return;
                    });
                }
                return(null);
            }
            foreach (var placemark in placemarks)
            {
                Console.WriteLine(placemark);
                CLLocationCoordinate2D coord = new CLLocationCoordinate2D(placemark.Location.Coordinate.Latitude, placemark.Location.Coordinate.Longitude);
                var marker = Marker.FromPosition(coord);
                //marker.Title = string.Format("Marker 1");
                marker.Icon = UIImage.FromBundle("add_loc_marker.png");
                marker.Map  = mapView;
                camera      = CameraPosition.FromCamera(latitude: Convert.ToDouble(placemark.Location.Coordinate.Latitude, CultureInfo.InvariantCulture),
                                                        longitude: Convert.ToDouble(placemark.Location.Coordinate.Longitude, CultureInfo.InvariantCulture),
                                                        zoom: zoom);
                lat_temporary  = placemark.Location.Coordinate.Latitude.ToString().Replace(',', '.');
                lng_temporary  = placemark.Location.Coordinate.Longitude.ToString().Replace(',', '.');
                mapView.Camera = camera;
                break;
            }
            return("");
        }
        // This overridden method will be called after the AcquaintanceDetailViewController has been instantiated and loaded into memory,
        // but before the view hierarchy is rendered to the device screen.
        // The "async" keyword is added here to the override in order to allow other awaited async method calls inside the override to be called ascynchronously.
        public override async void ViewWillAppear(bool animated)
        {
            if (TeamMemberLite == null)
            {
                return;
            }

            Title = TeamMemberLite.DisplayName;
            CompanyNameLabel.Text = TeamMemberLite.Company;
            JobTitleLabel.Text    = TeamMemberLite.JobTitle;

            teamMember = await teamMemberService.Get(TeamMemberLite);

            if (teamMember != null)
            {
                // set the title and label text properties

                StreetLabel.Text         = teamMember.Street;
                CityLabel.Text           = teamMember.City;
                StateAndPostalLabel.Text = teamMember.StatePostal;
                PhoneLabel.Text          = teamMember.Phone;
                EmailLabel.Text          = teamMember.Email;

                // Set image views for user actions.
                // The action for getting navigation directions is setup further down in this method, after the geocoding occurs.
                SetupSendMessageAction();
                SetupDialNumberAction();
                SetupSendEmailAction();

                GetDirectionsImageView.Image = UIImage.FromBundle("directions");
                // use FFImageLoading library to asynchronously:
                await ImageService
                .Instance
                .LoadUrl(teamMember.PhotoUrl, TimeSpan.FromHours(Settings.ImageCacheDurationHours)) // get the image from a URL
                .LoadingPlaceholder("placeholderProfileImage.png")                                  // specify a placeholder image
                .Transform(new CircleTransformation())                                              // transform the image to a circle
                .Error(e => System.Diagnostics.Debug.WriteLine(e.Message))
                .IntoAsync(ProfilePhotoImageView);                                                  // load the image into the UIImageView

                try {
                    // asynchronously geocode the address
                    var locations = await _Geocoder.GeocodeAddressAsync(teamMember.AddressString);

                    // if we have at least one location
                    if (locations != null && locations.Length > 0)
                    {
                        var coord = locations[0].Location.Coordinate;

                        var span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coord.Latitude));

                        // set the region that the map should display
                        MapView.Region = new MKCoordinateRegion(coord, span);

                        // create a new pin for the map
                        var pin = new MKPointAnnotation()
                        {
                            Title      = TeamMemberLite.DisplayName,
                            Coordinate = new CLLocationCoordinate2D()
                            {
                                Latitude  = coord.Latitude,
                                Longitude = coord.Longitude
                            }
                        };

                        // add the pin to the map
                        MapView.AddAnnotation(pin);

                        // add a top border to the MapView
                        MapView.Layer.AddSublayer(new CALayer()
                        {
                            BackgroundColor = UIColor.LightGray.CGColor,
                            Frame           = new CGRect(0, 0, MapView.Frame.Width, 1)
                        });

                        // setup fhe action for getting navigation directions
                        SetupGetDirectionsAction(coord.Latitude, coord.Longitude);
                    }
                } catch {
                    DisplayErrorAlertView("Geocoding Error", "Please make sure the address is valid and that you have a network connection.");
                }
            }
        }
예제 #22
0
        /// <summary>
        /// Navigate to an address
        /// </summary>
        /// <param name="name">Label to display</param>
        /// <param name="street">Street</param>
        /// <param name="city">City</param>
        /// <param name="state">Sate</param>
        /// <param name="zip">Zip</param>
        /// <param name="country">Country</param>
        /// <param name="countryCode">Country Code if applicable</param>
        /// <param name="navigationType">Navigation type</param>
        public async void NavigateTo(string name, string street, string city, string state, string zip, string country, string countryCode, NavigationType navigationType = NavigationType.Default)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(street))
            {
                street = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(city))
            {
                city = string.Empty;
            }

            if (string.IsNullOrWhiteSpace(state))
            {
                state = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(zip))
            {
                zip = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(country))
            {
                country = string.Empty;
            }

            var placemarkAddress = new MKPlacemarkAddress
            {
                City        = city,
                Country     = country,
                State       = state,
                Street      = street,
                Zip         = zip,
                CountryCode = countryCode
            };

            var coder      = new CLGeocoder();
            var placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);

            if (placemarks.Length == 0)
            {
                Debug.WriteLine("Unable to get geocode address from address");
                return;
            }

            CLPlacemark placemark = placemarks[0];

            var mapItem = new MKMapItem(new MKPlacemark(placemark.Location.Coordinate, placemarkAddress));

            mapItem.Name = name;

            MKLaunchOptions launchOptions = null;

            if (navigationType != NavigationType.Default)
            {
                launchOptions = new MKLaunchOptions
                {
                    DirectionsMode = navigationType == NavigationType.Driving ? MKDirectionsMode.Driving : MKDirectionsMode.Walking
                };
            }

            var mapItems = new[] { mapItem };

            MKMapItem.OpenMaps(mapItems, launchOptions);
        }
예제 #23
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Starting off by initilizing all of the components of the view.

            var stackView = new UIStackView
            {
                Axis         = UILayoutConstraintAxis.Vertical,
                Alignment    = UIStackViewAlignment.Fill,
                Distribution = UIStackViewDistribution.EqualSpacing,
                Spacing      = 25,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            var scrollView = new UIScrollView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height));

            var NameField = new UITextField
            {
                Frame       = new CGRect(25, 20, 35, 15),
                Placeholder = "Event Name"
            };
            var AddressField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "Address"
            };
            var CityFiled = new UITextField
            {
                Frame       = new CGRect(25, 40, 35, 15),
                Placeholder = "City"
            };
            var StateField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "State"
            };
            var CountryField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "Country"
            };
            var ZipField = new UITextField
            {
                Frame       = new CGRect(25, 50, 35, 15),
                Placeholder = "ZipCode"
            };
            var DescField = new UITextField
            {
                Frame       = new CGRect(25, 50, 35, 15),
                Placeholder = "Event Description"
            };
            var SubmitButton = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 90, 300, 30)
            };
            var GetImage = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 60, 300, 30)
            };
            var StateLabel = new UILabel()
            {
                Text          = "Press the button to choose between Public or Private.",
                TextAlignment = UITextAlignment.Center
            };
            var isPublicButton = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 90, 300, 30)
            };


            UIDatePicker DatePicker = new UIDatePicker(new CGRect(
                                                           UIScreen.MainScreen.Bounds.X - UIScreen.MainScreen.Bounds.Width,
                                                           UIScreen.MainScreen.Bounds.Height - 230,
                                                           UIScreen.MainScreen.Bounds.Width,
                                                           180));
            var calendar = new NSCalendar(NSCalendarType.Gregorian);

            calendar.TimeZone = NSTimeZone.LocalTimeZone;
            var currentDate = NSDate.Now;
            var components  = new NSDateComponents();

            components.Year = -60;
            NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None);

            DatePicker.MinimumDate = currentDate;
            DatePicker.Mode        = UIDatePickerMode.DateAndTime;

            SubmitButton.SetTitle("Submit Event", UIControlState.Normal);
            GetImage.SetTitle("Pick An Image", UIControlState.Normal);
            isPublicButton.SetTitle("Private Event", UIControlState.Normal);


            //Start putting the components together to build the view.

            stackView.AddArrangedSubview(NameField);
            stackView.AddArrangedSubview(AddressField);
            stackView.AddArrangedSubview(CityFiled);
            stackView.AddArrangedSubview(StateField);
            stackView.AddArrangedSubview(CountryField);
            stackView.AddArrangedSubview(ZipField);
            stackView.AddArrangedSubview(DescField);
            stackView.AddArrangedSubview(DatePicker);
            stackView.AddArrangedSubview(StateLabel);
            stackView.AddArrangedSubview(isPublicButton);
            stackView.AddArrangedSubview(GetImage);
            stackView.AddArrangedSubview(SubmitButton);

            scrollView.AddSubview(stackView);

            View.Add(scrollView);

            //Finializing the layout.

            scrollView.ContentSize = stackView.Frame.Size;
            scrollView.AddConstraint(stackView.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor));
            scrollView.AddConstraint(stackView.BottomAnchor.ConstraintEqualTo(scrollView.BottomAnchor));
            scrollView.AddConstraint(stackView.LeftAnchor.ConstraintEqualTo(scrollView.LeftAnchor));
            scrollView.AddConstraint(stackView.RightAnchor.ConstraintEqualTo(scrollView.RightAnchor));

            View.AddConstraint(scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor));
            View.AddConstraint(scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor));
            View.AddConstraint(scrollView.LeftAnchor.ConstraintEqualTo(View.LeftAnchor));
            View.AddConstraint(scrollView.RightAnchor.ConstraintEqualTo(View.RightAnchor));
            View.BackgroundColor = UIColor.White;
            var g = new UITapGestureRecognizer(() => View.EndEditing(true));

            View.AddGestureRecognizer(g);


            //Button function #1: submitting the event and presenting the submission to the user.
            SubmitButton.TouchUpInside += async(object sender, EventArgs e) =>
            {
                //Populate the Event model.
                userEvent.Address   = AddressField.Text;
                userEvent.EventName = NameField.Text;
                userEvent.City      = CityFiled.Text;
                userEvent.State     = StateField.Text;
                userEvent.Country   = CountryField.Text;
                userEvent.ZipCode   = int.Parse(ZipField.Text);
                DateTime.SpecifyKind((DateTime)DatePicker.Date, DateTimeKind.Utc).ToLocalTime();
                userEvent.DateOfEvent = (DateTime)DatePicker.Date;
                userEvent.isPublic    = isPublic;
                var    geoCoder     = new CLGeocoder();
                var    location     = new CLLocation();
                string worldAddress = userEvent.Address + ", "
                                      + userEvent.City + ", "
                                      + userEvent.State + ", "
                                      + userEvent.Country + ", "
                                      + userEvent.ZipCode.ToString();
                var placemarks = geoCoder.GeocodeAddressAsync(worldAddress);
                await placemarks.ContinueWith((addresses) =>
                {
                    foreach (var address in addresses.Result)
                    {
                        location = address.Location;
                    }
                });

                userEvent.Lat         = location.Coordinate.Latitude;
                userEvent.Long        = location.Coordinate.Longitude;
                userEvent.Description = DescField.Text;

                EventService ES = new EventService(_client);
                if (userImage != null)
                {
                    Event EventLocation = await ES.CreateNewEvent(userEvent, userImage);

                    var ShowEvent = new SubmittedEvent(EventLocation, _client, _locationmanager);
                    this.NavigationController.PopViewController(true);
                    this.NavigationController.PushViewController(ShowEvent, true);
                }
                else
                {
                    Event EventLocation = await ES.CreateNewEvent(userEvent);

                    var ShowEvent = new SubmittedEvent(EventLocation, _client, _locationmanager);
                    this.NavigationController.PopViewController(true);
                    this.NavigationController.PushViewController(ShowEvent, true);
                }
            };

            //Button function #2: opening Image Picker
            GetImage.TouchUpInside += (object sender, EventArgs e) =>
            {
                ShowSelectPicPopup();
            };

            //Button function #3: Public/Private toggle function
            isPublicButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                if (isPublic == false)
                {
                    isPublic = true;
                    isPublicButton.SetTitle("Public Event", UIControlState.Normal);
                }
                else
                {
                    isPublic = false;
                    isPublicButton.SetTitle("Private Event", UIControlState.Normal);
                }
            };
        }
        // This overridden method will be called after the AcquaintanceDetailViewController has been instantiated and loaded into memory,
        // but before the view hierarchy is rendered to the device screen.
        // The "async" keyword is added here to the override in order to allow other awaited async method calls inside the override to be called ascynchronously.
        public override async void ViewWillAppear(bool animated)
        {
            if (Acquaintance != null)
            {
                // set the title and label text properties
                Title = Acquaintance.DisplayName;
                CompanyNameLabel.Text    = Acquaintance.Company;
                JobTitleLabel.Text       = Acquaintance.JobTitle;
                StreetLabel.Text         = Acquaintance.Street;
                CityLabel.Text           = Acquaintance.City;
                StateAndPostalLabel.Text = Acquaintance.StatePostal;
                PhoneLabel.Text          = Acquaintance.Phone;
                EmailLabel.Text          = Acquaintance.Email;

                // Set image views for user actions.
                // The action for getting navigation directions is setup further down in this method, after the geocoding occurs.
                SetupSendMessageAction();
                SetupDialNumberAction();
                SetupSendEmailAction();

                // use FFImageLoading library to asynchronously:
                await ImageService.Instance
                .LoadFileFromApplicationBundle(String.Format(Acquaintance.PhotoUrl))                            // get the image from the app bundle
                .LoadingPlaceholder("placeholderProfileImage.png")                                              // specify a placeholder image
                .Transform(new CircleTransformation())                                                          // transform the image to a circle
                .IntoAsync(ProfilePhotoImageView);                                                              // load the image into the UIImageView

                // use FFImageLoading library to asynchronously:
                //	await ImageService
                //		.LoadUrl(Acquaintance.PhotoUrl)                     // get the image from a URL
                //		.LoadingPlaceholder("placeholderProfileImage.png")  // specify a placeholder image
                //		.Transform(new CircleTransformation())              // transform the image to a circle
                //		.IntoAsync(ProfilePhotoImageView);                  // load the image into the UIImageView


                // The FFImageLoading library has nicely transformed the image to a circle, but we need to use some iOS UIKit and CoreGraphics API calls to give it a colored border.
                double min = Math.Min(ProfilePhotoImageView.Frame.Height, ProfilePhotoImageView.Frame.Height);
                ProfilePhotoImageView.Layer.CornerRadius  = (float)(min / 2.0);
                ProfilePhotoImageView.Layer.MasksToBounds = false;
                ProfilePhotoImageView.Layer.BorderColor   = UIColor.FromRGB(84, 119, 153).CGColor;
                ProfilePhotoImageView.Layer.BorderWidth   = 5;
                ProfilePhotoImageView.BackgroundColor     = UIColor.Clear;
                ProfilePhotoImageView.ClipsToBounds       = true;

                try
                {
                    // asynchronously geocode the address
                    var locations = await _Geocoder.GeocodeAddressAsync(Acquaintance.AddressString);

                    // if we have at least one location
                    if (locations != null && locations.Length > 0)
                    {
                        var coord = locations[0].Location.Coordinate;

                        var span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coord.Latitude));

                        // set the region that the map should display
                        MapView.Region = new MKCoordinateRegion(coord, span);

                        // create a new pin for the map
                        var pin = new MKPointAnnotation()
                        {
                            Title      = Acquaintance.DisplayName,
                            Coordinate = new CLLocationCoordinate2D()
                            {
                                Latitude  = coord.Latitude,
                                Longitude = coord.Longitude
                            }
                        };

                        // add the pin to the map
                        MapView.AddAnnotation(pin);

                        // add a top border to the MapView
                        MapView.Layer.AddSublayer(new CALayer()
                        {
                            BackgroundColor = UIColor.LightGray.CGColor,
                            Frame           = new CGRect(0, 0, MapView.Frame.Width, 1)
                        });

                        // setup fhe action for getting navigation directions
                        SetupGetDirectionsAction(coord.Latitude, coord.Longitude);
                    }
                } catch
                {
                    //DisplayErrorAlertView("Geocoding Error", "Please make sure the address is valid and that you have a network connection.");
                }
            }
        }
    /// <summary>
    /// Navigate to an address
    /// </summary>
    /// <param name="name">Label to display</param>
    /// <param name="street">Street</param>
    /// <param name="city">City</param>
    /// <param name="state">Sate</param>
    /// <param name="zip">Zip</param>
    /// <param name="country">Country</param>
    /// <param name="countryCode">Country Code if applicable</param>
    /// <param name="navigationType">Navigation type</param>
    public async void NavigateTo(string name, string street, string city, string state, string zip, string country, string countryCode, NavigationType navigationType = NavigationType.Default)
    {
      if (string.IsNullOrWhiteSpace(name))
        name = string.Empty;


      if (string.IsNullOrWhiteSpace(street))
        street = string.Empty;


      if (string.IsNullOrWhiteSpace(city))
        city = string.Empty;

      if (string.IsNullOrWhiteSpace(state))
        state = string.Empty;


      if (string.IsNullOrWhiteSpace(zip))
        zip = string.Empty;


      if (string.IsNullOrWhiteSpace(country))
        country = string.Empty;

      var placemarkAddress = new MKPlacemarkAddress
      {
        City = city,
        Country = country,
        State = state,
        Street = street,
        Zip = zip,
        CountryCode = countryCode
      };

      var coder = new CLGeocoder();
      var placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);

      if(placemarks.Length == 0)
      {
        Debug.WriteLine("Unable to get geocode address from address");
        return;
      }

      CLPlacemark placemark = placemarks[0];

      var mapItem = new MKMapItem(new MKPlacemark(placemark.Location.Coordinate, placemarkAddress));
      mapItem.Name = name;

      MKLaunchOptions launchOptions = null;
      if (navigationType != NavigationType.Default)
      {
        launchOptions = new MKLaunchOptions
        {
          DirectionsMode = navigationType == NavigationType.Driving ? MKDirectionsMode.Driving : MKDirectionsMode.Walking
        };
      }

      var mapItems = new[] { mapItem };
      MKMapItem.OpenMaps(mapItems, launchOptions);
    }
        /// <summary>
        /// Navigate to an address
        /// </summary>
        /// <param name="name">Label to display</param>
        /// <param name="street">Street</param>
        /// <param name="city">City</param>
        /// <param name="state">Sate</param>
        /// <param name="zip">Zip</param>
        /// <param name="country">Country</param>
        /// <param name="countryCode">Country Code if applicable</param>
        /// <param name="navigationType">Navigation type</param>
        public async Task <bool> NavigateTo(string name, string street, string city, string state, string zip, string country, string countryCode, NavigationType navigationType = NavigationType.Default)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(street))
            {
                street = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(city))
            {
                city = string.Empty;
            }

            if (string.IsNullOrWhiteSpace(state))
            {
                state = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(zip))
            {
                zip = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(country))
            {
                country = string.Empty;
            }


            CLPlacemark[]      placemarks       = null;
            MKPlacemarkAddress placemarkAddress = null;

            try
            {
                placemarkAddress = new MKPlacemarkAddress
                {
                    City        = city,
                    Country     = country,
                    State       = state,
                    Street      = street,
                    Zip         = zip,
                    CountryCode = countryCode
                };

                var coder = new CLGeocoder();

                placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to get geocode address from address: " + ex);
                return(false);
            }

            if ((placemarks?.Length ?? 0) == 0)
            {
                Debug.WriteLine("No locations exist, please check address.");
                return(false);
            }

            try
            {
                var placemark = placemarks[0];

                var mapItem = new MKMapItem(new MKPlacemark(placemark.Location.Coordinate, placemarkAddress));
                mapItem.Name = name;

                MKLaunchOptions launchOptions = null;
                if (navigationType != NavigationType.Default)
                {
                    launchOptions = new MKLaunchOptions
                    {
                        DirectionsMode = navigationType == NavigationType.Driving ? MKDirectionsMode.Driving : MKDirectionsMode.Walking
                    };
                }

                var mapItems = new[] { mapItem };
                MKMapItem.OpenMaps(mapItems, launchOptions);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to launch maps: " + ex);
            }

            return(true);
        }
        /// <summary>
        /// Navigate to an address
        /// </summary>
        /// <param name="name">Label to display</param>
        /// <param name="street">Street</param>
        /// <param name="city">City</param>
        /// <param name="state">Sate</param>
        /// <param name="zip">Zip</param>
        /// <param name="country">Country</param>
        /// <param name="countryCode">Country Code if applicable</param>
        /// <param name="navigationType">Navigation type</param>
        public async Task<bool> NavigateTo(string name, string street, string city, string state, string zip, string country, string countryCode, NavigationType navigationType = NavigationType.Default)
        {
            if (string.IsNullOrWhiteSpace(name))
                name = string.Empty;


            if (string.IsNullOrWhiteSpace(street))
                street = string.Empty;


            if (string.IsNullOrWhiteSpace(city))
                city = string.Empty;

            if (string.IsNullOrWhiteSpace(state))
                state = string.Empty;


            if (string.IsNullOrWhiteSpace(zip))
                zip = string.Empty;


            if (string.IsNullOrWhiteSpace(country))
                country = string.Empty;


            CLPlacemark[] placemarks = null;
            MKPlacemarkAddress placemarkAddress = null;
            try
            {
                placemarkAddress = new MKPlacemarkAddress
                {
                    City = city,
                    Country = country,
                    State = state,
                    Street = street,
                    Zip = zip,
                    CountryCode = countryCode
                };

                var coder = new CLGeocoder();
                
                placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to get geocode address from address: " + ex);
                return false;
            }

            if ((placemarks?.Length ?? 0) == 0)
            {
                Debug.WriteLine("No locations exist, please check address.");
                return false;
            }

            try
            {
                var placemark = placemarks[0];

                var mapItem = new MKMapItem(new MKPlacemark(placemark.Location.Coordinate, placemarkAddress));
                mapItem.Name = name;

                MKLaunchOptions launchOptions = null;
                if (navigationType != NavigationType.Default)
                {
                    launchOptions = new MKLaunchOptions
                    {
                        DirectionsMode = navigationType == NavigationType.Driving ? MKDirectionsMode.Driving : MKDirectionsMode.Walking
                    };
                }

                var mapItems = new[] { mapItem };
                MKMapItem.OpenMaps(mapItems, launchOptions);
            }
            catch(Exception ex)
            {
                Debug.WriteLine("Unable to launch maps: " + ex);
            }

            return true;
        }
예제 #28
0
        /// <summary>
        /// Purpose: Gets the Person to get the data from -> Get the coordinate of the person -> call the Eventhandler to draw the annotation of the map
        /// Example: FillControls (person) -> HandleCLGeocodeCompletionHandler
        /// </summary>
        /// <param name="person">The person to fill the controlls with</param>
        async public override Task FillControlsAsync (BusinessLayer.Person person)
        {

            CLPlacemark[] placemarks;
            // Then fill the controls
            if (person == null || person.Name == null)
                return;

            _person = person;

            // Send the address infos of the person to the CLGeocoder to find the location
            CLGeocoder clg = new CLGeocoder(); 
            string location = person.Strasse + "," + person.Ort + "," + person.PLZ ;
            placemarks = await clg.GeocodeAddressAsync(location);
            HandleCLGeocodeCompletionHandler(placemarks, null);


        }