かみやんの技術者ブログ

主にプログラムの話です

C#でGoogle Static Maps APIの使い方(ソースコードあり)

C#Google Static Maps APIで地図画像をダウンロードする方法を紹介します。
まず、

下記が、C#でのコードです。

        //Author : Eiji Kamiya 2009/10/4
        //Licence : BSD

        //Google Static Maps APIで画像を取得し、ファイルに保存する
        private void SaveGoogleMap(string url, string fileName)
        {
            try {
                WebClient web = new WebClient();
                using (FileStream fs = new FileStream(fileName, FileMode.Create)) {
                    using (BufferedStream bs = new BufferedStream(web.OpenRead(url))) {
                        byte[] buf = new byte[4096];
                        int size;
                        while ((size = bs.Read(buf, 0, buf.Length)) != 0) {
                            fs.Write(buf, 0, size);
                        }
                    }
                }
                MessageBox.Show(fileName + "を保存しました。", "成功", MessageBoxButtons.OK);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Error at SaveGoogleMap", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        //メニュー:つくばの地図をGoogle Static Maps APIで取得してファイルに保存する
        private void saveTsukubaMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //center : 画像中心位置(緯度経度、単位:度)
            //zoom : ズームレベル0〜19
            //maptype:satellite or roadmap
            //size : 画像サイズ(単位:ピクセル)
            //sensor : false
            //format : jpg or gif
            //key : MAPS_API_KEY
            string url = "http://maps.google.com/maps/api/staticmap?" +
                "center=36.084782,140.110584&zoom=18&maptype=roadmap&" +
                "size=640x640&sensor=false&format=gif&key=" + MAPS_API_KEY;
            SaveGoogleMap(url, "Route\\Tsukuba.gif");
        }

SaveGoogleMap()メソッドにURLと保存先のファイル名を入力するだけです。
画像を大量にダウンロードすると止められたり(1日にDLできる上限がある)します。これでGoogle Earthみたいなものを作ったりカーナビみたいなアプリを作るとGoogleに怒られると思います。自己責任で利用ください。