Sunday, April 29, 2012

LocationServices for Windows Phone, part 4: getting the current address from Bing

before we begin

Get the API keys set up – if you haven’t registered already, go to http://www.bingmapsportal.com/ and do so, then register for a personal app key that you can use. After that’s done, edit the App.xaml and insert your own key.

        <usoniandream:ServiceAPIKey x:Key="BING_API_KEY" Value="" />
        <usoniandream:ServiceURI x:Key="BING_SERVICE_URI_LOCATION" URL="http://dev.virtualearth.net/REST/v1/" />

the namespace you’ll need to add to your App.xaml is:

            xmlns:usoniandream="clr-namespace:Usoniandream.WindowsPhone.LocationServices.Models;assembly=Usoniandream.WindowsPhone.LocationServices"

NuGet for the prerequisites

Easiest way to grab both the Reactive Extensions (rx) and RestSharp is to use NuGet. Install the following two packages and you’re set to move forward:

  • Rx_Experimental-Xaml version 1.1.11111
  • RestSharp version 102.7

add the references needed

1) Add references to the core library:

  • Usoniandream.WindowsPhone.LocationsServices
  • Usoniandream.WindowsPhone.Extensions
  • Usoniandream.WindowsPhone.GeoConverter

2) Add a reference to the Bing data library:

  • Usoniandream.WindowsPhone.LocationsServices.Bing

add some code

3) Declare a service layer:

        public LocationServices.Service.Bing.Reactive.ServiceLayer bingservicelayer = new LocationServices.Service.Bing.Reactive.ServiceLayer();

4) Declare a property for the address:

        public LocationServices.Models.Bing.BingMapLocation CurrentAddress { get ; set;  }

5) Wire the call to get the address:

            addressSubscriber = bingservicelayer.GetAddressAtPoint(new LocationServices.SearchCriterias.Bing.AddressByPoint(GeoHelper.Watcher.Position.Location))
                .ObserveOnDispatcher()
                .Subscribe(result =>
                {
                    this.CurrentAddress = result;
                },
                ex =>
                {
                    // handle errors..
                });

6) Finally, a bit of xaml to wrap it all up:

      <toolkit:PhoneTextBox x:Name="tbAddress" Text="{Binding CurrentAddress.FormattedAddress}" ActionIconTapped="tbAddress_ActionIconTapped" ActionIcon="/content/appbar.globe.nomargin.png" />

7) Along with a click event:

The GetCurrentAddressByCurrentLocation() method contains the code above we just added.

        private void tbAddress_ActionIconTapped(object sender, EventArgs e)
        {
            ViewModel.WireUpPositioning();
            ViewModel.GetCurrentAddressByCurrentLocation();
        }

8) And the end result gives us:

image

The framework libraries, source code and sample app are all on GitHub: https://github.com/peterdrougge/Usoniandream.WIndowsPhone.LocationServices

No comments: