Using ReverseGeocodeQuery for Windows Phone 8


So, I started writing some of my apps I had for Android and WP7 for Windows Phone 8 and to my surprise Nokia Maps are looking to be a really good thing. With the New Nokia Maps, there are Maps services that come with the Windows Phone 8 SDK. One in particular is ReverseGeocodeQuery. This is great as I can use my internal map to get geocoding without having to reference any of the Bing Services. Now, if you want more of the Bing services like Search, Live API, ect. then BIng Services API is the way to go. For my example I will show you how to use the ReverseGeocodeQuery and fill in a textblock with a address of where I am. 

Building the Sample Phone Project in Visual Studio 2012

 First thing you want to do is open Visual Studio 2012 and create a new windows phone project. We are going to name it “ReverseGeocodeQueryPhoneApp” and you will want to pick Windows Phone 8.0 SDK.

 Next, you should see Visual Studio  creating your project and you should see below.

Now, with the MainPage.xaml open, add in the code below to the main content grid.

<TextBlock x:Name=”CurrentLocTextBlock” HorizontalAlignment=”Left”
Foreground=”{StaticResource PhoneForegroundBrush}”
FontSize=”20″ FontWeight=”Bold”/>

 Open the code behind and Add in the reference code below.

public partial class MainPage : PhoneApplicationPage
{
// Progress indicator shown in system tray
private ProgressIndicator ProgressIndicator = null;

// My current location
private GeoCoordinate MyCoordinate = null;

// Reverse geocode query
private ReverseGeocodeQuery MyReverseGeocodeQuery = null;

/// <summary>
/// Accuracy of my current location in meters;
/// </summary>
private double _accuracy = 0.0;

// Constructor
public MainPage()
{
InitializeComponent();
GetCurrentCoordinate();
}

/// <summary>
/// Method to get current coordinate asynchronously so that the UI thread is not blocked. Updates MyCoordinate.
/// Using Location API requires ID_CAP_LOCATION capability to be included in the Application manifest file.
/// </summary>
private async void GetCurrentCoordinate()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;

try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
_accuracy = currentPosition.Coordinate.Accuracy;

MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);

if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy)
{
MyReverseGeocodeQuery = new ReverseGeocodeQuery();
MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Longitude);
MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}

}
catch (Exception ex)
{
...
}

}

/// <summary>
/// Event handler for reverse geocode query.
/// </summary>
/// <param name="e">Results of the reverse geocode query - list of locations</param>
private void ReverseGeocodeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
CurrentLocTextBlock.Text = "Current Location: " + address.City + ", " + address.State;
}
}
}
}

 Remember to check ID_CAP_Location and ID_CAP_Map in the Capabilities section of the Windows Manifest. if you don’t you will get a Access Denied Error.

Now you are set to debug your work, below is what should be displaying in the emulator.

I hope you found the post useful. As I come across more great things in Windows Phone 8 development (I am sure I will). I will pass it along to you all.

Happy Coding!!

Thanks,

John

Comments (15)

  1. KRK says:

    Thank you very much.

    It was interesting to learn this.

    KRK

  2. tt says:

    Need your help。

    I get the address only “china”, I can't get the city "shanghai", why?

  3. tt says:

    use the code,I only can get Country and PostalCode, what should I do to get the other data such as city ?

  4. John says:

    As part of ReverseGeocodeQuery_QueryCompleted, the QueryCompletedEventArgs<IList<MapLocation>> brings back a list of possible locations. You can loop through the list to find the best possible address.

    MapAddress address = e.Result[0].Information should give you all the possible data elements you need to bring back all address elements.

    Try reading: msdn.microsoft.com/…/microsoft.phone.maps.services.mapaddress(v=vs.105).aspx

    Thanks,

    John

  5. tt says:

    John, thanks.

    The website I have read, now I sure there is no problem in my code. I use the code from your code.

    Some area can get detail info. such as new GeoCoordinate(31.2042859131461, 121.552734375),it can get Country,City and district.

    Some area get little info. such as  new GeoCoordinate(31.281192, 121.535912),it can only get Country.

    Now I guess the API ReverseGeocodeQuery get little data in China. How you think ? What shouleI do if I want get the data of City?

  6. Gerardo Melendrez says:

    Thanks. Useful.

  7. Mohamed Samsudeen says:

    Hi John,

    There is no response in text block. I have done all the things you said.

    Thanks,

    Mohamed Samsudeen K S

  8. meesun says:

    what should i do if i want to update the position information whenever the user makes a move to a different location????

  9. Mohamed Samsudeen  

    I had the same problem. After I added a height and width to the textblock, I could see the location information.

    David

  10. anshul says:

    I cant see any location on my emulator, tried changing height and width. please help

  11. sunil says:

    void reverseGeocode_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)

           {

               if (e.Error == null)

               {

                   if (e.Result.Count > 0)

                   {

                       MessageBox.Show("This works");

                       MapAddress address = e.Result[0].Information.Address;

                       CurrentLocTextBlock.Text = "Current Location: " + address.City + ", " + address.State;

                       txtAdd.Text = address.City;

                   }

                   else

                   {

                       MessageBox.Show("e.Result.Count < 0.");

                   }

               }

               else

               {

                   MessageBox.Show("e.Error != null");

               }

           }

    why this code control always goes to MessageBox.Show("e.Result.Count < 0.");

  12. manju says:

    Thank u so much john.

  13. pinocchio says:

    there is an .UnauthorizedAccessException at  " MyReverseGeocodeQuery.QueryAsync(); " this line of code… .any suggestion ??

  14. RajeevChandran says:

    Hi Pinocchio

    Its permission based issue.

    Enable both "ID_CAP_MAP" and "ID_CAP_LOCATION" capabilities in WMAppManifest file.

  15. Gülşah Merve KAPUCU says:

    Thank you, this was really useful.