public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var camera = CameraPosition.FromCamera (-33.868, 151.2086, 12);
			mapView = MapView.FromCamera (CGRect.Empty, camera);
			geocoder = new Geocoder ();

			mapView.CoordinateLongPressed += (sender, e) => {
				// On a long press, reverse geocode this location.
				geocoder.ReverseGeocodeCord (e.Coordinate, (response, error) => {
					if (response != null && response.FirstResult != null) {
						var marker = new Marker () {
							Position = e.Coordinate,
							Title = response.FirstResult.AddressLine1,
							Snippet = response.FirstResult.AddressLine2,
							AppearAnimation = MarkerAnimation.Pop,
							Map = mapView
						};
					} else {
						Console.WriteLine (string.Format ("Could not reverse geocode point ({0},{1}): {2}", 
							e.Coordinate.Latitude, e.Coordinate.Longitude, error));
					}
				});
			};

			View = mapView;
		}
Exemplo n.º 2
0
 public Form1()
 {
     InitializeComponent();
     geocoderService = new GeocoderService();
     tokenizer = new Tokenizer();
     geocoder = new Geocoder();
 }
        public void TestReplacement()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"
            <components>
                <component name='Geocoder'>
                    <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' />
                </component>

                <component name='DummyGeocoder'>
                    <parameter name='CandidateTextReplacer' value='Azavea.Open.Geocoding.Processors.CandidateTextReplacer,Azavea.Open.Geocoding' />
                </component>

                <component name='CandidateTextReplacer'>
                    <parameter name='ReplaceField' value='Address' />
                    <parameter name='Find' value='340' />
                    <parameter name='ReplaceWith' value='680' />
                </component>
            </components>
            ");
            Config gcCfg = new Config("GcConfig", doc);
            Geocoder gc = new Geocoder(gcCfg, "Geocoder");

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "340 N 12th St";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
            Assert.AreEqual("680 N 12th St", candidates[0].Address);
        }
Exemplo n.º 4
0
        private void centerMap(Geocoder.Location location)
        {
            mapCenter = location;
            var lat = mapCenter.Latitude;
            var lon = mapCenter.Longitude;
            gMap.Position = new GMap.NET.PointLatLng(lat, lon);

        }
Exemplo n.º 5
0
 private void markCurrentLocation(Geocoder.Location location)
 {
     var lat = location.Latitude;
     var lon = location.Longitude;
     GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen m = new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(new GMap.NET.PointLatLng(lat, lon));
     currentPosition = m;
     markerOverlay.Markers.Add(m);
     m.ToolTipText = "Current Position";
 }
Exemplo n.º 6
0
        public void TestLoadDummyGeocoderWithProcessorWithConfig()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig, "GeocoderSourcesWithProcessorsWithConfigs");

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "tS ht21 N 043";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Exemplo n.º 7
0
        public void TestLoadDummyGeocoder()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig);

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "340 N 12th St";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Exemplo n.º 8
0
        public async void DragMapPinProcess(CameraPosition cameraPos)
        {
            try
            {
                _currentLocation = cameraPos.Target;
                var geo = new Geocoder(this);

                var addresses = await geo.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 1);

                Address addressList = addresses[0];

                string formatedAddress = "";

                for (var i = 0; i < addressList.MaxAddressLineIndex; i++)
                {
                    formatedAddress += addressList.GetAddressLine(i) + " ";
                }
                _autocompleteTextView.Text = formatedAddress;
            }
            catch
            {
            }
        }
        async void ShowPOI(object sender, GoogleMap.MapLongClickEventArgs e)
        {
            LatLngBounds bounds = e.Point.GetBoundingBox(8000);     // ~5mi

            pointsOfInterest.ForEach(m => m.Remove());
            pointsOfInterest.Clear();

            Geocoder geocoder = new Geocoder(this);
            var      results  = await geocoder.GetFromLocationNameAsync("Starbucks", 10,
                                                                        bounds.Southwest.Latitude, bounds.Southwest.Longitude,
                                                                        bounds.Northeast.Latitude, bounds.Northeast.Longitude);

            foreach (var result in results)
            {
                var markerOptions = new MarkerOptions()
                                    .SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueCyan))
                                    .SetPosition(new LatLng(result.Latitude, result.Longitude))
                                    .SetTitle(result.FeatureName)
                                    .SetSnippet(GetAddress(result));

                pointsOfInterest.Add(map.AddMarker(markerOptions));
            }
        }
