javascript - 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>
解决方案
看起来脚本在<div id='map' class='container'></div>
创建之前正在运行。您需要确保 Javascript在元素加载后运行。为此,您可以执行以下操作之一:
将脚本移动到 HTML 文档的底部,就在
</html>
标记之前:<html> <!-- ALL OF YOUR CURRENT HTML CODE --> ... <!-- PLACE SCRIPT HERE --> <script> <!-- ALL OF YOU MAP CODE --> </script> </html>
将脚本放在文档加载后调用的函数中:
纯Javascript:
document.addEventListener('DOMContentLoaded', function() { // all of your map code here }, false);
- 或者 -
查询:
$(document).ready(function(){ // all of your map code here });
推荐阅读
- javascript - 显示使用 OpenLayers 创建的最后一个多边形
- visual-studio-code - VS Code 找不到 Arduino IDE 路径
- python-3.x - 用beautifulsoup提取没有标签的文本
- javascript - 来自其他站点时如何自动打开选项卡?
- android - Flutter:打开 Facebook Messenger 时出现 ERR_UNKOWN_URL_SCHEME
- python - 对于每个循环,更新变量
- apache - 如何正确使用 Apache 的 mod_env 模块来修改 PATH?
- c# - HRESULT 异常:尝试读取 Airpod pro 电池时出现 0xD0000033
- python - python中的多个条件if语句语法
- azure - Azure Blob 容器文件下载