WordPressで住所をカスタムフィールドで入力した際に、ついでにそのカスタムフィールドの情報を引っ張ってきてGoogle Mapを利用する方法。
目次
1.住所から緯度経度を取得
phpテンプレート
<?php
function strAddrToLatLng( $strAddr )
{
$strRes = file_get_contents(
'http://maps.google.com/maps/api/geocode/json'
. '?address=' . urlencode( mb_convert_encoding( $strAddr, 'UTF-8' ) )
. '&sensor=false'
);
$aryGeo = json_decode( $strRes, TRUE );
if ( !isset( $aryGeo['results'][0] ) )
return '';
$strLat = (string)$aryGeo['results'][0]['geometry']['location']['lat'];
$strLng = (string)$aryGeo['results'][0]['geometry']['location']['lng'];
return $strLat . ',' . $strLng;
}
$map_latlon = post_custom('map');
?>
これで$map_latlonの値は、カスタムフィールド'map'の値の住所の緯度経度が代入されました。
2.Google Map apiで地図を表示
phpテンプレート
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window,'load',function(){
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(<?php echo strAddrToLatLng($map_latlon); ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var mp = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo strAddrToLatLng($map_latlon); ?>),
map: mp
});
});
</script>
<div id="map" style="width:100%; height: 500px;"></div>
id="map" style="width:100%; height: 500px;の部分でお好みのサイズにカスタマイズしてください。
WordPressのプラグインでカスタムフィールドから地図を表示する方法もありますが、細かい設定をしたい場合はこちらの方法が便利です。
今現在の設定ですとGoogle Mapの拡大縮小を禁止しています。
3.Google Mapのカスタマイズ
| マウスホイール | scrollwheel |
| ダブルクリック | disableDoubleClickZoom |
| ドラッグ | draggable |
| 航空写真切替 | mapTypeControl |
| 移動コントロール | panControl |
| 拡大縮小バー | zoomControl |
| スケール | scaleControl |
| ストリートビュー | streetViewControl |
phpテンプレート
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(<?php echo strAddrToLatLng($map_latlon); ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
draggable: false,
disableDoubleClickZoom: true,
panControl: true
};
このvar mapOptions = {}の中にカスタマイズ用のプロパティを入れていけば好みのGoogle Mapの埋め込みが実装可能になります。