第一次使用 Google map API, map 未显示。我已经阅读了很多有关导致问题的高度和宽度声明的内容,我尝试将所有相关样式从 % 切换到 px ,但没有任何变化。
我正在使用 Rails 4.2.1
map Javascript 最初是 Bootstrap 模板的一部分
这是我的 JavaScript:
function init() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// Disables the default Google Maps UI components
disableDefaultUI: true,
scrollwheel: false,
draggable: false,
// How you would like to style the map.
styles: [{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"lightness": 100
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"visibility": "on"
},
{
"color": "#C6E2FF"
}
]
},
{
"featureType": "poi",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#C5E3BF"
}
]
},
{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#D1D1B8"
}]
}]
};
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
// Get the HTML DOM element that will contain your map
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
在index.html.erb中,
应该显示 map 的 div:
<div id="map"></div>
链接到 API 的脚本标记:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=my_api_key_here">
</script>
我的.less文件中的关联样式:
#map {
width: 100%;
height: 200px;
margin-top: 100px;
}
@media(min-width:767px) {
#map {
height: 400px;
margin-top: 250px;
}
}
我的 .css 文件中的关联样式:
#map {
width: 100%;
height: 200px;
margin-top: 100px;
}
@media(min-width:767px) {
#map {
height: 400px;
margin-top: 250px;
}
}
如有任何建议,我们将不胜感激,谢谢!
最佳答案
我找到了修复此解决方案的答案。
我将 callback=initialize
选项添加到 html 内的脚本标记中:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
这篇文章有帮助:
关于javascript - Google map API -- map 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363394/