Part 25: Working with the Geolocator and Geoposition Classes

Play Part 25: Working with the Geolocator and Geoposition Classes
Sign in to queue

Description

Source Code: https://aka.ms/absbeginnerdevwp8
PDF Version: https://aka.ms/absbeginnerdevwp8pdf

In the previous lesson I was able to hardcode a GeoCoordinate object and pass it to the Map control to set it's position. However, for our app, we will want to retrieve that information from the phone. The Windows Phone API has a Geolocator class that will use the phone's GPS system to determine where in the world it is.

Here's the game plan:

  1. We'll experiment with our UpdateMap() method to learn about the Geolocator class, how to set it's accuracy and obtain the current position.
  2. We'll learn about other classes in the Windows Phone API that allow us to work with the map and the locale of the user
  3. We'll configure the Windows Phone Emulator and set its position to a specific place, namely, the John Hancock Center in Chicago. I have a special affinity for Chicago and for that building specifically that I'll tell you about later.

 

1. Modify UpdateMap() to retrieve it's position from the Geolocator class

We'll pick up where we left off in the previous lesson, updating the UpdateMap() method as follows:

Generic Episode Image

 

  1. We create a new instance of the Geolocator class and set it's DesiredAccuracyInMeters property to 50 (meters).
  2. We call the GetGeopositionAsync method.  At this point, I'd like to point out the best article I read on the process of acquiring the Geoposition of the phone and why there are several factors to consider. Actually, It's a blog post on the Windows Phone Developer blog from Daniel Estrada Alva, a software development engineer on the Windows Phone team.  http://blogs.windows.com/windows_phone/b/wpdev/archive/2012/11/30/acquiring-a-single-geoposition-in-windows-phone-8.aspx
  3. There's a keyword you may not be familiar with in line 40: the await keyword. This corresponds with the async keyword I added to the method's signature in line 34. Just how this works and why I would like to save until a later lesson when I take extensively about the new await functionality in C# 5.0. For now, just understand that the purpose of this is to keep our application responsive while potentially long running tasks are executing. In this case, the phone may take a long time to acquire the current location using its built in GPS hardware. While it is acquiring the location, the user's phone, and even our app, should continue to be responsive to the user's input. Again, more later.
  4. The Geoposition object has a collection of coordinates. However, we have to do a little conversion because the Map control requires those coordinates be in a GeoCoordinate object.
  5. Finally, we pass the GeoCoordinate we just created to the SetView() method.

When we run the app (F5), we can see the result:

 

Generic Episode Image

 

... the result is that the Map control is zoomed into Redmond, Washing, the home of Microsoft's main campus. This is the default position of the Windows Phone Emulator.

 

2. Use the Emulator's Additional Tools to change the virtual location of the Emulator for testing

So, how do we change the Emulator to use a different latitude and longitude?

Generic Episode Image

 

  1. I click the double chevron to open up the Additional Tools panel.
  2. I click the Location tab at the top.
  3. I the words "John Hancock, Chicago" into the Search textbox and hit the Enter key on my keyboard.

This shows me a different map ... a map of downtown Chicago positioned at the John Hancock Center. Excellent.

I'll use the primary (left) mouse button to add a pin on that location.

 

Generic Episode Image

 

By adding a pin, I've set the Current Location to the correct latitude and longitude for the John Hancock Center.

However, sometimes it takes a while for the phone's GPS to catch up and refresh. What I've found works best is to exit out of the AroundMe app, go to the Windows Phone 8 application list, open Maps and wait for the phone to reposition to the desired location. When I do that, after about 10 seconds, the Maps program repositions to downtown Chicago.

 

Generic Episode Image

 

