Пример #1
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);
        }
Пример #2
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();
            mpMapa.ShowsUserLocation = true;
            var Localizador = CrossGeolocator.Current;
            var Posicion    = await Localizador.GetPositionAsync(TimeSpan.FromSeconds(10), null, true); //obtener la posición cada 10 segundos.

            var Ubicacion     = new CLLocation(Posicion.Latitude, Posicion.Longitude);
            var Georeferencia = new CLGeocoder();
            var DatosGeo      = await Georeferencia.ReverseGeocodeLocationAsync(Ubicacion);


            Latitud  = Posicion.Latitude;
            Longitud = Posicion.Longitude;

            lblCiudad.Text       = DatosGeo[0].Locality;
            lblDepartamento.Text = DatosGeo[0].AdministrativeArea;
            lblLatitud.Text      = Latitud.ToString();
            lblLongitud.Text     = Longitud.ToString();
            lblMunicipio.Text    = DatosGeo[0].SubLocality;
            lblPais.Text         = DatosGeo[0].Country;
            txtDescripcion.Text  = DatosGeo[0].Description;

            mpMapa.MapType = MapKit.MKMapType.HybridFlyover; //Se establece el tipo de mapa
            var CentrarMapa = new CLLocationCoordinate2D(Latitud, Longitud);
            var AlturaMapa  = new MKCoordinateSpan(.003, .003);
            var Region      = new MKCoordinateRegion(CentrarMapa, AlturaMapa);

            mpMapa.SetRegion(Region, true);
        }
Пример #3
0
        public void Configure(string location)
        {
            var geoCoder = new CLGeocoder();

            Console.WriteLine(location);
            geoCoder.GeocodeAddress(location, AnnotationHandler);
        }
        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();
        }
Пример #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
        protected void AgregoMapa()
        {
            map.MapType = MKMapType.Standard;
            map.Bounds  = UIScreen.MainScreen.Bounds;           //full screen baby

            map.ShowsUserLocation = false;

            MKReverseGeocoder geo      = new MKReverseGeocoder(locationManager.Location.Coordinate);
            CLGeocoder        geocoder = new CLGeocoder();

            Task.Factory.StartNew(async() =>
            {
                var res = await geocoder.ReverseGeocodeLocationAsync(locationManager.Location);
                Console.WriteLine(res[0].AdministrativeArea);

                pais   = res[0].Country;
                ciudad = res[0].Locality;
            });

            // centro el mapa y pongo el zoom en la region
            mapCenter = new CLLocationCoordinate2D(locationManager.Location.Coordinate.Latitude,
                                                   locationManager.Location.Coordinate.Longitude);
            var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 2000, 2000);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;
        }
        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);
        }
Пример #8
0
        public async Task <Address[]> GetAddressesAsync(double latitude, double longitude)
        {
            var geocoder   = new CLGeocoder();
            var placemarks = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(latitude, longitude));

            return(placemarks.Select(Convert).ToArray());
        }
Пример #9
0
        public void pegarAsync(float latitude, float longitude, GeoEnderecoEventHandler callback)
        {
            var location = new CLLocation(latitude, longitude);
            var geoCoder = new CLGeocoder();

            geoCoder.ReverseGeocodeLocation(location, (placemarkers, error) => {
                if (placemarkers.Length > 0)
                {
                    var geoEndereco = placemarkers[0];
                    var endereco    = new GeoEnderecoInfo
                    {
                        Logradouro  = geoEndereco.Thoroughfare,
                        Complemento = geoEndereco.SubThoroughfare,
                        Bairro      = geoEndereco.SubLocality,
                        Cidade      = geoEndereco.Locality,
                        Uf          = geoEndereco.AdministrativeArea,
                        CEP         = geoEndereco.PostalCode,
                    };
                    if (callback != null)
                    {
                        ThreadUtils.RunOnUiThread(() => {
                            callback(null, new GeoEnderecoEventArgs(endereco));
                        });
                    }
                }
            });
        }
        //als user gebruik maakt van de location button
        public void GetAddress()
        {
            var myVM = this.ViewModel as AddLocationViewModel;

            if (myVM != null)
            {
                //permissie vragen aan gebruiker voor locatie
                CLLocationManager locationManager = new CLLocationManager();
                locationManager.RequestWhenInUseAuthorization();

                CLLocation loc = locationManager.Location;
                ReverseGeocodeToConsoleAsync(loc);

                async void ReverseGeocodeToConsoleAsync(CLLocation location)
                {
                    var geoCoder   = new CLGeocoder();
                    var placemarks = await geoCoder.ReverseGeocodeLocationAsync(location);

                    txtCity.Text          = placemarks[0].PostalAddress.City;
                    myVM.Location.City    = placemarks[0].PostalAddress.City;
                    txtCountry.Text       = placemarks[0].PostalAddress.Country;
                    myVM.Location.Country = placemarks[0].PostalAddress.Country;
                    txtStreet.Text        = placemarks[0].PostalAddress.Street;
                    myVM.Location.Street  = placemarks[0].PostalAddress.Street;
                }
            }
        }
