Reputation: 297
I am currently getting a location using MVVMCross for android using the code below. I am handling the location update on the view using a Command to access the GeoCoder object & fetch the address data. I have taken some code from this question on SO but it seems that the ViewModel resides in the same project and not in the core. I wanted to know if this is the right way of achieving this or should I be using another approach
View Model `
public IMvxCommand LocationUpdate { get; set; }
public LocationViewModel(IMvxLocationWatcher locationWatcher)
{
_locationWatcher = locationWatcher;
FindCurrentLocation();
_timer = new Timer(OnTick, null, 1000, 1000);
}
private void OnLocation(MvxGeoLocation location)
{
Lat = location.Coordinates.Latitude;
Lng = location.Coordinates.Longitude;
if(LocationUpdate != null)
LocationUpdate.Execute();
_locationFound = true;
_locationWatcher.Stop();
}
private void FindCurrentLocation()
{
_locationFound = false;
_locationWatcher.Start(new MvxLocationOptions { Accuracy = MvxLocationAccuracy.Fine }, OnLocation, OnLocationError);
}
`
View
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.LocationView);
_viewModel = (LocationViewModel) ViewModel;
_viewModel.LocationUpdate = new MvxCommand(LocationUpdated);
/* Initialisation code */
}
private void LocationUpdated()
{
var options = new MarkerOptions();
LatLng latLng = new LatLng(_viewModel.Lat, _viewModel.Lng);
options.SetPosition(latLng);
options.SetTitle(_viewModel.SiteName);
_site = _fragment.Map.AddMarker(options);
_fragment.Map.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(latLng, 12));
Geocoder geocdr = new Geocoder(BaseContext);
IList<Address> addresses = geocdr.GetFromLocation(_viewModel.Lat, _viewModel.Lng, 1);
if (addresses.Any())
{
Address address = addresses.First();
_viewModel.SiteName = address.GetAddressLine(0);
_viewModel.SiteAddress = string.Concat( address.GetAddressLine(1),", ",
address.GetAddressLine(2), ", ", address.GetAddressLine(3));
}
}
Upvotes: 2
Views: 446
Reputation: 24470
You probably want to create it as a plugin, where you create an Interface which describes how to get the Address from coordinates, and returns it.
Then you will need to implement platform specific implementations for each platform that will need this.
You can read more about plugins here: https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins
Upvotes: 1