Exemplo n.º 10
0
        private async Task RetreiveLocation()
        {
            var locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 100;

            if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
            {
                var position = await locator.GetLastKnownLocationAsync();

                if (position == null)
                {
                    //got a cahched position, so let's use it.
                    position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);
                }
                txtLat.Text  = "Latitude: " + position.Latitude.ToString();
                txtLong.Text = "Longitude: " + position.Longitude.ToString();

                var geocoder        = new Geocoder();
                var locationAddress = await locator.GetAddressesForPositionAsync(position);

                foreach (var item in locationAddress)
                {
                    if (item.CountryName != null)
                    {
                        txtProvince.Text = "Province: " + item.CountryName;
                        txtCity.Text     = "City: " + item.AdminArea;
                        txtDistrict.Text = "District: " + item.SubAdminArea;
                        txtStreet.Text   = "Street: " + item.Thoroughfare;
                        txtAddress.Text  = "Address: " + item.SubThoroughfare;
                        break;
                    }
                }
                MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude)
                                                               , Distance.FromMiles(1)));
            }
        }
Exemplo n.º 11
0
        async void OnCalendarButtonClicked(object sender, EventArgs e)
        {
            ICalendar calendar = DependencyService.Get <ICalendar>();

            geoCoder = new Geocoder();

            var locator1 = CrossGeolocator.Current;

            if (!locator1.IsGeolocationEnabled)
            {
                //GPS is unavailable
                await DisplayAlert("No GPS", "We could not retrieve your location, please make sure you have GPS enabled.", "OK");
            }
            else
            {
                //Retrieve GPS coordinates
                var pos = await locator1.GetPositionAsync(timeoutMilliseconds : 30000);

                if (pos.Longitude != 0.0D || pos.Latitude != 0.0D)//0.0D to check if empty, double can't be 'null'.
                {
                    position = new Position(pos.Latitude, pos.Longitude);

                    //Works like a charm, sometimes.
                    var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(position);

                    //locationLabel.Text = possibleAddresses.First();
                    calendar.SetEvent(datePicker.Date + timePicker.Time, "Fiets ophalen", "Locatie van fiets: " + possibleAddresses.First());
                    //Debug.WriteLine("Fiets ophalen", "Locatie van fiets: " + position);
                    //Debug.WriteLine("set event");
                }
                else
                {
                    //GPS is unavailable
                    await DisplayAlert("Time-out", "We could not retrieve your location on time, please try again.", "OK");
                }
            }
        }
        private async Task PinLocationsAsync()  // async taak tot ophalen van de locatie
        {
            await Task.Run(async() =>
            {
                Geocoder gc = new Geocoder();

                //I believe the suggested format is:

                //House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country

                //Manueel positie invoeren op UWP

                MyPosition = new Position(51.134634, 2.763420);
                PinLabel   = $"{KlantAdres}";
                PinCollection.Add(new Pin()
                {
                    Position = MyPosition, Type = PinType.Generic, Label = PinLabel
                });



                var result =
                    await gc.GetPositionsForAddressAsync(KlantAdres);

                foreach (Position pos in result)
                {
                    Debug.WriteLine("Lat: {0}, Lng: {1}", pos.Latitude, pos.Longitude);
                    //MyPosition = new Position(pos.Latitude, pos.Longitude);
                    MyPosition = new Position(51.134634, 2.763420);
                    PinLabel   = $"{KlantAdres}";
                    PinCollection.Add(new Pin()
                    {
                        Position = MyPosition, Type = PinType.Generic, Label = PinLabel
                    });
                }
            });
        }
