Search code examples
javascriptwordpressleaflet

Get error when i display a map to wordpress using leaflet tool (Uncaught Error: Map container not found)


I am trying to insert the leaflet javascript to display a map from mapserver, i tried this following code but i got this error :

Uncaught Error: Map container not found.
    at e._initContainer (leaflet.js?ver=1:6)
    at e.initialize (leaflet.js?ver=1:6)
    at new e (leaflet.js?ver=1:6)
    at Object.o.map (leaflet.js?ver=1:6)
    at script1.js?ver=1:3

I did search some tutorials but i didn't found something for wordpress, so i don't know what i do to solve this problem. This is the code i use to insert the js and css leaflet files in functions.php:

function add_js_scripts() {
wp_enqueue_script('script-leaflet-js', 'http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js',array() ,true);
wp_enqueue_style( 'script-leaflet-css','http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',array(),true);
wp_enqueue_script( 'script-leaflet-map', get_template_directory_uri().'/script1.js', array(), true );}
add_action('wp_enqueue_scripts', 'add_js_scripts');

script1.js :

        var map = L.map('mapid').setView([29, -6.8644], 5); 
L.tileLayer.wms("http://localhost:81/cgi-bin/mapserv.exe?map=/wamp64/www/wordpress/map1.map", {
            layers: 'map1',
            format: 'image/png',
            transparent: true,
            attribution: "Dan's Amazing Roads",
            maxZoom: 18,
            minZoom: 12,
        }).addTo(mapid);

and this is the code i insert in the page :

<div id="mapid" style="width: 600px; height: 500px;"></div>

Thank you!


Solution

  • Try to load when DOM is ready

    Since the $in_footer argument of wp_enqueue_script() is true. It gets enqueued in the wp_footer() action, usually right before the ending of the body tag, and will be read in last then called when dom beeing ready.

    Doc: wp_enqueue_script

    (function()
    {
       var map = L.map('mapid').setView([29, -6.8644], 5); 
       L.tileLayer.wms("htt....
    })();
    

    Another method, all browsers (except old IE...)

    document.addEventListener('DOMContentLoaded', function()
    {
       var map = L.map('mapid').setView([29, -6.8644], 5); 
       L.tileLayer.wms("htt....
    
    }, false);