Пример #11
0
        public async Task <LocationAddress> GetLocationAddress(double latitude, double longitude)
        {
            var geoCoder   = new CLGeocoder();
            var place      = new CLLocation(latitude, longitude);
            var placemarks = await geoCoder.ReverseGeocodeLocationAsync(place);

            if (placemarks.Any())
            {
                var placeMark = placemarks.First();

                var location = new LocationAddress()
                {
                    Name     = placeMark.Name,
                    City     = placeMark.Locality,
                    Province = placeMark.AdministrativeArea,
                    ZipCode  = placeMark.PostalCode,
                    Country  = $"{placeMark.Country} ({placeMark.IsoCountryCode})",
                    Address  = new CNPostalAddressFormatter().StringFor(placeMark.PostalAddress)
                };

                return(location);
            }

            return(null);
        }
        public TravelMapLocationDataSource()
        {
            locationCheckTimer = new Timer(3000);

            locationCheckTimer.Elapsed += (object sender, ElapsedEventArgs e) =>
            {
                Console.WriteLine($"Tick, updating {Locations.Count} items.");
                foreach (var locale in Locations)
                {
                    CLGeocoder coder      = new CLGeocoder();
                    CLLocation clLocation = new CLLocation(locale.Location.Latitude, locale.Location.Longitude);

                    locale.LocationNameString = $"{locale.Location.Latitude}, {locale.Location.Longitude}";
                    coder.ReverseGeocodeLocation(clLocation, (placemarks, error) =>
                    {
                        CLPlacemark placemark = placemarks[0];
                        if (placemark != null)
                        {
                            locale.LocationNameString = placemark.Name;
                        }
                        if (error != null)
                        {
                            Console.WriteLine("Error Placemarking: " + error.LocalizedDescription);
                            locale.LocationNameString = $"{locale.Location.Latitude}, {locale.Location.Longitude}.";
                        }
                    });


                    RaiseLocationNameAcquired(this, new EventArgs());
                }
            };

            locationCheckTimer.Start();
        }
Пример #13
0
    void LocationManager_LocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
    {
        locationManager.StopUpdatingLocation();
        var l = e.Locations[0].Coordinate;


        coder = new CLGeocoder();
        coder.ReverseGeocodeLocation(new CLLocation(l.Latitude, l.Longitude), (placemarks, error) =>
        {
            var city    = placemarks[0].Locality;
            var state   = placemarks[0].AdministrativeArea;
            var weather = new XAMWeatherFetcher(city, state);

            var result = weather.GetWeather();

            InvokeOnMainThread(() =>
            {
                info.Text       = result.Temp + "°F " + result.Text;
                latLong.Text    = l.Latitude + ", " + l.Longitude;
                cityField.Text  = result.City;
                stateField.Text = result.State;

                getWeatherButton.Enabled  = true;
                getLocationButton.Enabled = true;
            });
        });
    }
Пример #14
0
 public GeocoderViewControllerAdapter(MvxViewController viewController, MKMapView mapView, Action <string> addressChanged)
     : base(viewController)
 {
     _geocoder              = new CLGeocoder();
     _addressChanged        = addressChanged;
     mapView.RegionChanged += MapView_RegionChanged;
     mapView.SetRegion(new MapKit.MKCoordinateRegion(new CoreLocation.CLLocationCoordinate2D(45.5316085, -73.6227476), new MapKit.MKCoordinateSpan(0.01, 0.01)), animated: true);
 }