Exemplo n.º 13
0
        /// <summary>
        /// Override this method to execute an action when the BindingContext changes.
        /// </summary>
        /// <remarks></remarks>
        protected async override void OnBindingContextChanged()
        {
            base.OnBindingContextChanged();

            try {
                DoctorModel doctor = (DoctorModel)BindingContext;

                _name.Text = doctor.Name;
                _openingHoursList.ItemsSource = doctor.OpeningHours;

                _streetAddress.Text     = doctor.Street;
                _postalCodeAddress.Text = doctor.PostalCode + " " + doctor.City;

                Geocoder gecoder   = new Geocoder();
                string   address   = doctor.Street + " " + doctor.PostalCode + " " + doctor.City;
                var      positions = await gecoder.GetPositionsForAddressAsync(address);

                List <Position> positionsArr = positions.ToList();

                if (positionsArr.Count > 0)
                {
                    Position position = positionsArr[0];                     // Latitude, Longitude

                    var mapSpan = MapSpan.FromCenterAndRadius(position, Distance.FromMiles(0.3));
                    var mapPin  = new Pin {
                        Type     = PinType.Place,
                        Position = position,
                        Label    = "custom pin",
                        Address  = "custom detail info"
                    };
                    _map.MoveToRegion(mapSpan);
                    _map.Pins.Add(mapPin);
                }
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine("EXception in Doctor Page OnBindingContextChanged,, {0}", e.ToString());
            }
        }
        public async void loadLatLng()
        {
            try
            {
                var timeout = TimeSpan.FromSeconds(1);
                var locator = CrossGeolocator.Current;
                if (locator.IsGeolocationEnabled)
                {
                    locator.DesiredAccuracy = 50;
                    int tm = 1000;
                    if (Device.OS == TargetPlatform.Android)
                    {
                        tm = 100000;
                    }
                    var position = await locator.GetPositionAsync(tm);

                    if (position != null)
                    {
                        Latitude  = position.Latitude.ToString();
                        Longitude = position.Longitude.ToString();

                        Geocoder geoCoder          = new Geocoder();
                        var      positionAds       = new Position(position.Latitude, position.Longitude);
                        var      possibleAddresses = await geoCoder.GetAddressesForPositionAsync(positionAds);

                        foreach (var address in possibleAddresses)
                        {
                            Address = address;
                            addressNumberTxt.Text = Address; break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 15
0
    // ---

    public static IPromise <LatLong> GetLatLongForAddress(string streetAddress, string city, string country)
    {
        // Get access singleton (object that holds a token and associated geocoder).
        MapboxAccess access   = MapboxAccess.Instance;
        Geocoder     geocoder = access.Geocoder;

        var promise = new Promise <LatLong>();

        string forwardGeocodeQuery = $"{streetAddress} {city} {country}";

        Debug.Log($"Performing forward geocode with query \"{forwardGeocodeQuery}\"");
        ForwardGeocodeResource forwardGeocode = new ForwardGeocodeResource(forwardGeocodeQuery);

        geocoder.Geocode(forwardGeocode, (ForwardGeocodeResponse response) => {
            /*
             * Debug.Log($"Forward geocode response has features:");
             * foreach (Feature feature in response.Features) {
             *  Debug.Log($" - {feature.Id} {feature.PlaceName} {feature.Address} {feature.Center}");
             * }
             */

            // There are lots of interesting types of features returned by the API, places, POIs, localities, etc.
            // I'm assuming they're ordered by relevance, so let's just pick the first one.
            if (response.Features.Count > 0)
            {
                Feature chosenFeature = response.Features[0];
                Vector2d coordinates  = chosenFeature.Center;
                promise.Resolve(new LatLong((float)coordinates.x, (float)coordinates.y));
            }
            else
            {
                promise.Resolve(new LatLong());
            }
        });

        return(promise);
    }
        public CreateInsideViewModel(INavigation navigation, int tripID)
        {
            _navigation     = navigation;
            _geoCoder       = new Geocoder();
            _currentWeather = _weather_sunny;

            _tripHistory              = new TripHistory();
            _tripHistory.Id           = tripID;
            _tripHistory.RegisterDate = DateTime.Now;

            //_imageDatas.Clear();
            //_imageDatas.Add(_tripHistory.Image1);
            //_imageDatas.Add(_tripHistory.Image2);
            //_imageDatas.Add(_tripHistory.Image3);
            //_imageDatas.Add(_tripHistory.Image4);
            //_imageDatas.Add(_tripHistory.Image5);
            //_imageDatas.Add(_tripHistory.Image6);
            //_imageDatas.Add(_tripHistory.Image7);
            //_imageDatas.Add(_tripHistory.Image8);
            //_imageDatas.Add(_tripHistory.Image9);
            //_imageDatas.Add(_tripHistory.Image10);

            //_cameraPictures.Add(Picture1);
            //_cameraPictures.Add(Picture2);
            //_cameraPictures.Add(Picture3);
            //_cameraPictures.Add(Picture4);
            //_cameraPictures.Add(Picture5);
            //_cameraPictures.Add(Picture6);
            //_cameraPictures.Add(Picture7);
            //_cameraPictures.Add(Picture8);
            //_cameraPictures.Add(Picture9);
            //_cameraPictures.Add(Picture10);

            InsideDate = GetInsideDateFromDateTime(_tripHistory.RegisterDate);

            OnPropertyChanged(_currentWeather);
        }
Exemplo n.º 17
0
        async Task <MapSpan> GeocoderPueblo()
        {
            var Pueblo = await FirebaseHelper.ObtenerPueblo(Comercio.IdPueblo);

            Geocoder geoCoder = new Geocoder();
            string   address  = Pueblo.Nombre + ", Andalucía, Spain";
            IEnumerable <Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(address);

            Position position = approximateLocations.FirstOrDefault();

            if (Comercio.Ubicacion != null)
            {
                return(new MapSpan(new Position(Comercio.Ubicacion.Latitud, Comercio.Ubicacion.Longitud), 0.001, 0.001));
            }
            else if (position == new Position(0, 0))
            {
                string direccion = Pueblo + ", Andalucía";
                IEnumerable <Position> direccionesAproximadas = await geoCoder.GetPositionsForAddressAsync(direccion);

                Position posicion = direccionesAproximadas.FirstOrDefault();
                if (posicion == new Position(0, 0) || Connectivity.NetworkAccess != NetworkAccess.Internet)
                {
                    stackMapa.IsVisible = false;
                    stackMapa.IsEnabled = false;
                    //Como hay que devolver un MapSpan, devuelvo la posición de Almería
                    return(new MapSpan(new Position(36.834047, -2.4637136), 0.001, 0.001));
                }
                else
                {
                    return(new MapSpan(posicion, 0.001, 0.001));
                }
            }
            else
            {
                return(new MapSpan(position, 0.001, 0.001));
            }
        }
Exemplo n.º 18
0
        protected override async Task Loaded()
        {
            if (_isLoadingFirstTime)
            {
                try
                {
                    var locator = CrossGeolocator.Current;
                    locator.DesiredAccuracy = 50;

                    var position = await locator.GetPositionAsync(10000);

                    var geoCoder = new Geocoder();
                    var address  = await geoCoder.GetAddressesForPositionAsync(new Position(position.Latitude, position.Longitude));

                    //var service = DependencyService.Get<IReverseGeocode>();
                    //var location = await service.ReverseGeoCodeLatLonAsync(position.Latitude, position.Longitude);

                    System.Diagnostics.Debug.WriteLine("---------- Location --------- :" + address.ToList().FirstOrDefault().ToString());

                    IsLoading           = true;
                    _isLoadingFirstTime = false;
                    var items = await ReferralItemServiceManager.DefaultInstance.GetItemsAsync();

                    foreach (var item in items)
                    {
                        ReferralItems.Add(item);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    IsLoading = false;
                }
            }
        }
Exemplo n.º 19
0
        async Task <string> ReverseGeocodeToConsoleAsync()
        {
            RunOnUiThread(() =>
            {
                if (String.IsNullOrEmpty(CompanyAddressMapActivity.CompanyLat) || String.IsNullOrEmpty(CompanyAddressMapActivity.CompanyLng))
                {
                    return;
                }
                CompanyAddressMapActivity.CompanyLat = CompanyAddressMapActivity.CompanyLat.Replace(',', '.');
                CompanyAddressMapActivity.CompanyLng = CompanyAddressMapActivity.CompanyLng.Replace(',', '.');
                double lat = Convert.ToDouble(CompanyAddressMapActivity.CompanyLat, CultureInfo.InvariantCulture);
                double lng = Convert.ToDouble(CompanyAddressMapActivity.CompanyLng, CultureInfo.InvariantCulture);

                var geo = new Geocoder(this);

                var addresses = geo.GetFromLocation(lat, lng, 1);
                addresses.ToList().ForEach((addr) =>
                {
                    //myNotationTemp = null;
                    RegionTemp             = null;
                    IndexTemp              = addr.PostalCode;
                    CountryTemp            = addr.CountryName;
                    CityTemp               = addr.Locality;
                    FullCompanyAddressTemp = addr.Thoroughfare;
                    if (addr.SubThoroughfare != null)
                    {
                        if (!addr.SubThoroughfare.Contains(addr.Thoroughfare))
                        {
                            FullCompanyAddressTemp += " " + addr.SubThoroughfare;
                        }
                    }
                });
                _reverseDoneYet = true;
            });

            return("");
        }
Exemplo n.º 20
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            var button = FindViewById <Button> (Resource.Id.geocodeButton);

            button.Click += (sender, e) => {
                new Thread(new ThreadStart(() => {
                    var geo = new Geocoder(this);

                    var addresses = geo.GetFromLocationName("50 Church St, Cambridge, MA", 1);

                    RunOnUiThread(() => {
                        var addressText = FindViewById <TextView> (Resource.Id.addressText);

                        addresses.ToList().ForEach((addr) => {
                            addressText.Append(addr.ToString() + "\r\n\r\n");
                        });
                    });
                })).Start();
            };
        }
Exemplo n.º 21
0
        public static async Task SetLocation(TelegramBotClient botHandle, Message source, GroupCollection matches)
        {
            var responseText = Strings.GeocodeDefault;

            if (!string.IsNullOrWhiteSpace(matches[2].Value))
            {
                var addresses = await Geocoder.GetAddresses(matches[2].Value);

                var address = addresses?.FirstOrDefault();

                if (address != null)
                {
                    await AddOrUpdateLocation(source.From.Id, address);

                    responseText = string.Format(Strings.GeocodeLocationSet, address.FormattedAddress);
                }
                else
                {
                    responseText = Strings.GeocodeNotFound;
                }
            }

            await botHandle.SendSmartTextMessageAsync(source, responseText);
        }
Exemplo n.º 22
0
        public async void loadMap()
        {
            try
            {
                var locator  = CrossGeolocator.Current;
                var position = await locator.GetPositionAsync(10000);

outer:
                if (position != null)
                {
                    customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude),
                                                                       Distance.FromMiles(1)));
                    ShopListPage.Lat1 = position.Latitude.ToString();
                    ShopListPage.Lng1 = position.Longitude.ToString();


                    Geocoder geoCoder          = new Geocoder();
                    var      positionAds       = new Position(position.Latitude, position.Longitude);
                    var      possibleAddresses = await geoCoder.GetAddressesForPositionAsync(positionAds);

                    foreach (var address in possibleAddresses)
                    {
                        addressLbl.Text = address;

                        break;
                    }
                }
                else
                {
                    goto outer;
                }
            }
            catch (Exception)
            {
            }
        }
        private async void pinTouched(object sender, EventArgs e)
        {
            Geocoder geoCoder  = new Geocoder();
            var      addresses = await geoCoder.GetAddressesForPositionAsync(this.Prez.Position);

            switch (Device.OS)
            {
            case TargetPlatform.iOS:
                Device.OpenUri(
                    new Uri(string.Format("http://maps.apple.com/?q={0}", WebUtility.UrlEncode(addresses.FirstOrDefault()))));
                break;

            case TargetPlatform.Android:
                Device.OpenUri(
                    new Uri(string.Format("geo:0,0?q={0}", WebUtility.UrlEncode(addresses.FirstOrDefault()))));
                break;

            case TargetPlatform.Windows:
            case TargetPlatform.WinPhone:
                Device.OpenUri(
                    new Uri(string.Format("bingmaps:?where={0}", Uri.EscapeDataString(addresses.FirstOrDefault()))));
                break;
            }
        }
Exemplo n.º 24
0
        public EventDetail(int eventId)
        {
            InitializeComponent();

            Services services = new Services();

            eventData = new Models.Event();

            try
            {
                eventData = services.getEvent(eventId);
            }
            catch (Exception exception)
            {
                Console.Write(exception);
                eventData = App.Database.GetEventAsync(eventId).Result;
            }

            BindingContext = eventData;

            if (eventData.eventLink.Length <= 0)
            {
                btnLink.IsVisible = false;
            }
            else
            {
                btnLink.IsVisible = true;
            }

            btnLink.Clicked += BtnLink_Clicked;
            btnRsvp.Clicked += BtnRsvp_Clicked;

            geocoder = new Geocoder();

            DoGeoCode(eventData.eventLocation, eventData.eventLocationName);
        }
Exemplo n.º 25
0
        async void getPosition(string address)
        {
            try
            {
                Geocoder gc = new Geocoder();
                IEnumerable <Position> possibleAddresses =
                    await gc.GetPositionsForAddressAsync(address);

                foreach (var result in possibleAddresses)
                {
                    AddShopPage.Latitude  = result.Latitude.ToString();
                    AddShopPage.Longitude = result.Longitude.ToString();

                    EditShopPage.Latitude  = result.Latitude.ToString();
                    EditShopPage.Longitude = result.Longitude.ToString();


                    break;
                }
            }
            catch
            {
            }
        }
Exemplo n.º 26
0
        //Sets location of appointment to current location, by assigning the longitude and latitude. Also navigates to TKMap to view location and map items
        private async void Current_Location()
        {
            var locator  = CrossGeolocator.Current;
            var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1));

            double lat_  = position.Latitude;
            double long_ = position.Longitude;

            Geocoder pos     = new Geocoder();
            Position pos_    = new Position(lat_, long_);
            var      address = await pos.GetAddressesForPositionAsync(pos_);


            ((Appointment)BindingContext).Latitude  = position.Latitude;
            ((Appointment)BindingContext).Longitude = position.Longitude;
            ((Appointment)BindingContext).Address   = address.First().ToString();
            DegMinSecConversion();
            var answer = await DisplayAlert("Would you like to view location on map?", null, "Yes", "No");

            if (answer)
            {
                await Navigation.PushAsync(new SamplePage(((Appointment)BindingContext).Longitude, ((Appointment)BindingContext).Latitude, (Appointment)BindingContext));
            }
        }
        private async Task <LatLng> GetLocationFromAddress(string strAddress)
        {
            if (string.IsNullOrEmpty(strAddress))
            {
                return(null);
            }

            #pragma warning disable 618
            var locale = (int)Build.VERSION.SdkInt < 25 ? MainContext.Resources?.Configuration?.Locale : MainContext.Resources?.Configuration?.Locales.Get(0) ?? MainContext.Resources?.Configuration?.Locale;
            #pragma warning restore 618
            Geocoder coder = new Geocoder(MainContext, locale);

            try
            {
                var address = await coder.GetFromLocationNameAsync(strAddress, 2);

                switch (address?.Count)
                {
                case > 0:
                    return(null !);
                }

                Address location = address[0];
                var     lat      = location.Latitude;
                var     lng      = location.Longitude;

                LatLng p1 = new LatLng(lat, lng);

                return(p1);
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
                return(null !);
            }
        }
