Skip to content Skip to sidebar Skip to footer

Why Am I Getting A Google Map Javascript Error In My Wordpress Theme?

I'm missing something when trying to add a Google Map to a WordPress theme. When I use the plugin Debug Bar for WordPress development it throws a JavaScript error of: Script error

Solution 1:

change your functions.php to include something like the below. The google map api has a dependency to your script.

<?phpfunctiontheme_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');


?>

Solution 2:

ok I think the issue is at

( function( $ ) {
$(functioninitMap() {

this is throwing an error because you can't define a function like that. Replace it as

( function( $ ) {
    functioninitMap(){
    .....
    }
} )( jQuery );

Solution 3:

With Stephen's answer I ended up targeting the wp_footer and included the JavaScript instead of calling it from an external file as that is what is in Google's example.

Here is the code, I hope it can help someone else:

function call_the_js_files() {  
    if (is_page_template('page-foo.php')) :
    ?>
    <scripttype='text/javascript'>functioninitMap() {
        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); 
        }
    </script><?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 );
    endif;
add_action( 'wp_footer', 'call_the_js_files' );

Post a Comment for "Why Am I Getting A Google Map Javascript Error In My Wordpress Theme?"