1. Problem
Your aim is to obtain an
application that is able to tell the user what time the sun will rise
and set today in the user's location.
2. Solution
There are several ways to find
out the time of sunrise and sunset (for example, through web services,
libraries, and complex calculations). This recipe shows how to access
and use a certain property in order to explore the potential of Location
Services. There are several ways to calculate the times from latitude
and longitude values, and we will let you choose which best suits your
needs.
3. How It Works
You will use
information about the user's position, obtained from the device, to
calculate the time of sunrise and sunset, simulating with a helper class
the behavior of a service to calculate them
4. The Code
To start writing code for this recipe we need two members field:
GeoCoordinateWatcher geo = new GeoCoordinateWatcher();
SuntimesHelper ssc = new SuntimesHelper();
SuntimesHelper is a
class written by us, whose code is based on algorithms that are easily
available on the Internet. This class exposes two methods, called GetSunRise and GetSunSet, as you can see in Figure 1.
void geo_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (!e.Position.Location.IsUnknown)
{
bool isSunrise = false;
bool isSunset = false;
DateTime sunrise = SuntimesHelper.GetSunRise(e.Position.Location.Latitude,
e.Position.Location.Longitude, DateTime.Now, out isSunrise);
DateTime sunset = SuntimesHelper.GetSunSet(e.Position.Location.Latitude,
e.Position.Location.Longitude, DateTime.Now, out isSunset);
geo.Stop()
}
}
It is important when working
with the position to point out that the applications used for localizing
consume battery power. Although we may sound repetitive, it is
important to provide the best possible user interaction in our
applications. Therefore, remember to stop the use of GeoCoordinateWatcher when you don't need it anymore.
5. Usage
From Visual Studio 2010, deploy
the application to a physical device and watch it calculating sunrise
and sunset from your position.