Now, I re-run the app from the Application List (I don't need to stop and re-start the app from Visual Studio) and it should pick up the change in GeoPosition.

 

Generic Episode Image

It works!

Recap

Just to recap, the big take away from this lesson is how to use the Geolocator class to interface with the phone's GPS hardware to retrieve an instance of the GeoPosition class. The GeoPosition class has a number of interesting details, but for our purposes we care only about the longitude and latitude, which we can use to construct a new GeoCoordinate class in order to center the Map control. We learned how to configure the Phone Emulator's Location to make it think it is at a specific place in the world to test various location scenarios.

Embed

Download

The Discussion

  • User profile image
    QuocTruong

    @BobTabor: You are awesome. I alway vote 5 stars for you.

  • User profile image
    BobTabor

    @QuocTruong: Thanks.  Smiley

  • User profile image
    Russell

    I finished this tutorial and my app builds, but when I run it on my phone (my computer won't support the emulator so I have to run everything on my device) it crashes when it tries to find my location.

  • User profile image
    Clint

    @Russell: how does it crash?  Does an exception get thrown?  Do you have the Location and map capabilities checked from https://channel9.msdn.com/Series/Windows-Phone-8-Development-for-Absolute-Beginners/Part-24-Getting-Started-with-the-AroundMe-Project

  • User profile image
    BobTabor

    @Russell: I think you may be experiencing the issue with sending too many digits after the decimal to Flickr.  I believe I talk about this problem in the next video or two.  Sorry!  They can only accept 5 digits after the decimal.  Didn't realize this until it was too late.

  • User profile image
    gauravi

    How can assign my current place Latitude,Longitude.

    this code is giving chicago as place but what if i want my city?

  • User profile image
    Clint

    @gauravi: you can set the emulator to where every you want.  if you want easy way to get lat,long, use Wikipedia, look for coordinates on the right side.  http://en.wikipedia.org/wiki/Arc_de_Triomphe or http://en.wikipedia.org/wiki/Seattle

  • User profile image
    lxyms

    @Russell: Try to change TimeSpan.FromSeconds(30) to TimeSpan.FromSeconds(300). It works on my device.

  • User profile image
    devlife3

    Quick question.  Why create a new GeoCoordinate instance as opposed to using the position.Coordinate instance?  Does it make a difference or were you just trying to be more explicit?

    var position = await geoLocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30));
    
    var gpsCoorCenter = new GeoCoordinate(position.Coordinate.Latitude, position.Coordinate.Longitude);

  • User profile image
    Rajeev

    Hai bab. . I need to download that sdk for my machine for later use incase if removed accidently. . i tried but i shows we can install online only . . instead of this i need to install in offline mode. . kindly help me via this mail id . .

    mailto.rajiv18@yahoo.com // mailto.rajiv18@hotmail.co.in

    Thank you so much in advance . . :-)

  • User profile image
    Clint

    @devlife3: they are actually different classes ... note the upper and lower case C in coordinate.

  • User profile image
    Clint

    @Rajeev: go to https://www.microsoft.com/en-us/download/details.aspx?id=35471 and click "install instructions", there you'll see the last item talking about an iso install.   https://go.microsoft.com/fwlink/?LinkID=257234&clcid=0x409

    X

  • User profile image
    laith 2

    How i can Select location in map
    i need select location phone any where
    and detect the earliest point i want

  • User profile image
    Clint

    @laith 2: we didn't cover that in our tutorial, head over to https://dev.windowsphone.com, I found https://code.msdn.microsoft.com/wpapps/Windows-Phone-8-JumpStart-b3ef6476 which has push pins

  • User profile image
    ratna03

    Hello Bob, I am developing a windows phone app in 8.1 and the visual studio i am using is vs express for windows phone 2012... so will it be compatible for developing app??? and i am not getting that how to add bing map api in my project??? help me out...

  • User profile image
    Luandierison

    Hello I'm from Brazil

    Translation:

    Hello! I'm finding it difficult to develop an app that uses the GPS on a map so that it shows the path of a person for example, if she tighten "button to start the race" the app starts to show the way that person is going through and that stop it when she squeeze in another button "stop" ... if the app would save the path from the starting point to the end ... and show details like speed, distance traveled ... 
    thanks for listening....


    message Original

    Olá! Galera estou encontrando dificuldades em desenvolver um app que use o GPS em um mapa de forma que ele mostre o trajeto de uma pessoa por exemplo, se ela apertar em "botao iniciar corrida" o app começa a mostrar o caminho que essa pessoa está percorrendo e que ele pare quando ela apertar em um outro botao "parar"... o app no caso salvaria o trajeto do ponto inicial e o final... e mostraria detalhes como velocidade, distancia percorrida... 

  • User profile image
    BobTabor

    @ratna03: Hi, you're getting your terms mixed.  Windows Phone 8.0 ... Windows 8.1 ... they're different.  Windows Phone 8.1 doesn't exist (yet).  re: Bing Map ... see the yellow box on this page:

    https://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207045(v=vs.105).aspx

    @Luandierison: Sorry, that's not part of this series.  I can't help you with that.

  • User profile image
    DolaWP8

    Hi,Bob , I want to thank you for this great tutorials but I have a little question.

    when we call GetGeopositionAsync() method ,why in parameter you put 

    TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30)

    what is the benefit of it?? I removed it and called the method without parameter and it was the same result !!

    Thanks :)

  • User profile image
    Moizzah Asif

    Hi bob, i am working on an app where i am using windows phone 8 maps API. I have attached a slider control with the map control for zooming in an out, although i have set the maximum and minimum vale 20 and 1, but the problem is that when the user slides and stop at a type double value, the debugger throws an exception. Can you guide me how to handle this situation

  • User profile image
    Amna

    Hello, your tutorials are a great help!! i wanted to know how how can i get the same perfect results as you got for John Hancock, Chicago, for some area in my city, say for example i want Dolmen Mall, Karachi (Pakistan). firstly it doesn't provide me with any location on the map if i just enter the name of area in words. even if i give the respective co-ordinates for Dolmen Mall Karachi, it doesn't show a detailed location marked dolmen mall as that it gave for John Hancock, Chicago. naturally i want the user to have a nice detailed look so that he can have an idea of his location.
    i even tried giving the following properties of mode true, but nothing as such changed...
    PedestrianFeaturesEnabled="True"
    LandmarksEnabled="True"
    CartographicMode="Road"

    please help. Thanks ( i managed to get the co-ordinates of places in karachi from this link http://www.viewphotos.org/pakistan/coordinates-of-Karachi-232.html)

  • User profile image
    MathV

    Hello,

    Thank you for this great tutorial.
    I do have one question: Can i improve the latency on getting the current geolocation? If I change the location quickly in the emulator en then debug for the coördinates, the systeem still retrieves the previous geolocation.

    It seems to be lagging when switching locations quickly.

    Thank you in advance.

    Math

Add Your 2 Cents