首页 > 解决方案 > mapbox not initializing due to template

问题描述

I am trying to initialise MapBox but console throw an error "Uncaught Error: Container 'map' not found."

I am working with templates which I believed is the issue whereby Mapbox is unable to query the element that is being specified in my html due to some reason. I am fairly new to using template and my context is it fragments the HTML page. Hoping that someone that is experience in it can assist me on this. Thank you!

        mapboxgl.accessToken = 'MYAPIKEY';
        var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        interactive: true,
        dragRotate: true,
        doubleClick: true
        });


        // THIS TRACK'S USER LOCATION IN REAL-TIME USING USER'G GroupSchool
        map.addControl(new mapboxgl.GeolocateControl({
        positionOptions: {
        enableHighAccuracy: true
        },
        trackUserLocation: true
        }));
        //IF I CHANGE THIS URL TO PHP THAT CONTAINS THE GEOJSON FORMAT
        var url = http://xxxx.geojson;
      


        map.on('load', function () {
            window.setInterval(function() {
                map.getSource('drone').setData(url);
            }, 2000);

            map.addSource('drone',
            {
              type: 'geojson',
              data: url
            });

            map.addLayer({
                "id": "drone",
                "type": "symbol",
                "source": "drone",
                "layout": {
                    "icon-image": "rocket-15"
                }
            });
        });
          <template id="home.html">
            <ons-page>
                <!-- Toolbar-->
                <ons-toolbar>
                    <div class="left">
                        <ons-toolbar-button onclick="fn.open()">
                            <ons-icon icon="md-menu"></ons-icon>
                        </ons-toolbar-button>
                    </div>
                    <div class="center">
                    </div>
                </ons-toolbar>

                <div id='map' class='container'></div>



            </ons-page>


        </template>

标签: javascriptjqueryhtmltemplatesmapbox

解决方案


看起来脚本在<div id='map' class='container'></div>创建之前正在运行。您需要确保 Javascript在元素加载后运行。为此,您可以执行以下操作之一:

  1. 将脚本移动到 HTML 文档的底部,就在</html>标记之前:

    <html>
        <!-- ALL OF YOUR CURRENT HTML CODE -->
        ...
        <!-- PLACE SCRIPT HERE -->
        <script>
            <!-- ALL OF YOU MAP CODE -->
        </script>
    </html>
    
  2. 将脚本放在文档加载后调用的函数中:

    纯Javascript:

    document.addEventListener('DOMContentLoaded', function() {
       // all of your map code here
    }, false);
    

    - 或者 -

    查询:

    $(document).ready(function(){
        // all of your map code here
    });
    

推荐阅读