Getting your device’s location takes remarkably little code.
The new emulator that comes with Mango makes it possible to test location services without adding a GPS to your desktop computer and putting it in your car, thus saving a fortune on extension cords.
To get started, create a new Windows Phone application and, if you like, set the name of the application in the Xaml.
Add a list box named Output to take up the entire grid, this will display both the status of the GeoCoordinateWatcher (the GPS interface) but will also update with the new longitude and latitude every second or so.
<Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="Sensors" Style="{StaticResource PhoneTextNormalStyle}" /> <TextBlock x:Name="PageTitle" Text="Location" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" /> </StackPanel> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox Name="Output" Margin="20" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </Grid> </Grid>
In the code behind file, we’ll create an instance of GeoCoordinateWatcher and handle the events for when the Position changes and when the Status of the GeoCoordinateWatcher changes.
public MainPage() { InitializeComponent(); gcw.StatusChanged += gcw_StatusChanged; gcw.PositionChanged += gcw_PositionChanged; gcw.Start(); }
The two event handlers retrieve the needed information from the parameter passed into the event handler
void gcw_PositionChanged( object sender, GeoPositionChangedEventArgs<GeoCoordinate> e ) { string latitude = e.Position.Location.Latitude.ToString(); string longitude = e.Position.Location.Longitude.ToString(); string Accuracy = e.Position.Location.HorizontalAccuracy.ToString(); Output.Items.Add( String.Format( "New Lat: {0}, New Long: {1}", latitude, longitude)); } void gcw_StatusChanged( object sender, GeoPositionStatusChangedEventArgs e ) { string status = e.Status.ToString(); Output.Items.Add( String.Format( ">> New Status: {0}", status ) ); }
To see this work in the emulator, be sure to click on the chevron next to the standard emulator, and then to click on the Location tab in the extended emulator. Move around the map and notice how the longitude and latitude are reflected in the list box. Notice also that the longitude and latitude are updated every second even if you don’t change the location.
This posting is based on material from our forthcoming book, Migrating to Windows Phone, by Jesse Liberty and Jeff Blankenburg
Thanks alot 😀