Exemplo n.º 28
0
        public void OnLocationChanged(Location location)
        {
            var locationText = FindViewById <TextView> (Resource.Id.locationTextView);

            locationText.Text = String.Format("Latitude = {0}, Longitude = {1}", location.Latitude, location.Longitude);

            // demo geocoder

            new Thread(new ThreadStart(() => {
                var geocdr = new Geocoder(this);

                var addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

                //var addresses = geocdr.GetFromLocationName("Harvard University", 5);

                RunOnUiThread(() => {
                    var addrText = FindViewById <TextView> (Resource.Id.addressTextView);

                    addresses.ToList().ForEach((addr) => {
                        addrText.Append(addr.ToString() + "\r\n\r\n");
                    });
                });
            })).Start();
        }
Exemplo n.º 29
0
        public async void bindLocation()
        {
            try
            {
                this.geocoder = new Geocoder();

                this.locator = CrossGeolocator.Current;

                locator.DesiredAccuracy = 50;

                position = await locator.GetPositionAsync(new TimeSpan(10000));

                Xamarin.Forms.Maps.Position oPosition = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);

                IEnumerable <string> cAddress = await geocoder.GetAddressesForPositionAsync(oPosition);

                string Address   = cAddress.First();
                var    aAddress  = Address.Split('\n');
                string cEndereco = aAddress[0].Split(',')[0];
                string cNumero   = aAddress[0].Split(',')[1].Split('-')[0];
                string cBairro   = aAddress[0].Split(',')[1].Split('-')[1];

                this.oEmpresa.endereco = cEndereco + ", " + cNumero;
                this.oEmpresa.bairro   = cBairro;

                this.endereco.Text = oEmpresa.endereco;
                this.bairro.Text   = oEmpresa.bairro;
            }
            catch (Exception ex)
            {
                //Android.Util.Log.Error("AppSA error", ex.Message);
                position           = new Plugin.Geolocator.Abstractions.Position();
                position.Latitude  = -22.2046169;
                position.Longitude = -49.9743474;
            }
        }
