If you have Windows Phone and would like to be able easily send your location to someone the code below will be helpful.
When reviewing the code you will find that it is functional but lacks a pleasant user interface, as you build this app you can add your own icon(s) and more features.
Icon Sizes:
Sample | Size | Flip and Cycle | Iconic |
---|---|---|---|
Small | 159 × 159 pixels | 110 × 110 pixels | |
Medium | 336 × 336 pixels | 202 × 202 pixels | |
Wide | 691 × 336 pixels | N/A |
Download NuGet Package: Windows Phone Toolkit
- In Visual Studio go to File Menu -> New -> Project
- Select “Windows Phone App” within Visual C# -> Windows Phone
- Expand Properties in the Solution Explorer and open “WMAppManifest.xml”
- Click on the Capabilities tab
- Under Capabilities, check “ID_CAP_LOCATION” AND “ID_CAP_MAP”
Basic
<phone:PhoneApplicationPage xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps" x:Class="Location.MainPage" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <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 Text="My Location" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/> <TextBlock Text="Location" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button x:Name="btnLocateMe" Content="Locate Me" HorizontalAlignment="Left" Margin="10,350,0,0" VerticalAlignment="Top" Click="btnLocateMe_Click"/> <Button x:Name="btnEmail" Content="Email" HorizontalAlignment="Left" Margin="289,350,0,0" VerticalAlignment="Top" Click="btnEmail_Click" Width="157"/> <TextBlock x:Name="txtbLat" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="Lat: " VerticalAlignment="Top"/> <TextBlock x:Name="txtbLon" HorizontalAlignment="Left" Margin="10,42,0,0" TextWrapping="Wrap" Text="Long: " VerticalAlignment="Top"/> <maps:Map x:Name="map1" HorizontalAlignment="Left" Margin="10,74,0,0" VerticalAlignment="Top" Height="271" Width="436"/> <Button Content="Exit" HorizontalAlignment="Left" Margin="289,525,0,0" VerticalAlignment="Top" Width="157" Click="Button_Click"/> <Button x:Name="btnSMS" Content="SMS" HorizontalAlignment="Left" Margin="289,422,0,0" VerticalAlignment="Top" Width="157" Click="btnSMS_Click"/> </Grid> </Grid> </phone:PhoneApplicationPage>
#region Using Namespaces - Start using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Location.Resources; #region Store Location Consent - Start using System.IO.IsolatedStorage; #endregion Store Location Consent - Stop #region Geo Location Using Namespace - Start using System.Device.Location; using System.Threading.Tasks; #endregion Geo Location Using Namespace - Stop #region Pushpin Using Namespace - Start using Microsoft.Phone.Maps.Controls; using Microsoft.Phone.Maps.Toolkit; #endregion - Stop #region Email Sharing Using Namespace - Start using Microsoft.Phone.Tasks; #endregion Email Sharing Using Namespace - Stop #endregion Using Namespaces - Stop namespace Location { public partial class MainPage : PhoneApplicationPage { #region Create Variables For Geo Location private GeoCoordinateWatcher loc = null; #endregion Create Variables For Geo Location // Constructor public MainPage() { InitializeComponent(); btnEmail.IsEnabled = false; btnSMS.IsEnabled = false; } private void btnLocateMe_Click(object sender, RoutedEventArgs e) { if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true) { // The user has opted out of Location. return; } // Quick Lookup - Start loc = new GeoCoordinateWatcher(GeoPositionAccuracy.Default); //EventHandler for location service status changes loc.StatusChanged += loc_StatusChanged; //If the location service is disabled or not supported if (loc.Status == GeoPositionStatus.Disabled) { //Display a message MessageBox.Show("Location services must be enabled"); return; } loc.Start(); // Quick Lookup - Stop } void loc_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) { if (e.Status == GeoPositionStatus.Ready) { map1.SetView(loc.Position.Location, 10.0); #region Add Location Pushpin - Start Pushpin myLocation = new Pushpin(); myLocation.Content = "My Location"; MapOverlay myOverlay = new MapOverlay(); myOverlay.Content = myLocation; myOverlay.GeoCoordinate = new GeoCoordinate(loc.Position.Location.Latitude, loc.Position.Location.Longitude); myOverlay.PositionOrigin = new Point(0, 0.5); MapLayer myLayer = new MapLayer(); myLayer.Add(myOverlay); map1.Layers.Add(myLayer); #endregion Add Location Pushpin - Start txtbLat.Text = "Lat: " + loc.Position.Location.Latitude.ToString(); txtbLon.Text = "Long: " + loc.Position.Location.Longitude.ToString(); btnEmail.IsEnabled = true; btnSMS.IsEnabled = true; loc.Stop(); } } private void btnEmail_Click(object sender, RoutedEventArgs e) { string Msg = "Lat: " + loc.Position.Location.Latitude.ToString() + Environment.NewLine + "Long: " + loc.Position.Location.Longitude.ToString() + Environment.NewLine + Environment.NewLine + "Google: " + "https://maps.google.com/maps?q=" + loc.Position.Location.Latitude.ToString() + "," + loc.Position.Location.Longitude.ToString() + //Environment.NewLine + //Environment.NewLine + //"Bing: " + Environment.NewLine; EmailComposeTask emailcomposer = new EmailComposeTask(); emailcomposer.To = ""; emailcomposer.Subject = "My Current Location"; emailcomposer.Body = Msg; //Show the Email application emailcomposer.Show(); } private void btnSMS_Click(object sender, RoutedEventArgs e) { SmsComposeTask smsComposeTask = new SmsComposeTask(); smsComposeTask.To = ""; string Msg = "Lat: " + loc.Position.Location.Latitude.ToString() + Environment.NewLine + "Long: " + loc.Position.Location.Longitude.ToString() + Environment.NewLine + "Google: " + "https://maps.google.com/maps?q=" + loc.Position.Location.Latitude.ToString() + "," + loc.Position.Location.Longitude.ToString(); smsComposeTask.Body = Msg; smsComposeTask.Show(); } private void Button_Click(object sender, RoutedEventArgs e) { Application.Current.Terminate(); } protected override void OnNavigatedTo(NavigationEventArgs e) { //base.OnNavigatedTo(e); if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent")) { // User has opted in or out of location return; } else { MessageBoxResult result = MessageBox.Show("This app accesses your phone's location. Is that OK?", "My Location", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true; } else { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false; MessageBox.Show("Closing App Now"); Application.Current.Terminate(); } IsolatedStorageSettings.ApplicationSettings.Save(); } } } }
More Details
<phone:PhoneApplicationPage xmlns:Controls="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps" x:Class="MyLocation.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <!--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> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock Text="My Location" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <TextBlock x:Name="LatitudeTextBlock"/> <TextBlock x:Name="LongitudeTextBlock"/> <TextBlock x:Name="AccuracyTextBlock"/> <TextBlock x:Name="AltitudeTextBlock"/> <TextBlock x:Name="DirectionTextBlock"/> <TextBlock x:Name="SpeedTextBlock"/> <TextBlock x:Name="CityTextBlock"/> <Controls:Map x:Name="map1" Height="400" /> </StackPanel> </Grid> </Grid> </phone:PhoneApplicationPage>
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using MyLocation.Resources; #region Store Location Consent - Start using System.IO.IsolatedStorage; #endregion Store Location Consent - Stop #region Geo Location Using Namespace - Start using System.Device.Location; // Provides the GeoCoordinate class. using Windows.Devices.Geolocation; //Provides the Geocoordinate class. using System.Threading.Tasks; #endregion Geo Location Using Namespace - Stop #region Pushpin Using Namespace - Start using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Phone.Maps.Controls; using Microsoft.Phone.Maps.Services; #endregion - Stop #region Email Sharing Using Namespace - Start using Microsoft.Phone.Tasks; #endregion Email Sharing Using Namespace - Stop namespace MyLocation { public partial class MainPage : PhoneApplicationPage { private GeoCoordinateWatcher loc = null; public double dLat = 0; public double dLon = 0; // Constructor public MainPage() { InitializeComponent(); PhoneApplicationService phoneAppService = PhoneApplicationService.Current; phoneAppService.UserIdleDetectionMode = IdleDetectionMode.Disabled; // Sample code to localize the ApplicationBar BuildLocalizedApplicationBar(); ShowMyLocationOnTheMap(); } // Sample code for building a localized ApplicationBar private void BuildLocalizedApplicationBar() { // Set the page's ApplicationBar to a new instance of ApplicationBar. ApplicationBar = new ApplicationBar(); // Create a new button and set the text value to the localized string from AppResources. ApplicationBarIconButton appBarSMSButton = new ApplicationBarIconButton(); appBarSMSButton.IconUri = new Uri("/Assets/AppBar/appbar.message.png", UriKind.Relative); appBarSMSButton.Text = "SMS"; appBarSMSButton.Click += new EventHandler(SMS_Click); ApplicationBar.Buttons.Add(appBarSMSButton); ApplicationBarIconButton appBarEmailButton = new ApplicationBarIconButton(); appBarEmailButton.IconUri = new Uri("/Assets/AppBar/appbar.email.png", UriKind.Relative); appBarEmailButton.Text = "Email"; appBarEmailButton.Click += new EventHandler(Email_Click); ApplicationBar.Buttons.Add(appBarEmailButton); ApplicationBarIconButton appBarCloseButton = new ApplicationBarIconButton(); appBarCloseButton.IconUri = new Uri("/Assets/AppBar/appbar.close.png", UriKind.Relative); appBarCloseButton.Text = "Close"; appBarCloseButton.Click += new EventHandler(Close_Click); ApplicationBar.Buttons.Add(appBarCloseButton); //// Create a new menu item with the localized string from AppResources. //ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText); //ApplicationBar.MenuItems.Add(appBarMenuItem); } private void Close_Click(object sender, EventArgs e) { Application.Current.Terminate(); } private void SMS_Click(object sender, EventArgs e) { SmsComposeTask smsComposeTask = new SmsComposeTask(); smsComposeTask.To = ""; string Msg = LatitudeTextBlock.Text + Environment.NewLine + LongitudeTextBlock.Text + Environment.NewLine + "Google: " + "https://maps.google.com/maps?q=" + dLat.ToString() + "%2C" + dLon.ToString(); smsComposeTask.Body = Msg; smsComposeTask.Show(); } private void Email_Click(object sender, EventArgs e) { string Msg = "Lat: " + LatitudeTextBlock.Text + Environment.NewLine + "Long: " + LongitudeTextBlock.Text + Environment.NewLine + Environment.NewLine + "Google: " + "https://maps.google.com/maps?q=" + dLat.ToString() + "%2C" + dLon.ToString() + //Environment.NewLine + //Environment.NewLine + //"Bing: " + Environment.NewLine; EmailComposeTask emailcomposer = new EmailComposeTask(); emailcomposer.To = ""; emailcomposer.Subject = "My Current Location"; emailcomposer.Body = Msg; //Show the Email application emailcomposer.Show(); } public static GeoCoordinate ConvertGeocoordinate(Geocoordinate geocoordinate) { return new GeoCoordinate ( geocoordinate.Latitude, geocoordinate.Longitude, geocoordinate.Altitude ?? Double.NaN, geocoordinate.Accuracy, geocoordinate.AltitudeAccuracy ?? Double.NaN, geocoordinate.Speed ?? Double.NaN, geocoordinate.Heading ?? Double.NaN ); } private async void ReverseGeoCode(double dLat, double dLong) { try { List<MapLocation> locations; ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(dLat, dLong); query.QueryCompleted += (s, e) => { if (e.Error == null && e.Result.Count > 0) { locations = e.Result as List<MapLocation>; CityTextBlock.Text = "Near Address: " + locations[0].Information.Address.HouseNumber + " " + locations[0].Information.Address.Street + Environment.NewLine + locations[0].Information.Address.City + ", " + //locations[0].Information.Address.County + //", " + locations[0].Information.Address.State + " " + locations[0].Information.Address.PostalCode; } }; query.QueryAsync(); } catch { } } void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { Dispatcher.BeginInvoke(() => { ShowMyLocationOnTheMap(); //dLat = args.Position.Coordinate.Latitude; //dLon = args.Position.Coordinate.Longitude; //LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00"); //LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00"); }); } public string GetCompassDirection(double bearing) { int tmp; // Set Default Direction string direction = "N"; tmp = (Int32)(Math.Floor(Math.Round(bearing / 22.5))); switch (tmp) { case 1: direction = "NNE"; break; case 2: direction = "NE"; break; case 3: direction = "ENE"; break; case 4: direction = "E"; break; case 5: direction = "ESE"; break; case 6: direction = "SE"; break; case 7: direction = "SSE"; break; case 8: direction = "S"; break; case 9: direction = "SSW"; break; case 10: direction = "SW"; break; case 11: direction = "WSW"; break; case 12: direction = "W"; break; case 13: direction = "WNW"; break; case 14: direction = "NW"; break; case 15: direction = "NNW"; break; default: direction = "N"; break; } return direction; } private async void ShowMyLocationOnTheMap() { try { // Get my current location. Geolocator myGeolocator = new Geolocator(); myGeolocator.DesiredAccuracy = PositionAccuracy.High; myGeolocator.MovementThreshold = 100; // The units are meters. myGeolocator.PositionChanged += geolocator_PositionChanged; Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(); Geocoordinate myGeocoordinate = myGeoposition.Coordinate; GeoCoordinate myGeoCoordinate = ConvertGeocoordinate(myGeocoordinate); // Make my current location the center of the Map. this.map1.Center = myGeoCoordinate; this.map1.ZoomLevel = 15; dLat = myGeocoordinate.Latitude; LatitudeTextBlock.Text = "Lat: " + myGeocoordinate.Latitude.ToString(); dLon = myGeoCoordinate.Longitude; LongitudeTextBlock.Text = "Long: " + myGeocoordinate.Longitude.ToString(); AccuracyTextBlock.Text = "Acc: " + myGeocoordinate.Accuracy.ToString(); AltitudeTextBlock.Text = "Alt: " + myGeocoordinate.Altitude.ToString(); double dBearings = (double)myGeocoordinate.Heading; DirectionTextBlock.Text = "Dir: " + GetCompassDirection(dBearings); double dSpeed = (double)myGeocoordinate.Speed * 2.2369362920544; SpeedTextBlock.Text = "Speed: " + dSpeed.ToString() + " MPH"; ReverseGeoCode(dLat, dLon); // Create a small circle to mark the current location. Ellipse myCircle = new Ellipse(); myCircle.Fill = new SolidColorBrush(Colors.Blue); myCircle.Height = 10; myCircle.Width = 10; myCircle.Opacity = 50; // Create a MapOverlay to contain the circle. MapOverlay myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = myCircle; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = myGeoCoordinate; // Create a MapLayer to contain the MapOverlay. MapLayer myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); map1.Layers.Clear(); // Add the MapLayer to the Map. map1.Layers.Add(myLocationLayer); } catch { } } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent")) { // User has opted in or out of Location return; } else { MessageBoxResult result = MessageBox.Show("This app accesses your phone's location. Is that ok?", "Location", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true; } else { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false; } IsolatedStorageSettings.ApplicationSettings.Save(); } } } }
References:
Microsoft – Tiles for Windows Phone 8
You must be logged in to post a comment.