我在尝试将 Google map 添加到 WordPress 主题时遗漏了一些内容。当我使用插件Debug Bar时对于 WordPress 开发,它会抛出以下 JavaScript 错误:
Script error.
line 0
我不确定问题出在哪里,在开始研究后我认为我的问题是当我没有async defer
时调用Map的API时:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
阅读后:
Step 2: Add a map with a marker
我进行了研究以解决我认为的问题,并且遇到了:
- How to add defer=“defer” tag in plugin javascripts?
- https://wordpress.stackexchange.com/questions/38319/how-to-add-defer-defer-tag-in-plugin-javascripts
- Script Loader tag
functions.php的代码:
function call_the_js_files() {
if (is_page_template('page-foo.php')) :
wp_enqueue_script( 'google_api', 'https://maps.googleapis.com/maps/api/js?key=AP_KEY&callback=initMap', array( 'jquery' ), '', true );
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'google_api' !== $handle )
return $tag;
return str_replace( ' src', ' async defer src', $tag );
}, 10, 2 );
wp_enqueue_script( 'google_map', get_template_directory() . '/js/google.js', array( 'jquery' ), '', true );
endif;
add_action( 'wp_enqueue_scripts', 'call_the_js_files' );
google.js的代码:
( function( $ ) {
$(function initMap() {
var uluru = {
lat: 11111111,
lng: 222222222
};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 15,
center: uluru
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: uluru,
map: map,
icon: iconBase + 'parking_lot_maps.png'
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
} )( jQuery );
当我查看源代码时,我得到:
<script type='text/javascript' async defer src='https://maps.googleapis.com/maps/api/js?key=API_KEY;callback=initMap'></script>
<script type='text/javascript' src='site/location/for/js/google.js'></script>
但我仍然在调试栏上抛出错误。我是否遗漏或做错了什么?我在渲染 map 时没有遇到任何问题,我遇到的唯一问题是 JavaScript 错误。在开发中,我当前在 Google 上的 API 设置为 None
受到限制。
当我在 google map script error line 0
下进一步研究时我遇到了Google Maps Script error in Onion.js但我已经在运行<meta http-equiv="X-UA-Compatible" content="IE=edge">
在我的 header.php 中。
最佳答案
更改您的functions.php以包含如下内容。谷歌地图 API 依赖于您的脚本。
<?php
function theme_js() {
wp_enqueue_script( 'gmap', '//maps.googleapis.com/maps/api/js?key=YOuR_KEY&callback=initMap', array ('theme_js'), '1.0', true );
wp_register_script( 'theme_js', get_stylesheet_directory_uri() . '/js/hotelloc.js', array(), '1.0', true );
}
add_action('wp_footer', 'theme_js');
?>
关于javascript - 为什么我的 WordPress 主题中出现 Google map JavaScript 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555887/