javascript - Google map API -- map 不显示

标签 javascript css ruby-on-rails google-maps-api-3 less

第一次使用 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>

这篇文章有帮助:

Async Google Maps API v3 undefined is not a function

关于javascript - Google map API -- map 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363394/

相关文章:

javascript - IE 在 requestAnimationFrame 之前执行渲染

css - flex-box 如何在多个 flex-rows 的右侧有一个静态固定列?

css - Sveltekit:使用 $page.path 设置事件链接的样式

mysql2 gem 与 mysql 5.6.19 不兼容

javascript - 适用于小型设备的 Jquery 到 javascript,需要少量代码

javascript - 如何自定义嵌套组件?

javascript - 解码 JSONObject 内的 JSON 对象和 JSON 数组

html - 为什么我不能在我的元素中禁用响应式 Bootstrap

ruby-on-rails - Rails 获取上一个和下一个事件记录对象的最佳方法

ruby-on-rails - 使用 RGeo gem 将多边形转换为多多边形