[英]Google MAPS API - Trying to have a map on two separate HTML pages but on one of them an error occurs
“地图:预期为 Element 类型的 mapDiv,但已通过 null。”
- div的高度在css中设置。
Javascript(googleMaps.js):
function initMap() {
try {
const sportHall2 = { lat: 51.18310959584043, lng:
4.38829092697164 };
const map2 = new google.maps.Map(document.getElementById("map-2"),
{
zoom: 13,
center: sportHall2,
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
streetViewControl: true,
});
const map2b = new google.maps.Map(document.getElementById("map-2b"), {
zoom: 13,
center: sportHall2,
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
streetViewControl: true,
});
} catch (error) {
console.log(error);
}
}
HTML 第 1 页:
<script src="/scripts/googleMaps.js"></script>
<div class="grid-card">
<h3>Pius X-instituut</h3>
<h5>Bekijk de sporthal hier.</h5>
<p>Adres: Hof Van Tichelen 28 2020 Antwerpen</p>
<div id="map-2"></div>
</div>
<script src="/scripts/googleMaps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyDsZ0rx4aEk6eegfEHbfAl2Z_IA8iY6ho4&callback=
initMap&libraries=&v=
weekly" async></script>
HTML 第 2 页(发生错误并且 map 不会显示在此页面上):
<script src="/scripts/googleMaps.js"></script>
<div class="grid-card map-2b-container">
<h3>Pius X-instituut</h3>
<h5>Bekijk de sporthal hier.</h5>
<p>Adres: Hof Van Tichelen 28 2020 Antwerpen</p>
<div id="map-2b"></div>
</div>
<script src="/scripts/googleMaps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyDsZ0rx4aEk6eegfEHbfAl2Z_IA8iY6ho4&callback=
initMap&libraries=&v=weekly" async></script>
CSS:
#map-2{
height: 300px;
width: 100%;
}
#map-2b{
height: 300px;
width: 100%;
}
错误:Se {消息:“地图:预期 mapDiv 类型为 Element,但已通过 null。”,名称:“InvalidValueError”,堆栈:“错误↵ at new Se ( https://maps.googleapis.com/m...=6ho4&callback initMap&libraries=&v=weekly:156:128"}
尝试这个:
来源: 地图 API
const mapDiv = document.getElementById("map-2b");
const map2b = new google.maps.Map(mapDiv), {
zoom: 13,
center: sportHall2,
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
streetViewControl: true,
});
您是否尝试过使用 iframe 嵌入谷歌地图? 如果没有,那么这是在 HTML 中使用 map 的最简单方法。
步骤1:go 到https://www.google.com/maps
Step2:输入你要嵌入的位置。
第三步:点击菜单 -> 分享或嵌入 map -> 嵌入 map 选项卡
第四步:复制 iframe 标签并粘贴到 HTML 文件中
function initMap() {
try {
const sportHall2 = { lat: 51.18310959584043, lng:
4.38829092697164 };
if(document.getElementById('map-2')){
const map2 = new google.maps.Map(document.getElementById("map-2"), {
zoom: 13,
center: sportHall2,
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
streetViewControl: true,
});
}
}
上面的代码通过在每个单独的页面“map-2”上设置两个 div Id 并在运行 Map() 构造函数之前检查 div 是否存在来工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.