Пример #15
0
 public GeocoderViewControllerAdapter(MvxViewController viewController, MKMapView mapView, Action<string> addressChanged)
     : base(viewController)
 {
     _geocoder = new CLGeocoder ();
     _addressChanged = addressChanged;
     mapView.RegionChanged += MapView_RegionChanged;
     mapView.SetRegion (new MapKit.MKCoordinateRegion (new CoreLocation.CLLocationCoordinate2D (45.5316085, -73.6227476), new MapKit.MKCoordinateSpan (0.01, 0.01)), animated: true);
 }
Пример #16
0
        public async Task <CLPlacemark> ReverseGeocodeLocation(CLLocation location)
        {
            var geocoder = new CLGeocoder();

            var placemarks = await geocoder.ReverseGeocodeLocationAsync(location);

            return(placemarks?.FirstOrDefault());
        }
Пример #17
0
        public static async Task <IEnumerable <Location> > GetLocationsAsync(string address)
        {
            using (var geocoder = new CLGeocoder())
            {
                var positionList = await geocoder.GeocodeAddressAsync(address);

                return(positionList?.ToLocations());
            }
        }
Пример #18
0
        public static async Task <IEnumerable <Placemark> > GetPlacemarksAsync(double latitude, double longitude)
        {
            using (var geocoder = new CLGeocoder())
            {
                var addressList = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(latitude, longitude));

                return(addressList?.ToPlacemarks());
            }
        }
        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);
        }
Пример #20
0
        public async Task <GeoAddress[]> GeocodeLocationAsync(double latitude, double longitude, string currentLanguage)
        {
            var geocoder = new CLGeocoder();

            var placemarks = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(latitude, longitude));

            return(placemarks
                   .Select(ConvertPlacemarkToAddress)
                   .ToArray());
        }
        /// <summary>
        /// Retrieve addresses for position.
        /// </summary>
        /// <param name="position">Desired position (latitude and longitude)</param>
        /// <returns>Addresses of the desired position</returns>
        public async Task<IEnumerable<Address>> GetAddressesForPositionAsync(Position position, string mapKey = null)
        {
            if (position == null)
                throw new ArgumentNullException(nameof(position));

            using (var geocoder = new CLGeocoder())
            {
                var addressList = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(position.Latitude, position.Longitude));
                return addressList.ToAddresses();
            }
        }
        async Task <string> ReverseGeocodeToConsoleAsync()
        {
            if (String.IsNullOrEmpty(CompanyAddressMapViewController.company_lat) || String.IsNullOrEmpty(CompanyAddressMapViewController.company_lng))
            {
                return(null);
            }
            double     lat      = Convert.ToDouble(CompanyAddressMapViewController.company_lat, CultureInfo.InvariantCulture);
            double     lng      = Convert.ToDouble(CompanyAddressMapViewController.company_lng, CultureInfo.InvariantCulture);
            CLLocation location = new CLLocation(lat, lng);
            var        geoCoder = new CLGeocoder();

            CLPlacemark[] placemarks = null;
            try
            {
                placemarks = await geoCoder.ReverseGeocodeLocationAsync(location);
            }
            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)
            {
                //notationTemp = null;
                regionTemp             = null;
                indexTemp              = placemark.PostalCode;
                countryTemp            = placemark.Country;
                cityTemp               = placemark.SubAdministrativeArea;
                FullCompanyAddressTemp = placemark.Thoroughfare;
                if (placemark.SubThoroughfare != null)
                {
                    if (!placemark.SubThoroughfare.Contains(placemark.Thoroughfare))
                    {
                        FullCompanyAddressTemp += " " + placemark.SubThoroughfare;
                    }
                }


                break;

                //Console.WriteLine(placemark);
                //return placemark.Description;
            }
            return("");
        }
Пример #23
0
        public async Task <LocationAddress> ReverseLocationAsync(double lat, double lng)
        {
            var geoCoder   = new CLGeocoder();
            var location   = new CLLocation(lat, lng);
            var placemarks = await geoCoder.ReverseGeocodeLocationAsync(location);

            var place = new LocationAddress();
            var pm    = placemarks[0];

            place.City = pm.AdministrativeArea;
            return(place);
        }
        /// <summary>
        /// Retrieve addresses for position.
        /// </summary>
        /// <param name="location">Desired position (latitude and longitude)</param>
        /// <returns>Addresses of the desired position</returns>
        public async Task <IEnumerable <Address> > GetAddressesForPositionAsync(Position location, string mapKey = null)
        {
            if (location == null)
            {
                return(null);
            }

            var geocoder    = new CLGeocoder();
            var addressList = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(location.Latitude, location.Longitude));

            return(addressList.ToAddresses());
        }
