×
Namespaces

Variants
Actions
(Difference between revisions)

How to use Cimbalino Windows Phone Toolkit Location

From Nokia Developer Wiki
Jump to: navigation, search
pavan.pareta (Talk | contribs)
(Pavan.pareta - - Implementing the View)
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Fix metadata)
Line 8: Line 8:
 
|devices= Lumia 800, Lumia 920<!-- Devices tested against - e.g. Nokia Lumia 928, Nokia Asha 501) -->
 
|devices= Lumia 800, Lumia 920<!-- Devices tested against - e.g. Nokia Lumia 928, Nokia Asha 501) -->
 
|sdk= Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK<!-- SDK(s) built and tested against (e.g. Windows Phone 8.0 SDK) -->
 
|sdk= Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK<!-- SDK(s) built and tested against (e.g. Windows Phone 8.0 SDK) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Special Signing requirements -->
+
|signing= <!-- Special Signing requirements -->
 
|capabilities= ID_CAP_LOCATION<!-- Required capabilities for code (e.g. ID_CAP_LOCATION, ID_CAP_NETWORKING) -->
 
|capabilities= ID_CAP_LOCATION<!-- Required capabilities for code (e.g. ID_CAP_LOCATION, ID_CAP_NETWORKING) -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only - not link -->  
+
|translated-from-title= <!-- Title only - not link -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|creationdate= 20131118<!-- Format YYYYMMDD -->
 
|creationdate= 20131118<!-- Format YYYYMMDD -->
|author= [[User:saramgsilva]]<!-- Enter link [[User:username]] -->
+
|author= [[User:Saramgsilva]]
 
}}
 
}}
 
== Introduction ==
 
== Introduction ==

Revision as of 07:43, 26 November 2013

This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Location – LocationService.


SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Tested with
SDK: Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK
Devices(s): Lumia 800, Lumia 920
CompatibilityPlatform Security
Capabilities: ID_CAP_LOCATION
Article
Created: saramgsilva (18 Nov 2013)
Last edited: hamishwillee (26 Nov 2013)

Contents

Introduction

The Cimbalino Windows Phone Toolkit delivers a set of useful and powerful MVVM-compatible tools and services to help developers build Silverlight applications for Windows Phone. The Toolkit is divided in projects which deliver different features, ranging from base MVVM services and helpers, through to code for background agents, and for accessing media library, location services etc. Cimbalino.Phone.Toolkit.Location is a MVVM compatible services for location access.

ILocationService - Represents an interface for a service capable of handling the device location capabilities. The implementation is LocationService.


This article explains how to use the service in an MVVM Light app. Developers should first read How to use MVVM Light Toolkit for Windows Phone for a general overview of MVVM Light and how to use services.


Building the example code

The source code for the code example is available here: (github).

To build the source code you will also need the MVVM Light Toolkit and the Cimbalino Windows Phone Toolkit. Their packages are available in the Nuget Package Manager. For more details see:


The sample is built using MVVM Light and the article does not go into great detail about the plumbing/infrastructure provided by the toolkit. For more information see:


Note.pngNote: you must specify the following capabilities in the app manifest: ID_CAP_LOCATION


Registering the service

Register the service in the ViewModelLocator constructor as shown below

 /// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (!SimpleIoc.Default.IsRegistered<ILocationService>())
{
SimpleIoc.Default.Register<ILocationService, LocationService>();
}
SimpleIoc.Default.Register<MainViewModel>();
}
 
/// <summary>
/// Gets the main view model.
/// </summary>
/// <value>
/// The main view model.
/// </value>
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
 
public static void Cleanup()
{
// TODO Clear the ViewModels
var viewModelLocator = (ViewModelLocator)App.Current.Resources["Locator"];
viewModelLocator.MainViewModel.Cleanup();
}
}


Implementing the ViewModel

Then we should implement the MainViewModel.cs class as following:

  using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
 
