Skip to content
Bruno Sonnino
Menu
  • Home
  • About
Menu

Working with Sensors in UWP–Part 5–Geolocation

Posted on 7 November 2016

This last part in the series will show a different kind of sensor – the Geolocation sensor. In the strict sense, we can’t call this as a sensor, because the geolocation service will get the current location from the GPS sensor if it exists. If not, it will use other methods, like the network of wifi to detect the current location.

To get the current location, you must work in a different way that we worked for the other sensors:

  • You must add the Location capability to the app manifest
  • The user must consent with the use of the current location
  • You should instantiate a new Geolocator instance (and not get one with GetDefault)
  • There is no ReadingChanged event, but StatusChanged event

Even with these changes, you will see that it’s very easy to work with the geolocation. In this post we will develop a program that gets the current location and queries a weather service to get the forecast and see if it will rain.

Will it rain?

In Visual Studio, create a blank UWP project. To query the weather, we will use an open source project that has a C# API to query the OpenWeather map (http://openweathermap.org/API), located in https://github.com/joancaron/OpenWeatherMap-Api-Net. We can add this lib by using the Nuget Package manager (right click the References node in Solution Explorer and select Manage Nuget Packages). Just search for openweather and install the lib:

Just one note here: the official package doesn’t support Windows 10, so you must choose a fork of the project (the third project in the list) to install.

Then, you must add the Location capability to the app manifest. On the solution Explorer, open package.appxmanifest and go to the tab Capabilities. There, check the Location box.

Then, in the Main window, add this XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   <TextBlock x:Name="RainText" 
       HorizontalAlignment="Center" 
       VerticalAlignment="Center" 
       FontSize="30"/>
</Grid>
XML

In the constructor of MainPage, we must ask for the user permissions an process the response:

public MainPage()
{
    this.InitializeComponent();
    InitializeLocator();
}

public enum RainStatus
{
    Rain,
    Sun
};

private async void InitializeLocator()
{
    var userPermission = await Geolocator.RequestAccessAsync();
    switch (userPermission)
    {
        case GeolocationAccessStatus.Allowed:
            RainText.Text = "Updating rain status...";
            Geolocator geolocator = new Geolocator();
            Geoposition pos = await geolocator.GetGeopositionAsync();
            try
            {
                RainText.Text = await GetRainStatus(pos) == RainStatus.Rain ?
                    "It's possible to rain, you'd better take an umbrella" :
                    "It will be a bright an shiny day, go out and enjoy";
            }
            catch
            {
                RainText.Text = "Got an error while getting weather";
            }
            break;

        case GeolocationAccessStatus.Denied:
            RainText.Text = "I cannot check the weather if you don't give me the access to your location...";
            break;

        case GeolocationAccessStatus.Unspecified:
            RainText.Text = "I got an error while getting location permission. Please try again...";
            break;
    }
}
C#

If the user allows access to the location data, we get the current position with GetGeopositionAsync and then we use this position to get the rain status, using the open weather map API. The GetRainStatus method is:

private async Task GetRainStatus(Geoposition pos)
{
    var client = new OpenWeatherMapClient("YourPrivateId");
    var weather = await client.CurrentWeather.GetByCoordinates(new Coordinates()
    {
        Latitude = pos.Coordinate.Point.Position.Latitude,
        Longitude = pos.Coordinate.Point.Position.Longitude
    });
    return weather.Precipitation.Mode == "no" ? RainStatus.Sun : RainStatus.Rain;
}
C#

To use the OpenWeather API, you must register with the site and get an API key. For low usage, the key and usage is free. You can register at http://openweathermap.org/appid

When you run the program, you are able to know if you will need to take an umbrella to go out:

Conclusions

As you could see, working with sensors is very easy and it can offer a better experience for your users. You can integrate them with your apps in many different ways. In this post, I’ve shown how to use the weather API to query if it will rain in your location, a simple, but useful program.

All source code for this project is in https://github.com/bsonnino/GeoLocation

2 thoughts on “Working with Sensors in UWP–Part 5–Geolocation”

  1. Ammar Shaukat says:
    26 July 2018 at 06:46

    Is there a way to force C# API to fetch the Location coordinates through GPS rather than other sources ?

    Reply
    1. bsonnino says:
      22 November 2018 at 17:07

      AFAIK, you cannot force the source to be only the GPS, but you can set the desired accuracy to HIGH and get the source from the GeoPosition that you get and discard the ones that don’t come from the GPS

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • May 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • June 2024
  • November 2023
  • October 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • April 2020
  • March 2020
  • January 2020
  • November 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • October 2015
  • August 2013
  • May 2013
  • February 2012
  • January 2012
  • April 2011
  • March 2011
  • December 2010
  • November 2009
  • June 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • July 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • Development
  • English
  • Português
  • Uncategorized
  • Windows

.NET AI Algorithms asp.NET Backup C# Debugging Delphi Dependency Injection Desktop Bridge Desktop icons Entity Framework JSON Linq Mef Minimal API MVVM NTFS Open Source OpenXML OzCode PowerShell Sensors Silverlight Source Code Generators sql server Surface Dial Testing Tools TypeScript UI Unit Testing UWP Visual Studio VS Code WCF WebView2 WinAppSDK Windows Windows 10 Windows Forms Windows Phone WPF XAML Zip

  • Entries RSS
  • Comments RSS
©2025 Bruno Sonnino | Design: Newspaperly WordPress Theme
Menu
  • Home
  • About