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);
            }
        }
        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 ();
            };
        }
Beispiel #3
0
        public static async Task <IEnumerable <Position> > GetPositionsForAddressAsync(string address)
        {
            var             geocoder  = new AGeocoder(Forms.Context);
            IList <Address> addresses = await geocoder.GetFromLocationNameAsync(address, 5);

            return(addresses.Select(p => new Position(p.Latitude, p.Longitude)));
        }
        public IList<TrackLocation> GenerateListOfTrackLocations(Coordinate currentLocation, Geocoder geocoder)
        {
            var listAddresses = geocoder.GetFromLocation(currentLocation.Latitude, currentLocation.Longitude, 30);
            IList<TrackLocation> returnList = new List<TrackLocation>();

            returnList.Add(new TrackLocation
                               {
                                   Latitude = currentLocation.Latitude,
                                   Longitude = currentLocation.Longitude
                               });

            foreach (var address in listAddresses)
            {
                returnList.Add(new TrackLocation
                                   {
                                       City = address.Locality,
                                       Country = address.CountryName,
                                       PostalCode = address.PostalCode,
                                       Street = address.Thoroughfare,
                                       HouseNumber = address.FeatureName,
                                       Latitude = address.Latitude,
                                       Longitude = address.Longitude
                                   });
            }

            return returnList;
        }
 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 ();
 }
Beispiel #6
0
 public Locator(Activity ctx)
 {
     this.ctx = ctx;
     locationManager = (LocationManager)ctx.GetSystemService (Context.LocationService);
     locationManager.RequestLocationUpdates (LocationManager.PassiveProvider, 5 * 60 * 1000, 2, this);
     if (Geocoder.IsPresent)
         geocoder = new Geocoder (ctx);
 }
Beispiel #7
0
        public void OnLocationChanged(Location location)
        {
            var geocoder = new Geocoder (this, Java.Util.Locale.Default);
            var addresses = geocoder.GetFromLocation (location.Latitude, location.Longitude, 1);

            if (addresses.Count > 0)
            {
                app.UserCity.OnNext(addresses [0].Locality);
            }
        }
 public static async Task<IEnumerable<string>> GetAddressesForPositionAsync(Position position)
 {
     var geocoder = new AGeocoder(Forms.Context);
     IList<Address> addresses = await geocoder.GetFromLocationAsync(position.Latitude, position.Longitude, 5);
     return addresses.Select(p =>
     {
         IEnumerable<string> lines = Enumerable.Range(0, p.MaxAddressLineIndex + 1).Select(p.GetAddressLine);
         return string.Join("\n", lines);
     });
 }
Beispiel #9
0
        public static async Task <IEnumerable <string> > GetAddressesForPositionAsync(Position position)
        {
            var             geocoder  = new AGeocoder(Forms.Context);
            IList <Address> addresses = await geocoder.GetFromLocationAsync(position.Latitude, position.Longitude, 5);

            return(addresses.Select(p =>
            {
                IEnumerable <string> lines = Enumerable.Range(0, p.MaxAddressLineIndex + 1).Select(p.GetAddressLine);
                return string.Join("\n", lines);
            }));
        }
        /// <summary>
        /// Gets the list of current track locations to add.
        /// </summary>
        /// <param name="geocoder">The geocoder.</param>
        /// <returns></returns>
        public IList<TrackLocation> GetListOfCurrentTrackLocationsToAdd(Geocoder geocoder)
        {
            IList<TrackLocation> returnList = new List<TrackLocation>();

            if (this.CurrentLocation != null)
            {
                returnList = this.coordinateGeocoder.GenerateListOfTrackLocations(this.CurrentLocation, geocoder);
            }

            return returnList;
        }
Beispiel #11
0
        public CustomMapRendererAndroid()
        {
            geocoder = new Android.Locations.Geocoder(FormsActivity);

            locMgr = (LocationManager)FormsActivity.GetSystemService(Activity.LocationService);

            locCriteria          = new Criteria();
            locCriteria.Accuracy = Accuracy.Fine;

            polylineList = new List <Polyline>();
            markerList   = new List <Marker>();
        }
