博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Windows Phone 7 下的天气预报

Posted on 2011-03-09 09:26  星尘的天空  阅读(440)  评论(0编辑  收藏  举报

转载地址:http://www.gwewe.com/dev/featured/1011095792.html

对于天气预报的获取,我使用的是Yahoo的API,首先,我们学习一下YAHOO的天气预报API一些使用方法。

yahoo天气预报的url是

http://weather.yahooapis.com/forecastrss?w=2151330&u=c

说说里面参数代表的意思:

参数w对应各个地方在yahoo数据库中的WOEID,如北京的WOEID是2151330,目前也可以用参数p来代替w,不过官方还是推荐用w,貌似p是计划要被取消的。参数u用于确定温度的单位(c是摄氏度f是华氏度)。对于中国(国外没比较)的天气查询来说,YAHOO相对无论从能查到的地方还是预报的内容都是比较全的。

详细的API文档:http://developer.yahoo.com/weather/

获取地址编号

地址编号必须是一个WOEID,你可以通过雅虎的天气预报首页查询你需要的地址编号。这个编号在
你想要的那个城市天气预报页的URL中。你也可以通过在首页中输入你的邮政编码查询WOEID。例如,你想查询广州的天气情况,这个城市的天气预报页的URL是
http://weather.yahooapis.com/forecastrss?p=CHXX0037&u=c,所以它的WOEID是0037.

当向YAHOO发送天气预报的请求后,接收到的XML数据类似下面的
 

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
<title>Yahoo! Weather - Guangzhou, CH</title>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Guangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0037_c.html</link>
<description>Yahoo! Weather for Guangzhou, CH</description>
<language>en-us</language>
<lastBuildDate>Sun, 07 Nov 2010 7:00 pm CST</lastBuildDate>
<ttl>60</ttl>
<yweather:location city="Guangzhou" region="" country="CH"/>
<yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
<yweather:wind chill="25" direction="340" speed="6.44" />
<yweather:atmosphere humidity="34" visibility="7" pressure="982.05" rising="0" />
<yweather:astronomy sunrise="5:34 am" sunset="5:45 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url>
</image>
<item>
<title>Conditions for Guangzhou, CH at 7:00 pm CST</title>
<geo:lat>23.12</geo:lat>
<geo:long>113.3</geo:long>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Guangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0037_c.html</link>
<pubDate>Sun, 07 Nov 2010 7:00 pm CST</pubDate>
<yweather:condition text="Clear" code="31" temp="25" date="Sun, 07 Nov 2010 7:00 pm CST" />
<description>
<![CDATA[
<img src="/userfiles/2010/11/024458f7g.gif"/><br />
<b>Current Conditions:</b><br />
Clear, 25 C<BR />
<BR /><b>Forecast:</b><BR />
Sun - Clear. High: 28 Low: 16<br />
Mon - Mostly Sunny. High: 29 Low: 16<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Guangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0037_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
]]>
</description>
<yweather:forecast day="Sun" date="7 Nov 2010" low="16" high="28" text="Clear" code="31" />
<yweather:forecast day="Mon" date="8 Nov 2010" low="16" high="29" text="Mostly Sunny" code="34" />
<guid isPermaLink="false">CHXX0037_2010_11_07_19_00_CST</guid>
</item>
</channel>
</rss>
<!-- api2.weather.sg1.yahoo.com uncompressed/chunked Sun Nov 7 06:23:35 PST 2010 -->




最重要的是后面几行,查询当天和第二天的天气。
 

<yweather:forecast day="Sun" date="7 Nov 2010" low="16" high="28" text="Clear" code="31" />
<yweather:forecast day="Mon" date="8 Nov 2010" low="16" high="29" text="Mostly Sunny" code="34" />




即我们需要用到的节点是 yweather:forecase。

到这里大概了解YAHOO的API使用后,我们来做一个在Windows Phone 7 下获取天气预报的程序。

首先新建一个Silverlight for Windows Phone 7的工程,命名为MyYahooWeather,首先布置一下界面,MainPage.xaml的代码如下:
 

<phone:PhoneApplicationPage 
x:Class="MyYahooWeather.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Margin="12,17,12,28">
<TextBlock x:Name="ApplicationTitle" Text="My Yahoo Weather" FontSize="40"/>
<Rectangle Width="460" Height="5" Fill="Blue"/>
<TextBlock x:Name="City" Text="广?州Y" FontSize="32"/>
<Rectangle Width="460" Height="5" Fill="Blue"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Rectangle Margin="12,18,6,0">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/bk.jpg" Stretch="None"></ImageBrush>
</Rectangle.Fill>
</Rectangle>

<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" Height="200">
<Image x:Name="WeatherIcon2" Source="Images/cloudy.png" Width="300" Height="200" Margin="0,0,-60,-20" />
<StackPanel Orientation="Vertical" Width="250">
<TextBlock x:Name="date1" Text="2010-11-5" Margin="10,20,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="day1" Text="Mon" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="condition1" Text="Rain" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="temp1" Text="5-6C" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
</StackPanel>
</StackPanel>

<StackPanel Orientation="Horizontal" Height="200">
<Image x:Name="WeatherIcon3" Source="Images/cloudy.png" Width="300" Height="200" Margin="0,0,-60,-20" />
<StackPanel Orientation="Vertical" Width="250">
<TextBlock x:Name="date2" Text="2010-11-5" Margin="10,20,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="day2" Text="Mon" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="condition2" Text="Rain" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
<TextBlock x:Name="temp2" Text="5-6C" Margin="10,1,0,0" FontSize="32" VerticalAlignment="Center" />
</StackPanel>
</StackPanel>

</StackPanel>
</Grid>
</Grid>
</phone:PhoneApplicationPage>


在解决方案里面,右击当前解决方案,添加一个文件夹,命名为Images,把背景图片我天气预报用到的图片加进去。

打开MainPage.xaml.cs文件,添加通讯代码。以下是部分代码:
 

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://weather.yahooapis.com/forecastrss?p=CHXX0037&u=c"));
}

private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
XDocument doc = new XDocument();
doc = XDocument.Parse(e.Result);

bool forecastTomorrow = true;

foreach (XElement element in doc.Descendants("channel").First().Descendants("item").Nodes())
{
if (element.ToString().Contains("<yweather:forecast"))
{
string date = element.Attribute("date").Value;
string day = element.Attribute("day").Value;
string conditions = element.Attribute("text").Value;
string tempLow = element.Attribute("low").Value;
string tempHigh = element.Attribute("high").Value;
string code = element.Attribute("code").Value;

int weatherCode = Convert.ToInt16(code);
string imageName = weatherImage(weatherCode);

Uri uri = new Uri("Images/" + imageName + ".png", UriKind.Relative);
ImageSource img = new BitmapImage(uri);

if (forecastTomorrow)
{
date1.Text = date;
day1.Text = Eday2Cday(day);
condition1.Text = conditions;
temp1.Text = tempLow + "-" + tempHigh + "°?C";
WeatherIcon2.Source = img;
forecastTomorrow = false;
}
else
{
date2.Text = date;
day2.Text = Eday2Cday(day);
condition2.Text = conditions;
temp2.Text = tempLow + "-" + tempHigh + "°?C";
WeatherIcon3.Source = img;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

运行效果如下图所示: