Javascript 谷歌地图API-试图在两个单独的HTML页面上创建地图,但其中一个页面出现错误
“映射:应为元素类型的mapDiv,但传递的是null。” -div的高度在css中设置 Javascript(googleMaps.js): HTML第1页:Javascript 谷歌地图API-试图在两个单独的HTML页面上创建地图,但其中一个页面出现错误,javascript,html,css,google-maps-api-3,Javascript,Html,Css,Google Maps Api 3,“映射:应为元素类型的mapDiv,但传递的是null。” -div的高度在css中设置 Javascript(googleMaps.js): HTML第1页: <script src="/scripts/googleMaps.js"></script> <div class="grid-card"> <h3>Pius X-instituut</h3
<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>
错误:
Se{message:“Map:应为元素类型的mapDiv,但已传递
null“,名称:“InvalidValueError”,堆栈:“Error”↵ 在纽约东南部(
6ho4&callback=initMap&libraries=&v=weekly:156:128“}试试这个:
资料来源:
您是否尝试过使用iframe嵌入google地图?如果没有,那么这是在HTML中嵌入地图的最简单方法 步骤1:转到
步骤2:输入要嵌入的位置。
步骤3:单击菜单->共享或嵌入地图->嵌入地图选项卡
步骤4:复制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是否存在来工作构造函数。您使用的是typescript吗?请提供一个示例来说明您的问题。我使用的是JavaScript。@geocodezip感谢您的建议,我相信它现在应该是reprex/mcve/mwe。我希望您在两个页面上都会出现该错误(每个页面尝试访问两个div,但每个页面只有一个div…)。可能只访问div(如果存在);或者在两个页面上使用相同的名称作为map div。这是有道理的,我尝试使用相同的名称作为map div,但没有任何区别。在运行该函数之前,我还尝试检查div是否存在,但该函数也不起作用。之后,我尝试在两个HTML页面和HTML第1页sti上都使用map div元素我只显示了map-2,与HTML第2页一样,没有加载任何地图。错误保持不变。感谢您的建议,但我仍然收到相同的错误。感谢您的建议,但是很难获得我希望iframe的响应能力。
<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>
#map-2{
height: 300px;
width: 100%;
}
#map-2b{
height: 300px;
width: 100%;
}
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,
});
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,
});
}
}