住所でGoogle Mapを表示するショートコードタグ
2008/04/25
またまたショートコードタグですが、今回は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&v=2.x&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]
以下は実際にタグを埋め込んだサンプルです。
シングルページにするとマップが表示されます