[开发笔记]WordPress百度地图ShortCode

By | 2015 年 8 月 26 日

调用百度地图JavaScript API:
【APIKEY】换成自己的APIKEY

function extras_scripts() {
  wp_enqueue_script( 'map-api', 'http://api.map.baidu.com/api?v=2.0&ak=【APIKEY】', array(), NULL, false );
}
add_action( 'wp_enqueue_scripts', 'extras_scripts' );

短代码部分代码:

/**
 * 百度地图.
 * [baidumap id=map1 class="am-sm-12" height=350 address=广东省广州市 ]
 */
if ( ! function_exists( 'baidumap' ) ) :
function baidumap($attr) {
$attr['id'] =	empty($attr['id']) ? '1' : $attr['id'];
$attr['class'] = empty($attr['class']) ? '' : $attr['class'];
$attr['height'] = empty($attr['height']) ? '300' : $attr['height'];
return '<div id="baidumap-'.$attr['id'].'" class="'.$attr['class'].'" style="height:'.$attr['height'].'px"></div>
  <script type="text/javascript">
  // 百度地图API功能
  addMap("baidumap-'.$attr['id'].'","'.$attr['address'].'");
  function addMap(id,addr){
    var map = new BMap.Map(id);
    var myGeo = new BMap.Geocoder();
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(addr, function(point){
  	  if (point) {
  	    map.centerAndZoom(point, 18);
  	    map.addOverlay(new BMap.Marker(point));
  	  }
  	}, "");
    // 创建地址解析器实例
  	var scaleControl = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
  	scaleControl.setUnit(BMAP_UNIT_METRIC);
  	map.addControl(scaleControl);
  	var navControl = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:1});
  	map.addControl(navControl);
  	var overviewControl = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:true});
  	map.addControl(overviewControl);
    }
</script>';
}
add_shortcode('baidumap', 'baidumap');
endif;

CSS代码:

/* 百度地图 */
[id*=baidumap-] img{max-width: none;}

发表评论

电子邮件地址不会被公开。 必填项已用*标注