我使用以下代码在我的网页上创建嵌入式Google地图:
function init() {
var mapOptions = { // Set up the map options
center: new google.maps.LatLng(40.782710,-73.965310),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13
};
var venueMap; // Map() draws a map
venueMap = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function loadScript() {
var script = document.createElement('script'); // Create <script> element
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&callback=init';
document.body.appendChild(script); // Add element to page
}
window.onload = loadScript; // on load call loadScript()
效果很好,除了它会产生相同的错误described here.一个简单的建议解决方案是添加以下行:
google.maps.event.trigger(map, 'resize');
一位用户建议将其放入控制台,当我这样做时,效果很好。即使我手动重新调整窗口的大小,它也会完全重置。我试图在将元素添加到页面的行之后插入代码,我从Firefox中收到错误ReferenceError: google is not defined
并指向我插入的行。
我应该把这段代码放在哪里?
编辑:这是重新创建问题的代码:
$(function() {
$("article").hide().delay(1000).fadeIn(1000);
loadScript();
google.maps.event.listener(map, 'resize');
});
function init() {
var mapOptions = {
center: new google.maps.LatLng(40.782710, -73.965310),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13
};
var venueMap;
venueMap = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.trigger(map, 'resize');
//google.maps.event.trigger(map, 'resize');
}
function loadScript() {
var script = document.createElement('script');
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&callback=init';
document.body.appendChild(script);
}
&#13;
#map {
width: 400px;
height: 400px;
margin-left: auto;
margin-right: auto;
}
article {
width: 80%;
padding-top: 30px;
padding-bottom: 30px;
margin-left: auto;
margin-right: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<article>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div id="map"></div>
<script src="js/google-map.js"></script>
</article>
&#13;
答案 0 :(得分:0)
fadeIn完成后触发resize事件(google.maps.event.trigger(map, 'resize');
),id =“map”的div有一个大小。