我之前曾使用过地图,而且我从来没有遇到地图根本无法渲染的问题。
这里有我的代码实现,包括对places API库的请求
http://jsfiddle.net/Newtt/Ljn1n6nh/
这是我的代码示例:
JS:
function initialize() {
var elem = document.getElementById('map-dire');
var map = new google.maps.Map(elem, {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
}
google.maps.event.addDomListener(window, 'load', initialize());
这是最简单的地图形式,但它总是渲染一个灰色/米色的盒子,如果我点击任何地方就会显示Uncaught TypeError: Cannot read property 'x' of undefined
。我理解这个错误显示何时未加载地图的DOM元素。但是,只有在加载window
元素时,地图才会触发吗?
答案 0 :(得分:2)
**center and zoom are Required.**
尝试动态发送纬度和经度,我给出了参考的硬编码值
function initialize() {
var elem = document.getElementById('map-dire');
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(elem, mapOptions);
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
}
google.maps.event.addDomListener(window, 'load', initialize());
如果你给出像
这样的缩放属性,你编辑的jsfiddle也可以工作function initialize() {
var elem = document.getElementById('map-dire');
var map = new google.maps.Map(elem, {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: { lat: -34.397, lng: 150.644},zoom: 8
});
}
google.maps.event.addDomListener(window, 'load', initialize());
答案 1 :(得分:0)
有两个必需(必填)MapOptions
如果你不提供它们,你必须调用map.setCenter()和map.setZoom(),map.fitBounds()[计算两者],使用KmlLayer并将preserveViewport设置为false [也计算两者]或其他一些操作导致它们都被设置(因此地图将被初始化)。
调用map.setCenter()和map.setZoom()的代码段:
function initialize() {
var elem = document.getElementById('map-dire');
var map = new google.maps.Map(elem, {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
map.setCenter({lat: 0,lng: 0});
map.setZoom(2);
}
google.maps.event.addDomListener(window, 'load', initialize());
#map-dire {
height: 450px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div class="modal-body">
<div class="row">
<div class="col-lg-4">
<div class="search-box">
<input id="search-places" class="jr-input" focusdir search-box placeholder="Enter location">
<div id="directions-panel" class="directions-panel">
</div>
</div>
</div>
<div class="col-lg-8">
<div id="map-dire">
</div>
</div>
</div>
</div>
设置center
和zoom
的代码段:
function initialize() {
var elem = document.getElementById('map-dire');
var map = new google.maps.Map(elem, {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: {lat: 0,lng: 0},
zoom: 2
});
}
google.maps.event.addDomListener(window, 'load', initialize());
#map-dire {
height: 450px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div class="modal-body">
<div class="row">
<div class="col-lg-4">
<div class="search-box">
<input id="search-places" class="jr-input" focusdir search-box placeholder="Enter location">
<div id="directions-panel" class="directions-panel">
</div>
</div>
</div>
<div class="col-lg-8">
<div id="map-dire">
</div>
</div>
</div>
</div>