Beispiel #12
0
        public void OnLocationChanged(Location location)
        {
            if (MainActivity.isStarted)
            {
            try
            {
                _currentLocation = location;

                if (_currentLocation == null)
                    _location = "Unable to determine your location.";
                else
                {
                    _location = String.Format("{0},{1}", _currentLocation.Latitude, _currentLocation.Longitude);
                //	MainActivity.latitude = _currentLocation.Latitude;
                //	MainActivity.longitude = _currentLocation.Longitude;
                    Geocoder geocoder = new Geocoder(this);
                    IList<Address> addressList = geocoder.GetFromLocation(_currentLocation.Latitude, _currentLocation.Longitude, 10);
                    Address addressCurrent = addressList.FirstOrDefault();
                    if (addressCurrent != null)
                    {
                            StringBuilder deviceAddress = new StringBuilder();

                            for (int i = 0; i < addressCurrent.MaxAddressLineIndex; i++)
                                    deviceAddress.Append(addressCurrent.GetAddressLine(i))
                                        .AppendLine(",");

                            _address = deviceAddress.ToString();
                    }
                    else
                            _address = "Unable to determine the address.";

                    MainActivity.address = _address;

                    MainActivity.latitude = _currentLocation.Latitude;
                    MainActivity.longitude = _currentLocation.Longitude;

                    Intent intent = new Intent(this, typeof(GetGps.GPSServiceReciever));
                    intent.SetAction(GetGps.GPSServiceReciever.LOCATION_UPDATED);
                    intent.AddCategory(Intent.CategoryDefault);
                    intent.PutExtra("Location", _location);
                    SendBroadcast(intent);
                        MainActivity.isStarted = false;
                    StopSelf();
                }
            }

            catch (Exception)
            {
                //_address = "Unable to determine the address.";
            }

            }
        }
		protected override void OnHandleIntent (Android.Content.Intent intent)
		{
			var errorMessage = string.Empty;

			mReceiver = intent.GetParcelableExtra (Constants.Receiver) as ResultReceiver;

			if (mReceiver == null) {
				Log.Wtf (TAG, "No receiver received. There is nowhere to send the results.");
				return;
			}

			var location = intent.GetParcelableExtra (Constants.LocationDataExtra) as Location;

			if (location == null) {
				errorMessage = GetString (Resource.String.no_location_data_provided);
				Log.Wtf (TAG, errorMessage);
				DeliverResultToReceiver (Result.FirstUser, errorMessage);
				return;
			}

			var geocoder = new Geocoder (this, Java.Util.Locale.Default);

			List<Address> addresses = null;

			try {
				addresses = new List<Address> (geocoder.GetFromLocation (location.Latitude, location.Longitude, 1));
			} catch (IOException ioException) {
				errorMessage = GetString (Resource.String.service_not_available);
				Log.Error (TAG, errorMessage, ioException);
			} catch (IllegalArgumentException illegalArgumentException) {
				errorMessage = GetString (Resource.String.invalid_lat_long_used);
				Log.Error (TAG, string.Format ("{0}. Latitude = {1}, Longitude = {2}", errorMessage, location.Latitude, location.Longitude), illegalArgumentException);
			}

			if (addresses == null || addresses.Count == 0) {
				if (string.IsNullOrEmpty (errorMessage)) {
					errorMessage = GetString (Resource.String.no_address_found);
					Log.Error (TAG, errorMessage);
				}
				DeliverResultToReceiver (Result.FirstUser, errorMessage);
			} else {
				var address = addresses.FirstOrDefault ();
				var addressFragments = new List<string> ();

				for (int i = 0; i < address.MaxAddressLineIndex; i++) {
					addressFragments.Add (address.GetAddressLine (i));
				}
				Log.Info (TAG, GetString (Resource.String.address_found));
				DeliverResultToReceiver (Result.Canceled,
					string.Join ("\n", addressFragments));
			}
		}
        public void OnLocationChanged(Location location) {
            try {
                _currentLocation = location;

                if (_currentLocation == null)
                    _location = "Unable to determine your location.";
                else {
                    _location = String.Format("{0},{1}", _currentLocation.Latitude, _currentLocation.Longitude);

                    Geocoder geocoder = new Geocoder(this);

                    //The Geocoder class retrieves a list of address from Google over the internet
                    IList<Address> addressList = geocoder.GetFromLocation(_currentLocation.Latitude, _currentLocation.Longitude, 10);

                    Address addressCurrent = addressList.FirstOrDefault();

                    if (addressCurrent != null) {
                        StringBuilder deviceAddress = new StringBuilder();

                        for (int i = 0; i < addressCurrent.MaxAddressLineIndex; i++)
                            deviceAddress.Append(addressCurrent.GetAddressLine(i))
                                .AppendLine(",");

                        _address = deviceAddress.ToString();
                    }
                    else
                        _address = "Unable to determine the address.";

                    IList<Address> source = geocoder.GetFromLocationName(_sourceAddress, 1);
                    Address addressOrigin = source.FirstOrDefault();

                    var coord1 = new LatLng(addressOrigin.Latitude, addressOrigin.Longitude);
                    var coord2 = new LatLng(addressCurrent.Latitude, addressCurrent.Longitude);

                    var distanceInRadius = Utils.HaversineDistance(coord1, coord2, Utils.DistanceUnit.Miles);

                    _remarks = string.Format("Your are {0} miles away from your original location.", distanceInRadius);

                    Intent intent = new Intent(this,typeof(GPSServiceReciever));
                    intent.SetAction(GPSServiceReciever.LOCATION_UPDATED);
                    intent.AddCategory(Intent.CategoryDefault);
                    intent.PutExtra("Location", _location);
                    intent.PutExtra("Address", _address);
                    intent.PutExtra("Remarks", _remarks);
                    SendBroadcast(intent);
                }
            }
            catch (Exception ex){
                _address = "Unable to determine the address.";
            }

        }
