Tag Archives: Windows Phone 7.1

Determine location on Windows Phone 7.1

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device;
using System.Device.Location;
using System.Xml.Linq;
namespace Reverse_Geocoding_Blog
{
    public partial class MainPage : PhoneApplicationPage
    {

        GeoCoordinateWatcher geoLocWatcher;
        public MainPage()
        {
            InitializeComponent();
        }

        private void cmdGetLoc_Click(object sender, RoutedEventArgs e)
        {
            // create an object of GeoCoordinateWatcher to ask data from your device
            geoLocWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
            {
                MovementThreshold = 20
            };

            //create the event handlers.
            geoLocWatcher.PositionChanged += this.geoLocWatcher_PositionChanged;
            geoLocWatcher.StatusChanged += this.geoLocWatcher_StatusChanged;
            geoLocWatcher.Start();
        }

        private void geoLocWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // location is unsupported on this device
                    MessageBox.Show("This device has no support for Geopositioning");
                    break;
                case GeoPositionStatus.NoData:
                    // When no data can get queried back
                    break;
            }
        }

        private void geoLocWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Now we want to retreive the data from our device
            var data = e.Position.Location;
            var lat = data.Latitude.ToString();
            var lon = data.Longitude.ToString();
            // This is all the data we need to determine our location! We can get extra data out of this such as our Altitude and Speed.
            reverseGeoCode(lat, lon);


        }


        #region reverseGeoCoding
        private void reverseGeoCode(string lat, string lon)
        {

            // retrieve formatted adress given a lat and long
            var baseUri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";

            string requestUri = string.Format(baseUri, lat, lon); // create a new string of the baseUri with {0} and {1} defined by the lat and lon variable.
            var webClient = new WebClient();
            webClient.DownloadStringAsync(new Uri(requestUri)); // We create an asynchronous request - we are relying on a webservice and don't want to block the thread!
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted); 
           

        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var xmlElement = XElement.Parse(e.Result);
            var status = (from elm in xmlElement.Descendants()
                          where elm.Name == "status"
                          select elm).FirstOrDefault();

            if (status.Value.ToLower() == "ok")
            {
                var res = (from elm in xmlElement.Descendants()
                           where elm.Name == "formatted_address" // query out the formatted address from the returned results.
                           select elm).FirstOrDefault(); // If you look in the retrieved results (an xml file), you will see that the adress is stored in the first entry of "formatted_address".

                txtLocation.Text = res.Value.ToString();
            }
            else
            {
                // this implies that an adress has not been found. (The result queried back did not state any village, or other location information)        
            }

        }
        #endregion
    }
}

And XAML

<phone:PhoneApplicationPage 
    x:Class="Reverse_Geocoding_Blog.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" d:DesignWidth="480" d:DesignHeight="768"
    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>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Get Location" Height="72" HorizontalAlignment="Left" Margin="0,6,0,0" Name="cmdGetLoc" VerticalAlignment="Top" Width="450" Click="cmdGetLoc_Click" />
            <TextBlock Height="31" HorizontalAlignment="Left" Margin="12,84,0,0" Name="txtLocation" Text="Location" VerticalAlignment="Top" Width="426" />
        </Grid>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>