Exemplo n.º 30
0
        public void SendMessage(string foo)
        {
            Location currentLocation;
            string   addressText  = "Unable to determine the address.";
            string   locationText = "Unable to determine your location.";

            Address address = null;

            try
            {
                currentLocation = _locationManager.GetLastKnownLocation(_locationProvider);
                if (currentLocation != null)
                {
                    locationText = string.Format("{0:f6},{1:f6}", currentLocation.Latitude, currentLocation.Longitude);
                    Geocoder        geocoder    = new Geocoder(Application.Context);
                    IList <Address> addressList = geocoder.GetFromLocation(currentLocation.Latitude, currentLocation.Longitude, 10);
                    address = addressList.FirstOrDefault();

                    if (address != null)
                    {
                        StringBuilder deviceAddress = new StringBuilder();
                        for (int i = 0; i < address.MaxAddressLineIndex; i++)
                        {
                            deviceAddress.AppendLine(address.GetAddressLine(i));
                        }
                        // Remove the last comma from the end of the address.
                        addressText = deviceAddress.ToString();
                    }
                }
            }
            catch
            {
            }

            Android.Telephony.SmsManager.Default.SendTextMessage("2623092186", null, "Message from " + locationText + " address: " + addressText + " device " + foo, null, null);
        }
Exemplo n.º 31
0
        public async void textChange()
        {
            try
            {
                await Navigation.PushPopupAsync(new Loader());

                Geocoder geoCoder          = new Geocoder();
                var      positionAds       = new Position(Convert.ToDouble(ShopListPage.Lat1), Convert.ToDouble(ShopListPage.Lng1));
                var      possibleAddresses = await geoCoder.GetAddressesForPositionAsync(positionAds);

                foreach (var address in possibleAddresses)
                {
                    addressLbl.Text = "";
                    addressLbl.Text = address;

                    break;
                }
                Loader.CloseAllPopup();
            }
            catch (Exception)
            {
                Loader.CloseAllPopup();
            }
        }