Пример #25
0
		static Task<IEnumerable<Position>> GetPositionsForAddressAsync(string address)
		{
			var geocoder = new CLGeocoder();
			var source = new TaskCompletionSource<IEnumerable<Position>>();
			geocoder.GeocodeAddress(address, (placemarks, error) =>
			{
				if (placemarks == null)
					placemarks = new CLPlacemark[0];
				IEnumerable<Position> positions = placemarks.Select(p => new Position(p.Location.Coordinate.Latitude, p.Location.Coordinate.Longitude));
				source.SetResult(positions);
			});
			return source.Task;
		}
Пример #26
0
        public async Task <string> GetCityNameFromLocationAsync(LocationInfo location)
        {
            string city = string.Empty;

            using (var geocoder = new CLGeocoder())
            {
                var addresses = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(location.Latitude, location.Longitude));

                city = addresses.FirstOrDefault()?.Locality;
            }

            return(city);
        }
Пример #27
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;
        }
Пример #28
0
		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;
		}
Пример #29
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");
            }
        }
Пример #30
0
        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);
                }
            };
        }
Пример #31
0
        public async Task <string> GetNameForLocation(double latitude, double longitude)
        {
            var coder = new CLGeocoder();

            var locations = await coder.ReverseGeocodeLocationAsync(new CLLocation
                                                                    (latitude, longitude));

            var name = locations?.FirstOrDefault()?.Name ?? "unknown";


            await AddCoffee(name, latitude, longitude);

            return(name);
        }
Пример #32
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}";
            }
        }
Пример #33
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);
        }
Пример #34
0
        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");
        }
Пример #35
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///
        /// Member functions of the class
        ///
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////

        #region Member Functions

        /// <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>
        public override void FillControls (BusinessLayer.Person person)
        {

            // 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 ;
            clg.GeocodeAddress(location, HandleCLGeocodeCompletionHandler);

        }
Пример #36
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;
        }
Пример #37
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);


        }
		/// <summary>
		/// Inits the location services.
		/// </summary>
		void InitLocationServices ()
		{
			// Setup the map.
			this.mapView.ShowsUserLocation = true;
			this.mapView.SetUserTrackingMode (MonoTouch.MapKit.MKUserTrackingMode.FollowWithHeading, true);

			// We need the GeoCoder to do reverse searches on locations.
			this.geoCoder = new CLGeocoder ();

			// Start getting updates from the location manager.
			this.locMan.StartUpdatingLocation ();

			// This will be called in case something goes wrong regarding location updates.
			this.locMan.Failed += (object sender, NSErrorEventArgs e) => Console.WriteLine ("LocationManager failed: {0}", e.Error);

			// Handle location updates.
			locMan.LocationsUpdated += HandleLocationsUpdated; 
		}
Пример #39
0
		public async Task<CLPlacemark> ReverseGeocodeLocation (CLLocation location)
		{
			var geocoder = new CLGeocoder ();

			var placemarks = await geocoder.ReverseGeocodeLocationAsync (location);

			return placemarks?.FirstOrDefault ();
		}
		// This constructor signature is required, for marshalling between the managed and native instances of this class.
		public AcquaintanceDetailViewController(IntPtr handle) : base(handle) 
		{ 
			_Geocoder = new CLGeocoder(); 
		}