Beispiel #15
0
		async void AddressButton_OnClick()//(object sender, EventArgs eventArgs)
		{



			if (_currentLocation == null)
			{
				//_addressText.Text = "Can't determine the current address.";

				strCoordinates = "Can't determine the current location.";
				strStreet = "Can't determine the current address.";

				MainActivity.problems [MainActivity.index].ProblemsItems.SetCoordinates (strCoordinates);
				MainActivity.problems [MainActivity.index].ProblemsItems.SetStreet (strStreet);

				MainActivity.problems [MainActivity.index].ProblemsItems.WriteCoordinates (strCoordinates);
				MainActivity.problems [MainActivity.index].ProblemsItems.WriteStreet (strStreet);


				return;
			}

			Geocoder geocoder = new Geocoder(this);
			IList<Address> addressList = await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);

			Address address = addressList.FirstOrDefault();
			if (address != null)
			{
				StringBuilder deviceAddress = new StringBuilder();
				for (int i = 0; i < address.MaxAddressLineIndex; i++)
				{
					deviceAddress.Append(address.GetAddressLine(i))
						.AppendLine(",");
				}
				//MainActivity.list.AddStreet (deviceAddress.ToString ());

				//MainActivity.listStreet.AddItem(deviceAddress.ToString ());
				strStreet = deviceAddress.ToString ();

			}
			else
			{
				//MainActivity.list.AddStreet ("Unable to determine the address.");

			//	MainActivity.listStreet.AddItem ("Unable to determine the address.");
			
				strStreet = "Unable to determine the address.";
			}

			MainActivity.problems [MainActivity.index].ProblemsItems.SetStreet (strStreet);
			MainActivity.problems [MainActivity.index].ProblemsItems.WriteStreet (strStreet);
		}
		public async Task<string> GetLocation( double lat, double lon )
		{
			var geo = new Geocoder (MainActivity.GetMainActivity());
			var addresses = await geo.GetFromLocationAsync (lat, lon, 1);
			if (addresses != null) 
			{
				foreach (var item in addresses)
				{
					string address =  "@" + item.Thoroughfare + " " + item.SubLocality + "  " + item.SubAdminArea + "  " + item.AdminArea +  "  " + item.CountryName;
					return address;
				}
			}
			return null;
		}
        protected override void OnHandleIntent(Intent intent)
        {
            string errorMessage = "";
            // Get the location passed to this service through an extra.
            var location = intent.GetParcelableExtra(Constants.LOCATION_DATA_EXTRA).JavaCast<Location>();
            var geocoder = new Geocoder(this, Java.Util.Locale.Default);
            IList<Address> addresses = null;
            try
            {
                // In this sample, get just a single address.
                addresses = geocoder.GetFromLocation(location.Latitude, location.Longitude, 1);
            }
            catch (Java.IO.IOException ioException)
            {
                // Catch network or other I/O problems.
                errorMessage = "service not available";
                Console.WriteLine("{0} {1}", errorMessage, ioException.ToString());
            }
            catch (Java.Lang.IllegalArgumentException illegalArgumentException)
            {
                // Catch invalid latitude or longitude values.
                errorMessage = "invalid lat long used. " + "Latitude = " + location.Latitude + ", Longitude = " + location.Longitude;
                Console.WriteLine("{0} {1}", errorMessage, illegalArgumentException.ToString());
            }

            // Handle case where no address was found.
            if (addresses == null || addresses.Count == 0)
            {
                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = "no address found";
                    Console.WriteLine(errorMessage);
                }
                DeliverResultToReceiver(GeocodingResult.Failure, errorMessage);
            }
            else
            {
                Address address = addresses[0];
                var addressFragments = new List<string>();
                // Fetch the address lines using getAddressLine,
                // join them, and send them to the thread.
                for (int i = 0; i < address.MaxAddressLineIndex; i++)
                {
                    addressFragments.Add(address.GetAddressLine(i));
                }
                Console.WriteLine("address_found");
                DeliverResultToReceiver(GeocodingResult.Success, addressFragments);
            }
        }
        public void OnLocationChanged(Location location)
        {
            _latEditText.Text = location.Latitude.ToString();
              _longEditText.Text = location.Longitude.ToString();

              // Reverse GeoCoding
              Geocoder geocdr = new Geocoder(this);
              IList<Address> addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

              if (addresses.Any())
              {
            UpdateAddressFields(addresses.First());
              }

              // Cancel Progress Dialog
              _progressDialog.Cancel();
              _obtainingLocation = false;
        }
		public void OnLocationChanged (Location location)
		{
			TextView locationText = FindViewById<TextView> (Resource.Id.locationTextView);

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

			Task.Factory.StartNew (() => {
				// Do the reverse geocoding on a background thread.
				Geocoder geocdr = new Geocoder (this);
				IList<Address> addresses = geocdr.GetFromLocation (location.Latitude, location.Longitude, 5);
				return addresses;
			})
				.ContinueWith (task => {
				TextView addrText = FindViewById<TextView> (Resource.Id.addressTextView);
				task.Result.ToList ().ForEach ((addr) => addrText.Append (addr.ToString () + "\r\n\r\n"));

			}, TaskScheduler.FromCurrentSynchronizationContext ());
		}