Exemplo n.º 32
0
        public bool Initialise()
        {
            if (_locManager != null)
            {
                return(true);
            }

            try
            {
                _locManager = _activity.GetSystemService(Context.LocationService) as LocationManager;
                _geocoder   = new Geocoder(_activity);

                var criteria = new Criteria()
                {
                    Accuracy = Accuracy.NoRequirement
                };
                string bestProvider = _locManager.GetBestProvider(criteria, true);

                var lastKnownLocation = _locManager.GetLastKnownLocation(bestProvider);

                if (lastKnownLocation != null)
                {
                    OnLocationUpdated(lastKnownLocation);
                }

                _locManager.RequestLocationUpdates(bestProvider, 5000, 2, this);
                _locManager.RequestLocationUpdates("gps", 5000, 2, this);

                return(true);
            }
            catch (Exception)
            {
                Toast.MakeText(_activity, Resource.String.error_LocationUnavailable, ToastLength.Long).Show();
                return(false);
            }
        }
Exemplo n.º 33
0
        protected async void ButtonShowMap_Clicked(object sender, EventArgs e)
        {
            // puke
            //await Navigation.PushAsync(new CustomerMapPage());
            Geocoder      geoCoder        = new Geocoder();
            StringBuilder customerAddress = new StringBuilder();
            Pin           pin             = new Pin();

            customerAddress.Append(_vm.AddressLine1);
            customerAddress.Append(", ");
            customerAddress.Append(_vm.City);
            customerAddress.Append(", ");
            customerAddress.Append(_vm.State);
            customerAddress.Append(" ");
            customerAddress.Append(_vm.ZipCode);

            try
            {
                var location = await geoCoder.GetPositionsForAddressAsync(customerAddress.ToString());

                //var address = await geoCoder.GetAddressesForPositionAsync(new Position(39.909606, -76.299061));
                List <Position> approximateLocation = location.ToList();
                pin.Position = approximateLocation[0];
                pin.Label    = _vm.CustomerName;
                pin.Address  = customerAddress.ToString();

                await Navigation.PushAsync(new CustomerMapPage(pin));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                await DisplayAlert("Invalid Location", "Address cannot be mapped.", "OK");

                return;
            }
        }
