加载谷歌地图时的ReferenceError

时间:2015-08-05 00:26:38

标签: wordpress google-maps-api-3

在页面中加载地图时,我得到[错误] ReferenceError:无法找到变量:google global code(foundation.js,第21行)

我不是代码专家,所以如果有人能告诉我问题在哪里,我将不胜感激。谢谢。

以下是代码:

的JavaScript

function makeMap() {
    var snazzyMap = JSON.parse(wpGlobals.mapOptions);
    var map = new google.maps.Map(document.getElementById('map'), {
        center : new google.maps.LatLng(13.72638, 100.54029),
        zoom : 15,
        mapTypeId : google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        styles : snazzyMap
    });
    var marker = new google.maps.Marker({
        position : new google.maps.LatLng(13.72638, 100.54029)
    });
    marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', makeMap);

PHP

add_action('wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {
    wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', array(), null, true);
    wp_enqueue_script('script', get_stylesheet_directory_uri().'/js/foundation.js', array('google-maps'), null, true);
    wp_localize_script('script', 'wpGlobals', array(
        'mapOptions' = > file_get_contents(dirname(__FILE__).'/google_map_style.json')
        )
    );
}

JSON

[{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#b8d4a4"},{"visibility":"on"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"transit.station.rail","elementType":"labels.text","stylers":[{"visibility":"on"},{"gamma":"1"},{"lightness":"0"},{"saturation":"0"}]},{"featureType":"transit.station.rail","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#8490c8"},{"visibility":"on"}]}]

CSS

#map {
    width: 580px;
    height: 250px;
}

HTML

<div id="map"></div>

1 个答案:

答案 0 :(得分:0)

正如我在body标签内的html文件中所看到的,http://www.ceerd.net/wp-content/themes/ceerd/js/foundation.js文件在 293 一次添加两次,在 300 时添加一次。在此之间您添加了导致问题https://maps.googleapis.com/maps/api/js?v=3.exp&#038;sensor=false的谷歌地图脚本Can't find variable: google

原因 - 第一次包含foundation.js是使用谷歌对象,但直到那时它才可用。由于未加载谷歌脚本。

包含 google地图脚本后,请包含 foundation.js 文件。