Пример #41
0
    private void OnGUI()
    {
        KitchenSink.OnGUIBack();

        GUILayout.BeginArea(new Rect(50, 50, Screen.width - 100, Screen.height / 2 - 50));

        //this is the original way of how objective C use call back functions: Delegates using separate files.
        //in this case the file is PeoplePickerNavigationControllerDelegate.cs
        //we have have it easier to use delegates instead of creating new files for each delegate.
        //see examples above.  Ex: PersonalXT.CalendarAccess += delegate( ....
        if (GUILayout.Button("pick/select from contacts", GUILayout.ExpandHeight(true))) {
            ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController();
            if (pickerDelegate == null)
                pickerDelegate = new PeoplePickerNavigationControllerDelegate();
            picker.peoplePickerDelegate = pickerDelegate;
            UIApplication.deviceRootViewController.PresentViewController(picker, true, null);
        }

        if (GUILayout.Button("get all contacts", GUILayout.ExpandHeight(true)))	{
            //this will get you the contact records in which you can manipulate, etc
            //ABRecord[] contacts = PersonalXT.GetAllContactRecords();

            //convienent function to get the names of the contacts
            string[] contactList = PersonalXT.GetAllContactNames();
            for(int i=0; i < contactList.Length; i++){
                Log("Contact " + i + ": " +  contactList[i]);
            }
        }

        if (GUILayout.Button("add new contacts", GUILayout.ExpandHeight(true)))	{
            addNewContact();
        }

        if (GUILayout.Button("init Calendar and show events within 30 days", GUILayout.ExpandHeight(true))) {
            checkEventStoreAccessForCalendar();
        }

        if (GUILayout.Button("add an event for tomorrow", GUILayout.ExpandHeight(true))) {
            addEventForTomorrow();
        }

        if (GUILayout.Button("add alarm to events", GUILayout.ExpandHeight(true))) {
            createAlarmForEvents();
        }

        if (GUILayout.Button("add reminder with geolocation of current location", GUILayout.ExpandHeight(true))) {
            PersonalXT.RequestReminderAccess();
        }

        if (GUILayout.Button("reverse geocode happiest place on earth", GUILayout.ExpandHeight(true))) {
            CLLocation location = new CLLocation(33.809, -117.919);
            CLGeocoder geocoder = new CLGeocoder();
            geocoder.ReverseGeocodeLocation(location, delegate(object[] placemarks, NSError error) {
                if (error != null)
                    Debug.Log(error.LocalizedDescription());
                else {
                    foreach (var p in placemarks) {
                        var placemark = p as CLPlacemark;

                        Debug.Log("placemark: " + placemark.name + "\n"
                            + ABAddressFormatting.ABCreateString(placemark.addressDictionary, true));
                    }
                }
            });
        }

        if (GUILayout.Button("Significant location change", GUILayout.ExpandHeight(true))) {
            if (!CLLocationManager.LocationServicesEnabled() || !CLLocationManager.SignificantLocationChangeMonitoringAvailable()) {
                Debug.Log("Significant change monitoring not available.");
            } else {
        //				CLLocationManager manager = new CLLocationManager();

                manager.StartMonitoringSignificantLocationChanges();
            }
        }

        //commented out remove all events and reminders so users don't accidentally remove important events
        /*
        if (GUILayout.Button("remove all Events", GUILayout.ExpandHeight(true))) {
            PersonalXT.RemoveAllEvents();
            Log ("Removed events");
        }

        if (GUILayout.Button("remove all Reminders", GUILayout.ExpandHeight(true))) {
            PersonalXT.GetAllReminders(); //you can get all the reminders and handle them in line 59 above
            //PersonalXT.RemoveAllReminders(); //or you can simply call removeAllReminders
        }*/

        GUILayout.EndArea();
        OnGUILog();
    }
 public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
 {
     if (screen.CurrentWeather == null)
     {
         geocoder = new CLGeocoder ();
         geocoder.ReverseGeocodeLocation (newLocation, ReverseGeocodeLocationHandle);
         manager.StopUpdatingHeading();
         manager.StopUpdatingLocation();
     }
 }
 public LocationManager ()
 {
     this.locMgr = new CLLocationManager();
     clg = new CLGeocoder();
 }
        /// <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 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);
    }
Пример #46
0
		/// <summary>
		/// Getes the street for a given location.
		/// </summary>
		/// <returns>The string for location.</returns>
		/// <param name="geoCoder">Geo coder.</param>
		/// <param name="location">Location.</param>
		public async static Task<string> GetStreetForLocation(CLGeocoder geoCoder, CLLocation location)
		{
			// Try to find a human readable location description.
			var street = string.Empty;
			try
			{
				var placemarks = await geoCoder.ReverseGeocodeLocationAsync(location);
				if(placemarks != null && placemarks.Length > 0)
				{
					street = placemarks[0].Thoroughfare;
				}
			}
			catch(Exception ex)
			{
				// This can go wrong, especially on the Simulator.
				//Console.WriteLine("Geocoder error: " + ex);
				street = "(unknown)";
			}

			return street;
		}