C#で、住所から緯度・経度を検索する(geocoding.jp利用)


住所から簡単に緯度・経度を検索してくれるWebAPIを、geocoding.jpが提供してくれているらしいので、これを利用したWindowsのアプリを作成してみました。

プログラムは、本記事の最後にあるDownloadから取得可能です。




データ取得の処理

まずは、画面構成です。
検索するだけなので、検索キーワード、検索ボタンと結果の3つだけがあるシンプルな構成です。


プログラムは、検索ボタンクリック時のハンドラだけです。
APIがシンプルなので、処理も簡単に記述する事ができます。

//*********************************************************************
/// <summary> 検索ボタンクリック時のハンドラ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//*********************************************************************
private void button1_Click( object sender, EventArgs e ) {
 
    //----------------------------------------------------
    // 検索クエリを組み立てる
    // (HttpUtilityの使用には,System.Webの参照設定が必要)
    //----------------------------------------------------
    String queryStr = HttpUtility.UrlEncode( txtQuery.Text );
    String url      = "http://www.geocoding.jp/api/?v=1.1&q=" + queryStr;
 
 
    //---------------------------
    // サーバーにクエリを投げる
    //---------------------------
    WebResponse response = null;
    try {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";
        request.UserAgent   = "GeoLookup/1.0 (Language=CS)";
        request.ContentType = "text/xml";
        response = request.GetResponse();
    } catch( WebException  ex ) {
        response = ex.Response;
    }
 
    //---------------------------------
    // 応答をxmlドキュメントとして取得
    //---------------------------------
    XmlDocument doc;
    doc = new XmlDocument();
    doc.Load(response.GetResponseStream());
 
    //エラーチェック
    if ( doc.SelectNodes( "/result/error" ).Count > 0 ) {
        txtResult.Text = "検索エラー :" + doc.SelectNodes( "/result/error" ).Item(0).InnerText;
        return;
    }
 
    //--------------------------------
    // 取得した応答データを解析する
    //--------------------------------
    string lat             = selectTextToDef( doc, "/result/coordinate/lat", "" );
    string lng             = selectTextToDef( doc, "/result/coordinate/lng", "" );
    string lat_dms         = selectTextToDef( doc, "/result/coordinate/lat_dms", "" );
    string lng_dms         = selectTextToDef( doc, "/result/coordinate/lng_dms", "" );
    string needs_to_verify = selectTextToDef( doc, "/result/needs_to_verify", "" );
    string google_maps     = selectTextToDef( doc, "/result/google_maps", "" );
 
    //--------------------------------
    // 解析した結果を出力する
    //--------------------------------
    txtResult.Text  = "緯度     : " + lat +  Environment.NewLine;
    txtResult.Text += "経度     : " + lng +  Environment.NewLine;
    txtResult.Text += "緯度(dms): " + lat_dms +  Environment.NewLine;
    txtResult.Text += "経度(dms): " + lng_dms +  Environment.NewLine;
    txtResult.Text += "住所     : "       + google_maps     +  Environment.NewLine;
    txtResult.Text += "needs_to_verify: " + needs_to_verify +  Environment.NewLine;
}
 
//*********************************************************************
/// <summary> XMLドキュメントから指定されたノードの値を返す
///           指定されたノードが存在しない場合は,defaultValueを返す
/// </summary>
/// <param name="doc">          検索元xmlドキュメント  </param>
/// <param name="query">        検索を行うノード(xpath)</param>
/// <param name="defaultValue"> ノードが存在しない場合のデフォルト値</param>
/// <returns>                   検索したノードの値(innerText)</returns>
//*********************************************************************
private string selectTextToDef( XmlDocument doc, string query, string defaultValue = "" ) {
    XmlNodeList nodeList = doc.SelectNodes( query );
    if ( nodeList.Count <= 0 ) {
        return defaultValue;
    } 
 
    return nodeList.Item(0).InnerText;
}



HttpWebRequestと、XmlDocumentを使用しているおかげで説明すべき事が無いくらい簡単に作る事ができました。
あえて注意点を挙げるとすれば、検索クエリのURLエンコードで使用しているHttpUtilityクラスを使用する上で、System.Webを参照設定するのが必要なことぐらいです。



ダウンロード

.NetFramework3.0のランタイムを使用しています。

download: GeoLookup.zip

関連記事

コメントを残す

メールアドレスが公開されることはありません。