Beispiel #20
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

                        SetContentView (Resource.Layout.Main);

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

                        button.Click += async (sender, e) => {
                                var geo = new Geocoder (this);
                                var addresses = await geo.GetFromLocationAsync (42.37419, -71.120639, 1);

                                var addressText = FindViewById<TextView> (Resource.Id.addressText);
                                if (addresses.Any ()) {
                                        addresses.ToList ().ForEach (addr => addressText.Append (addr + System.Environment.NewLine + System.Environment.NewLine));
                                } else {
                                        addressText.Text = "Could not find any addresses.";
                                }
                        };
        }
        public async Task<GeoLocation> GetLocationAsync(string address, CancellationToken ct = default(CancellationToken))
        {
            var globals = Mvx.Resolve<IMvxAndroidGlobals>();
            var geocoder = new Geocoder(globals.ApplicationContext);

            var addresses = await geocoder.GetFromLocationNameAsync(address, 1);

            var first = addresses.FirstOrDefault();

            if (first == null)
            {
                throw new Exception("No results found");
            }

            return new GeoLocation()
            {
                Lat = first.Latitude.ToString(CultureInfo.InvariantCulture),
                Lng = first.Longitude.ToString(CultureInfo.InstalledUICulture)
            };
        }
        public void OnLocationChanged(Location location)
        {
            TextView locationText = FindViewById<TextView>(Resource.Id.locationTextView);

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

            // demo geocoder

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

                IList<Address> addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

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

                    addresses.ToList().ForEach((addr) => addrText.Append(addr.ToString() + "\r\n\r\n"));
                });
            }).Start();
        }
        public void OnLocationChanged(Android.Locations.Location location)
        {
            Log.Debug (tag, "Location changed");
            var lat = location.Latitude;
            var lng = location.Longitude;
            var geo = new Geocoder (this);
            List<Address> getAddress = new List<Address>(geo.GetFromLocation(lat,lng,1));
            Address returnedAddress = getAddress.FirstOrDefault();
            if (returnedAddress != null) {
                System.Text.StringBuilder strReturnedAddress = new StringBuilder ();
                for (int i = 0; i < returnedAddress.MaxAddressLineIndex; i++) {
                    strReturnedAddress.Append (returnedAddress.GetAddressLine (i)).AppendLine (" ");
                }
                loc.Text = strReturnedAddress.ToString ();
                getLoc.Text = "My Location";
                pos1 = new Xamarin.Forms.Labs.Services.Geolocation.Position()
                {
                    Latitude = location.Latitude,
                    Longitude = location.Longitude
                };

                //determine whether closer to los gatos or palo alto
                if (loc.Text.Contains("Palo Alto")) {
                    town = false;
                    getSpot.Enabled = true;
                } else if (loc.Text.Contains("Los Gatos")) {
                    town = true;
                    getSpot.Enabled = true;
                } else {
                    //set alert for executing the task
                    AlertDialog.Builder alert = new AlertDialog.Builder (this);
                    alert.SetTitle ("Sorry, you are too far from Palo Alto or Los Gatos");
                    alert.SetNeutralButton ("OK", (senderAlert, args) => {} );
                    //run the alert in UI thread to display in the screen
                    RunOnUiThread (() => {
                        alert.Show();
                    });
                }
            }
        }
