Rails 5:谷歌地图显示为灰色

时间:2017-12-27 09:21:42

标签: javascript ruby-on-rails google-maps

我在标签页面中实施了谷歌地图,用户可以点击地图并获取地址。我唯一的问题是,当页面加载时,地图显示为灰色,只有在我调整浏览器窗口大小后,地图才能正确显示。任何想法为什么会发生这种情况?

这是我的设置:

#map_canvas
  height: 300px
  width: 100%
  margin: 0px
  padding: 0px


<div id="map_canvas"></div>
<script>
var map;
var geocoder;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP };

function initialize() {
    var myOptions = {
        center: new google.maps.LatLng(38.89103282648849, -97.646484375),
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
    });

    var marker;
    function placeMarker(location) {
        if(marker){ //on vérifie si le marqueur existe
            marker.setPosition(location); //on change sa position
        }else{
            marker = new google.maps.Marker({ //on créé le marqueur
                position: location,
                map: map
            });
        }
        document.getElementById('lat').value=location.lat();
        document.getElementById('lng').value=location.lng();
        getAddress(location);
    }

    function getAddress(latLng) {
        geocoder.geocode( {'latLng': latLng},
            function(results, status) {
                if(status = google.maps.GeocoderStatus.OK) {
                    if(results[0]) {
                        document.getElementById("address").value = results[0].formatted_address;
                    }
                    else {
                        document.getElementById("address").value = "No results";
                    }
                }
                else {
                    document.getElementById("address").value = status;
                }
            });
    }
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

enter image description here

更新1

地图位于标签内,这是我试图适应resize的地方:

<script>
$('#tabs').on('click','.tablink,#prodTabs a',function (e) {
    e.preventDefault();
    var url = $(this).attr("data-url");

    if (typeof url !== "undefined") {
        var pane = $(this), href = this.hash;

        // ajax load from data-url
        $(href).load(url,function(result){
            pane.tab('show');
            google.maps.event.trigger(map, 'resize');
        });
    } else {
        $(this).tab('show');
    }
});
</script>

1 个答案:

答案 0 :(得分:0)

只需在地图初始化结束时触发调整大小,它就可以正常工作。

google.maps.event.trigger(map, 'resize');