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."; } }
public static double HaversineDistance(LatLng coord1, LatLng coord2, DistanceUnit unit) { double R = (unit == DistanceUnit.Miles) ? 3960 : 6371; var lat = (coord2.Latitude - coord1.Latitude).ToRadian(); var lng = (coord2.Longitude - coord1.Longitude).ToRadian(); var h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) + Math.Cos(coord1.Latitude.ToRadian()) * Math.Cos(coord2.Latitude.ToRadian()) * Math.Sin(lng / 2) * Math.Sin(lng / 2); var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1))); return R * h2; }