スマートフォン用のGoogleマップの実装

スマートフォンの場合の地図の実装です。
スマートフォンの場合は、javascriptが使用可能ですので、基本的にはPCの場合と変わらず、画像出力サイズのみをある程度固定してやった方が良いというぐらいです。

スマートフォン用ということで、WPtouchなどのテンプレートのfunctions.phpにショートコードを処理するためのプログラムを追加します。

function sc_gmap($atts, $content = null){

	extract(shortcode_atts(array(
		"lat" => '35.681766,139.766089',
		"text" => '',
		"target" => 'map_canvas',
		"width" => '280px',
		"height" => '210px',
		"class" => 'alignnone'
	), $atts));

	if(empty($lat) || !preg_match('/[0-9.,]+/',$lat)){ return(''); }
	else{
		$retmap  = '<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>' . "n";
		$retmap .= '<script type="text/javascript">' . "n";
		$retmap .= 'function initialize() {' . "n";
		$retmap .= 'var centerPos = new google.maps.LatLng(' . $lat . ');' . "n";
		$retmap .= 'var mapOptions = {' . "n";
		$retmap .= "zoom : 17,ncenter : centerPos,nmapTypeId : google.maps.MapTypeId.ROADMAP,n";
		$retmap .= "mapTypeControl : true,nscaleControl : true,nnavigationControl : truen";
		$retmap .= '};' . "n";
		$retmap .= 'var map = new google.maps.Map(document.getElementById("' . $target . '"),mapOptions);' . "n";
		$retmap .= 'var markerOptions = {' . "n";
		$retmap .= "position : centerPos,nmap : map,n";
		$retmap .= 'title : "' . $text . '"' . "n";
		$retmap .= '};' . "n";
		$retmap .= "var marker = new google.maps.Marker(markerOptions);n";
		$retmap .= '}' . "n";
		$retmap .= '</script>' . "n";
		$retmap .= '<div id="' . $target . '" style="width: 280px; height: 210px;"></div>' . "n";
		$retmap .= '<p><a href="http://maps.google.com/maps?ll=' . $lat . '&q=' . urlencode($text) . '@' . $lat . '&z=17">地図アプリで開く</a></p>' . "n";
		return($retmap);
	}
}
add_shortcode("map", "sc_gmap");

PC用と異なるのは、widthとheightのパラメータ値は使用せず、サイズはコード内で固定しています。
また、iPhoneなどではGoogleマップアプリが使用できるため、Mapアプリで開くためのリンクを追加しています。
(AndroidではアプリではなくGoogleマップのページが開きます)

PCの場合と同様に、このコードがページのロード時に読み込まれるよう、 bodyタグにonloadイベントを追加しinitialize()を呼び出します。

<body onload="initialize();">

Googleマップをショートコードで実装するにコメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です