住所でGoogle Mapを表示するショートコードタグ

またまたショートコードタグですが、今回はGoogle Mapsを表示するショートコードタグです。GeoCodingを利用しているので住所をタグで囲むだけでマップが表示されます。これも前回の翻訳タグ同様、GoogleのサンプルJavaScriptをほとんどそのままラッピングしているだけです。
// [gmapwithgc (nosinglemsg="message" id="id" width="width" height="height" zoom="zoom")]address[/gmaiwithgc]
// googleマップを住所で表示
function gmapwithgc_func($atts, $content='') {
  extract(shortcode_atts(array(
    'nosinglemsg' => '',
    'id' => 'gmap0',
    'width' => '500px',
    'height' => '300px',
    'zoom' => '14',
  ), $atts));
  if($nosinglemsg != "" and !is_single()){
    return $nosinglemsg;
  } else {
    return <<<_EOT_
    <script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=●●" type="text/javascript"></script>
      <div id="$id" style="width: $width; height: $height"></div>
      <script type="text/javascript">
    map = new GMap2(document.getElementById("$id"));
    geocoder = new GClientGeocoder();
        geocoder.getLatLng("$content",
        function(point) {
      if (!point) {
        alert("$content" + " not found");
      } else {
        map.setCenter(point, $zoom);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml("$content");
      }
    });
    </script>
_EOT_;
  }
}
add_shortcode('gmapwithgc', 'gmapwithgc_func');

ソースの●●部分はご利用のGoogle Maps APIキーに置き換えてください。
使い方は記事内に以下のようなタグを入れると、Google Mapsが表示されます。
[gmapwithgc]東京タワー[/gmapwithgc]

サイズや拡大率を指定できます。
[gmapwithgc width=”400px” height=”350px” zoom=”10″]富士山[/gmapwithgc]

シングルページのみマップを表示する場合は以下のようにシングルページ以外で表示されるメッセージを指定してください。
[gmapwithgc nosinglemsg=”記事のタイトルをクリックしてシングル表示にしてください”]東京タワー[/gmapwithgc]

ひとつの記事に複数タグを入れたい場合は重複しないidを指定してください。
[gmapwithgc id=”gmap2″]東京タワー[/gmapwithgc]

以下は実際にタグを埋め込んだサンプルです。

コメントする

トラックバックする

トラックバック用URL:


    サイト内検索

    プロフィール

  • 顔絵
  • kotani(こたに)

    30台後半になって突然脱サラ。フリーのスクリプト系プログラマーとして独立を目論む謎のおやぢ。東京都在住。趣味は古本屋巡り、文具いぢり、機械いぢり、B級グルメ探索等々多岐にわたる。PCを使う作業に関しては何でもかんでも自動化したがる自動化オタク。