Exemplo n.º 34
0
        private async Task LocalizarNoMapa(string param)
        {
            Geocoder geocoder = new Geocoder();
            Task <IEnumerable <Position> > resultado =
                geocoder.GetPositionsForAddressAsync(param);

            IEnumerable <Position> posicoes = await resultado;

            foreach (Position item in posicoes)
            {
                meuMapa.MoveToRegion(MapSpan.FromCenterAndRadius(item, Distance.FromMiles(5.0)));

                meuMapa.Pins.Clear();
                var pin = new Pin
                {
                    Type     = PinType.Generic,
                    Position = item,
                    Label    = "Localização",
                    Address  = txtPesquisa.Text
                };
                meuMapa.Pins.Add(pin);
                break;
            }
        }
Exemplo n.º 35
0
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.SelectLocation);

            var locationManager = (LocationManager)this.GetSystemService(LocationService);
            var geoCoder        = new Geocoder(this);

            this.listView = this.FindViewById <ListView>(Resource.Id.listViewSelectLocations);

            try
            {
                this.coreApplicationContext = CentralStation.Instance.Ainject.ResolveType <ICoreApplicationContext>();
                locationManager.RegisterLocationManager(this, this.coreApplicationContext);

                this.viewModel = CentralStation.Instance.Ainject.ResolveType <ISelectLocationViewModel>();
                IList <TrackLocation> currentLocations = this.viewModel.ResolveCurrentLocations(geoCoder);

                this.listView.Adapter = new TrackLocationListAdapter(this, currentLocations);
                //this.listView.TextFilterEnabled = true;

                this.listView.ItemClick += (sender, e) =>
                {
                    var backToMain = new Intent(this, typeof(CompleteLocationInput));
                    var item       = currentLocations[e.Position];
                    CentralStation.Instance.Ainject.ResolveType <ITimeTrackerWorkspace>().SaveTrackLocation(item);
                    backToMain.PutExtra("LocationId", item.ID);

                    this.StartActivity(backToMain);
                };
            }
            catch (Exception ex)
            {
                Log.Error(this.GetType().Name, ex.StackTrace);
            }
        }