using Cimbalino.Phone.Toolkit.Services;
 
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
/// <summary>
/// This class contains properties that the main View can data bind to.
/// </summary>
public class MainViewModel : ViewModelBase
{
/// <summary>
/// The location service
/// </summary>
private readonly ILocationService _locationService;
 
private bool _isLocationEnable;
 
/// <summary>
/// Define if is start enable
/// </summary>
private bool _isStartEnable;
 
/// <summary>
/// Define if is stop enable
/// </summary>
private bool _isStopEnable;
 
/// <summary>
/// The latitude
/// </summary>
private double _latitude;
 
/// <summary>
/// The logitude
/// </summary>
private double _longitude;
 
/// <summary>
/// The status
/// </summary>
private LocationServiceStatus _status;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(ILocationService locationService)
{
IsStartEnable = true;
IsLocationEnable = true;
IsStopEnable = false;
_locationService = locationService;
_locationService.ReportInterval = 5;
_locationService.PositionChanged += LocationService_PositionChanged;
_locationService.StatusChanged += LocationService_StatusChanged;
StartCommand =new RelayCommand(Start);
StopCommand =new RelayCommand(Stop);
LocationCommand = new RelayCommand(GetLocation);
}
 
/// <summary>
/// Gets or sets a value indicating whether [is location enable].
/// </summary>
/// <value>
/// <c>true</c> if [is location enable]; otherwise, <c>false</c>.
/// </value>
public bool IsLocationEnable
{
get
{
return this._isLocationEnable;
}
set
{
Set("IsLocationEnable", ref _isLocationEnable, value);
}
}
 
/// <summary>
/// Gets or sets a value indicating whether [is start enable].
/// </summary>
/// <value>
/// <c>true</c> if [is start enable]; otherwise, <c>false</c>.
/// </value>
public bool IsStartEnable
{
get
{
return this._isStartEnable;
}
set
{
Set("IsStartEnable", ref _isStartEnable, value);
}
}
 
/// <summary>
/// Gets or sets a value indicating whether [is stop enable].
/// </summary>
/// <value>
/// <c>true</c> if [is stop enable]; otherwise, <c>false</c>.
/// </value>
public bool IsStopEnable
{
get
{
return this._isStopEnable;
}
set
{
Set("IsStopEnable", ref _isStopEnable, value);
}
}
 
/// <summary>
/// Gets or sets the latitude.
/// </summary>
/// <value>
/// The latitude.
/// </value>
public double Latitude
{
get
{
return _latitude;
}
set
{
Set("Latitude", ref _latitude, value);
}
}
 
/// <summary>
/// Gets or sets the location command.
/// </summary>
/// <value>
/// The get location command.
/// </value>
public ICommand LocationCommand { get; private set; }
 
/// <summary>
/// Gets or sets the longitude.
/// </summary>
/// <value>
/// The logitude.
/// </value>
public double Longitude
{
get
{
return this._longitude;
}
set
{
Set("Longitude", ref _longitude, value);
}
}
 
/// <summary>
/// Gets or sets the start command.
/// </summary>
/// <value>
/// The start command.
/// </value>
public ICommand StartCommand { get; private set; }
 
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>
/// The status.
/// </value>
public LocationServiceStatus Status
{
get
{
return _status;
}
set
{
Set("Status", ref _status, value);
}
}
/// <summary>
/// Gets or sets the stop command.
/// </summary>
/// <value>
/// The stop command.
/// </value>
public ICommand StopCommand { get; private set; }
/// <summary>
/// Unregisters this instance from the Messenger class.
/// <para>To cleanup additional resources, override this method, clean
/// up and then call base.Cleanup().</para>
/// </summary>
public override void Cleanup()
{
base.Cleanup();
_locationService.PositionChanged -= LocationService_PositionChanged;
_locationService.StatusChanged -= LocationService_StatusChanged;
}
 
/// <summary>
/// Gets the location.
/// </summary>
private async void GetLocation()
{
var result = await _locationService.GetPositionAsync();
Longitude = result.Longitude;
Latitude = result.Latitude;
}
 
/// <summary>
/// Handles the PositionChanged event of the LocationService control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="LocationServicePositionChangedEventArgs"/> instance containing the event data.</param>
private void LocationService_PositionChanged(object sender, LocationServicePositionChangedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Latitude = e.Position.Latitude;
Longitude = e.Position.Longitude;
});
}
 
/// <summary>
/// Handles the StatusChanged event of the _locationService control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="LocationServiceStatusChangedEventArgs"/> instance containing the event data.</param>
private void LocationService_StatusChanged(object sender, LocationServiceStatusChangedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate { Status = e.Status; });
}
 
/// <summary>
/// Starts the location service.
/// </summary>
private void Start()
{
IsStartEnable = false;
IsStopEnable = true;
IsLocationEnable = false;
_locationService.Start();
}
 
/// <summary>
/// Stops the location service.
/// </summary>
private void Stop()
{
IsLocationEnable = true;
IsStartEnable = true;
IsStopEnable = false;
_locationService.Stop();
}
}

Implementing the View

Add the binding in main page like:

DataContext="{Binding MainViewModel, Source={StaticResource Locator}}"

The MainPage.xaml can be the following:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
DataContext="{Binding MainViewModel,
Source={StaticResource Locator}}"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
SupportedOrientations="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d">
 
<!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
 
<!-- TitlePanel contains the name of the application and page title -->
<StackPanel x:Name="TitlePanel"
Grid.Row="0"
Margin="12,17,0,28">
<TextBlock Margin="12,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Cimbalino Sample" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle1Style}"
Text="Location" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<TextBlock TextWrapping="Wrap">
Latitude:<Run Text="{Binding Latitude}" />
</TextBlock>
<TextBlock Margin="0,51,0,-51" TextWrapping="Wrap">
Logitude:<Run Text="{Binding Longitude}" />
</TextBlock>
<TextBlock Margin="0,102,0,-102" TextWrapping="Wrap">
Status:<Run Text="{Binding Status}" />
</TextBlock>
<Button Margin="0,298,0,214"
IsEnabled="{Binding IsStartEnable}"
Command="{Binding StartCommand}"
Content="Start" />
<Button Height="76"
IsEnabled="{Binding IsStopEnable}"
Margin="0,0,0,138"
VerticalAlignment="Bottom"
Command="{Binding StopCommand}"
Content="Stop" />
<Button Margin="0,219,0,293"
IsEnabled="{Binding IsLocationEnable}"
Command="{Binding LocationCommand}"
Content="Get location" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
154 page views in the last 30 days.
×