Beispiel #24
0
        async void FakeAddressButton_OnClick(object sender, EventArgs e)
        {
            string message = "";
            double lat;
            bool tryLat = double.TryParse(latInput.Text, out lat);
            double lon;
            bool tryLong = double.TryParse(longInput.Text, out lon);

            try
            {
                if (tryLat == false || tryLong == false)
                {
                    message = "Unable to determine the address or input is invalid.";
                }
                else
                {
                    Geocoder geocoder = new Geocoder(this);
                    IList<Address> addList = await geocoder.GetFromLocationAsync(lat, lon, 10);
                    Address add = addList.FirstOrDefault();

                    if (add != null)
                    {
                        StringBuilder deviceAddress = new StringBuilder();
                        for (int i = 0; i < add.MaxAddressLineIndex; i++)
                        {
                            deviceAddress.Append(add.GetAddressLine(i)).AppendLine(",");
                        }
                        fakeAddress.Text = deviceAddress.ToString();
                    }
                    else
                    {
                        fakeAddress.Text = string.Format("{0}", message);
                    }
                }
            }
            catch (Exception ex)
            {
                fakeAddress.Text = ex.Message;
            }
        }
        public Task <IList <Address> > GetFromLocationNameAsync(Context context, string locationName, int maxResults,
                                                                CancellationToken?token)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!token.HasValue)
            {
                token = CancellationToken.None;
            }

            return(Task.Run(() =>
            {
                if (Android.Locations.Geocoder.IsPresent)
                {
                    IList <Address> result;
                    using (var geo = new Android.Locations.Geocoder(context))
                    {
                        try
                        {
                            result = geo.GetFromLocationName(locationName, maxResults);
                        }
                        catch (Java.IO.IOException ex)
                        {
                            _log.DebugFormat("Geocoder bug. {0}", ex);
                            return GetFromLocationName(locationName, maxResults, token);
                        }
                    }

                    if (result != null && result.Count > 0)
                    {
                        return result;
                    }
                }

                return GetFromLocationName(locationName, maxResults, token);
            }, token.Value));
        }
        protected override void OnCreate(Bundle bundle)
        {
            // get the geolocation, then the address from it
            // to ensure something is in there, if location is dead, you're at the home of football - Anfield

            List<double> location = new List<double> ();
            List<string> address = new List<string> ();

            var geocoder = new Geocoder (this, Java.Util.Locale.Default);
            var locationManager = (LocationManager)GetSystemService (LocationService);

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

            Location lastKnownLocation = locationManager.GetLastKnownLocation (bestProvider);
            if (lastKnownLocation != null) {
                location.Add (lastKnownLocation.Latitude);
                location.Add (lastKnownLocation.Longitude);
            } else {
                if (AndroidData.GeoLocation == null) {
                    location.Add (53.430808);
                    location.Add (-2.961709);
                } else
                    location = AndroidData.GeoLocation;
            }

            // get the address for where you are

            var addr = geocoder.GetFromLocation (location [0], location [1], 1);

            address.Add (addr [0].Premises);
            address.Add (addr [0].Locality);
            address.Add (addr [0].CountryName);

            AndroidData.GeoLocation = location;
            AndroidData.GeoLocationAddress = address;
            AndroidData.GeoLocationUpdate = System.DateTime.Now;

            Finish ();
        }
		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();
			}
		}
		async Task<LocationData> ReverseGeocodeCurrentLocation(Location location)
		{
			return await Task.Run<LocationData>(async()=>{

				var geocoder = new Geocoder(EmpleadoApp.AppContext);

				var addressList =
					await geocoder.GetFromLocationAsync(location.Latitude, location.Longitude, 10);

				var address = addressList.FirstOrDefault();

				var locationData = new LocationData
				{
					UserCity = address.Locality,
					UserCountry = address.AdminArea,
					UserStreet = address.Thoroughfare,
					PostalCode = address.PostalCode
				};

				return locationData;

			});
		}
		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);

		}
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Coloca o layout "main" dos recursos em nossa view
			SetContentView (Resource.Layout.Main);

			// Pega o botão do recurso de layout e coloca um evento nele
			Button usa_gps = FindViewById<Button> (Resource.Id.usa_gps);
			usa_acelerometro = FindViewById<TextView> (Resource.Id.usa_acelerometro);
			gps_coordinates = FindViewById<TextView> (Resource.Id.gps_coordinates);
			gps_location = FindViewById<TextView> (Resource.Id.gps_location);

			sensorManager = (SensorManager)GetSystemService (Context.SensorService);
			InitializeLocationManager ();	

			usa_gps.Click += async delegate {
				if (currentLocation == null)
					return;

				Geocoder geocoder = new Geocoder (this);
				IList<Address> addressList = await geocoder.GetFromLocationAsync (
					                             currentLocation.Latitude, currentLocation.Longitude, 10);
				Address address = addressList.FirstOrDefault ();
				if (address != null) {
					StringBuilder deviceAddress = new StringBuilder ();
					for (int i = 0; i < address.MaxAddressLineIndex; i++) {
						deviceAddress.Append (address.GetAddressLine (i)).AppendLine (",");
					}

					gps_location.Text = deviceAddress.ToString ();
				} else {
					gps_location.Text = "Não foi possível localizar esta posição";
				}

			};
		}
        //http://blog.csdn.net/litton_van/article/details/7101422
        //http://blog.csdn.net/i_lovefish/article/details/7948215

        public async Task<string> GetCityNameAsync() {
            var lm = LocationManager.FromContext(Forms.Context);

            Criteria criteria = new Criteria();
            criteria.Accuracy = Accuracy.Low;   //高精度    
            criteria.AltitudeRequired = false;    //不要求海拔    
            criteria.BearingRequired = false; //不要求方位    
            criteria.CostAllowed = false; //不允许有话费    
            criteria.PowerRequirement = Power.Low;   //低功耗  

            var provider = lm.GetBestProvider(criteria, true);

            var loc = lm.GetLastKnownLocation(provider);//LocationManager.GpsProvider
            if (loc != null) {
                using (var g = new Geocoder(Forms.Context)) {
                    var addrs = await g.GetFromLocationAsync(loc.Latitude, loc.Longitude, 1);
                    if (addrs != null && addrs.Count > 0) {
                        var addr = addrs.First();
                        return addr.Locality;
                    }
                }
            }
            return "深圳";
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.location_demo);

            _builder = new StringBuilder();
            _geocoder = new Geocoder(this);
            _locationText = FindViewById<TextView>(Resource.Id.location_text);
            _locationManager = (LocationManager)GetSystemService(LocationService);

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

            Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);

            if (lastKnownLocation != null)
            {
                _locationText.Text = string.Format("Last known location, lat: {0}, long: {1}",
                                                   lastKnownLocation.Latitude, lastKnownLocation.Longitude);
            }

            _locationManager.RequestLocationUpdates(bestProvider, 5000, 2, this);
        }
        IList<TrackLocation> ISelectLocationViewModel.ResolveCurrentLocations(Geocoder geoCoder)
        {
            IList<TrackLocation> locations = this.coreApplicationContext.GetListOfCurrentTrackLocationsToAdd(geoCoder);

            return locations;
        }
			public AddressFilter (Context context, AddressCompletionAdapter adapter)
			{
				this.adapter = adapter;
				this.geocoder = new Geocoder (context);
			}