ASP.NETで、YahooローカルサーチのデータをGridViewに表示してみる
Yahooさんのローカルサーチは電話帳データ等から施設情報を抽出できる、かなり便利なAPIなのですが、ASP.NETから呼び出す例としてはあまり参考になるサイトがなかったので、ここに書いてしまいます。
仕様
電話帳データより「コンビニ」情報を取得し、GridViewにバインドする最短サンプルです。
クラスのジェネリックを使ってますが、ここは好みで改変して下さい。
「座標あるのに地図は?」と聞かないで下さい。それはJavaScriptの領域なので、他のサイトを参考にして頂いたほうが良いと思います。リクあれば書きますが。
yls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="yls.aspx.cs" Inherits="yls" %> <html> <head></head> <body> <form id="form1" runat="server"> <asp:GridView ID="gvResult" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Name" /> <asp:BoundField DataField="Yomi" /> <asp:BoundField DataField="Address" /> <asp:BoundField DataField="Coordinates" /> </Columns> </asp:GridView> </form> </body> </html>
yls.aspx.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Xml; using System.Net; using System.Configuration; public partial class yls : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<feature> features = new List<feature>(); string strXmlFormat = "http://search.olp.yahooapis.jp/OpenLocalPlatform/V1/localSearch" + "?appid={0}&cid={1}&gc={2}"; string strXmlUrl = String.Format(strXmlFormat , <Yahoo アプリケーションID> , "d8a23e9e64a4c817227ab09858bc1330" , "0205001"); string strXML = ""; using (WebClient client = new WebClient()) { client.Encoding = System.Text.Encoding.UTF8; strXML = client.DownloadString(strXmlUrl); } XmlDocument doc = new XmlDocument(); XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable); xnm.AddNamespace("y", "http://olp.yahooapis.jp/ydf/1.0"); doc.LoadXml(strXML); doc.PreserveWhitespace = false; //成功の可否を取得 string strSuccess = doc.SelectSingleNode("//y:ResultInfo/y:Status", xnm).InnerText; if (strSuccess != "200") return; XmlNodeList nodes = doc.SelectNodes("//y:Feature", xnm); // <Feature>でループ foreach (XmlNode node in nodes) { feature Feature = new feature(); Feature.Name = node.SelectSingleNode("y:Name", xnm).InnerText; Feature.Yomi = node.SelectSingleNode("y:Property/y:Yomi", xnm).InnerText; Feature.Address = node.SelectSingleNode("y:Property/y:Address", xnm).InnerText; Feature.Coordinates = node.SelectSingleNode("y:Geometry/y:Coordinates", xnm).InnerText; features.Add(Feature); } gvResult.DataSource = features; gvResult.DataBind(); } } public class feature { string _name = "", _yomi = "", _address = "", _coordinates = ""; public string Name { set { _name = value; } get { return _name; } } public string Yomi { set { _yomi = value; } get { return _yomi; } } public string Address { set { _address = value; } get { return _address; } } public string Coordinates { set { _coordinates = value; } get { return _coordinates; } } }
補足
- 実際の運用では地域や座標+半径で絞ったり、コンビニに限らず他の商業施設や公共施設を出すわけですが、それは下記のYahoo公式リファレンスに従ってパラメータを変えて、csファイルのstrXmlUrlを書き換えるだけで可能です。
- レスポンスXMLにNameSpaceがあるため、それに関連した処理も載せてあります。下記MS公式でもありますが、ポイントは「//y:Feature」といった独特な記述ですね。結構手間取った…