在WordPress上实现Google Maps JS

时间:2016-08-19 作者:JoaMika

我希望在我的wordpress网站上尽可能高效地实现这段代码

https://developers.google.com/maps/documentation/javascript/styling

我只希望JS加载到我将使用地图的帖子/页面上。我不知道该怎么开始!

EDIT:

如果我在函数中使用排队部分会怎么样?这是一个好的构造吗?

function x_shortcode_google_map( $atts, $content = null ) {
  extract( shortcode_atts( array(
    \'id\'           => \'\',
    \'class\'        => \'\',
    \'style\'        => \'\',
    \'lat\'          => \'\',
    \'lng\'          => \'\',
    \'drag\'         => \'\',
    \'zoom\'         => \'\',
    \'zoom_control\' => \'\',
    \'height\'       => \'\',
    \'hue\'          => \'\',
    \'no_container\' => \'\',
    \'api_key\'      => \'\'
  ), $atts, \'x_google_map\' ) );

  static $count = 0; $count++;

  $id           = ( $id           != \'\'     ) ? $id : \'x-google-map-\' . $count;
  $class        = ( $class        != \'\'     ) ? \'x-map x-google-map \' . esc_attr( $class ) : \'x-map x-google-map\';
  $style        = ( $style        != \'\'     ) ? \'style="\' . $style . \'"\' : \'\';
  $height       = ( $height       != \'\'     ) ? \'style="padding-bottom: \' . $height . \';"\' : \'\';
  $no_container = ( $no_container == \'true\' ) ? \'\' : \' with-container\';

  $js_params = array(
    \'lat\'         => ( $lat          != \'\'     ) ? $lat : \'40.7056308\',
    \'lng\'         => ( $lng          != \'\'     ) ? $lng : \'-73.9780035\',
    \'drag\'        => ( $drag         == \'true\' ),
    \'zoom\'        => ( $zoom         != \'\'     ) ? $zoom : \'12\',
    \'zoomControl\' => ( $zoom_control == \'true\' ),
    \'hue\'         => ( $hue          != \'\'     ) ? $hue : \'\',
  );

  $data = cs_generate_data_attributes( \'google_map\', $js_params );

  $script_url = \'https://maps.googleapis.com/maps/api/js\';

  if ( $api_key ) {
    $api_key = esc_attr( $api_key );
    $script_url = add_query_arg( array( \'key\' => $api_key ), $script_url );
  }

  wp_register_script( \'cs-google-maps\', $script_url );
  wp_enqueue_script( \'cs-google-maps\' );

  $output = "<div id=\\"{$id}\\" class=\\"{$class}{$no_container}\\" {$data} {$style}><div class=\\"x-map-inner x-google-map-inner\\" {$height}></div>" . do_shortcode( $content ) . "</div>";

  return $output;
}

add_shortcode( \'x_google_map\', \'x_shortcode_google_map\' );

1 个回复
SO网友:Aamer Shahzad

首先,以正确的方式将Google Maps API js排队。查找连接的函数wp_enqueue_scriptswp_enqueue_script() 将Google Maps API排队

function wp_mk_scripts() {
    if ( is_singular() ) {
        wp_enqueue_script( \'wp-mk-maps-js\', \'https://maps.googleapis.com/maps/api/js\', array( \'jquery\' ), null, true );
        wp_enqueue_script( \'wp-mk-gmaps-function\', get_stylesheet_directory_uri() . \'/js/maps.js\', array( \'jquery\' ), null, true );
    }
}
add_action( \'wp_enqueue_scripts\', \'wp_mk_scripts\' );
然后在theme\\u文件夹/js/maps中。js粘贴地图代码<script></script> 中的标记Style Google Maps

现在拨打<div id="map"></div> div模板中的任意位置以显示地图。

相关推荐