Exemplo n.º 36
0
        public void OnLocationChanged(Location location)
        {
            if (mMap != null)
            {
                // Set current location address and set to origin textfield
                geocoder = new Geocoder(this);
                IList <Address> addresses = geocoder.GetFromLocation(location.Latitude, location.Longitude, 1);
                originTxt = addresses[0].SubLocality;
                originAutocompleteFragment.SetText(addresses[0].GetAddressLine(0));
                locationManager.RemoveUpdates(this);

                // Move camera to user current location
                LatLng latLng = new LatLng(location.Latitude, location.Longitude);
                originLatLng = latLng;
                CameraUpdate cameraUpdate = CameraUpdateFactory.NewLatLngZoom(latLng, 18);
                mMap.AddMarker(new MarkerOptions().SetPosition(originLatLng).SetTitle("Origin"));
                mMap.MoveCamera(cameraUpdate);

                RunOnUiThread(() =>
                {
                    progress.Dismiss();
                });
            }
        }
        public async void OnLocationChanged(Location location)
        {
            TextView locationText = FindViewById <TextView>(Resource.Id.locationTextView);

            locationText.Text = String.Format("Latitude = {0:N5}, Longitude = {1:N5}", location.Latitude, location.Longitude);

            Geocoder geocdr = new Geocoder(this);
            Task <IList <Address> > getAddressTask = geocdr.GetFromLocationAsync(location.Latitude, location.Longitude, 5);
            TextView addressTextView = FindViewById <TextView>(Resource.Id.addressTextView);

            addressTextView.Text = "Trying to reverse geo-code the latitude/longitude...";

            IList <Address> addresses = await getAddressTask;

            if (addresses.Any())
            {
                Address addr = addresses.First();
                addressTextView.Text = FormatAddress(addr);
            }
            else
            {
                Toast.MakeText(this, "Could not reverse geo-code the location", ToastLength.Short).Show();
            }
        }