如何在调整浏览器大小时将谷歌地图标记设置为中心



我希望你能帮我在调整浏览器大小时将谷歌地图标记固定在中心。我需要响应式地图,所以...

谢谢你的时间,希望你能帮助我。

这是代码:

-.HTML:

<!-- Map container -->
<div id="map_container">
<!-- Map -->
<iframe id="map" src="https://mapsengine.google.com/map/embed?mid=zshaN7gd-oek.kGuRBCX_l_sU"></iframe>
<!-- / Map -->
</div>
<!-- / Map container -->

-.CSS:

#map_container {
margin: 200px auto;
padding: 0;
width: 90%;
height: 250px; }
#map_container #map {
position: relative;
margin-top: 0;
margin-left: 0;
width: 100%;
height: 100%;
border: none; }

您需要侦听窗口调整大小事件,然后设置中心:

 google.maps.event.addDomListener(window, 'resize', function() {
       map.setCenter(new google.maps.LatLng(-25.363882, 131.044922));
 });

上述解决方案适用于Google Maps JavaScript API v3,但是如果您只使用iframe方法,那么就响应式设计而言,事情对您来说并不好,据我所知。

好的,这是工作 JsFiddle 和我从 :https://developers.google.com/maps/documentation/javascript/examples/event-simple 稍微修改的示例:

<!DOCTYPE html>
<html>
<head>
    <title>Resize event</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
        function initialize() {
            var mapOptions = {
                zoom: 12,
                center: new google.maps.LatLng(-25.363882, 131.044922)
            };
            google.maps.event.addDomListener(window, 'resize', function () {
                map.setCenter(new google.maps.LatLng(-25.363882, 131.044922));
            });
            var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);
            var marker = new google.maps.Marker({
                position: map.getCenter(),
                map: map
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <div id="map-canvas"></div>
</body>
</html>

每当窗口大小更改时,以下代码都会重新加载您的地图,因此您的地图标记将自动位于中心,因为每次我们获得一张新地图时,该地图都会将标记设置在中心。希望这会有所帮助!

$(window).resize(function(){
   var ref=$('iframe:first').attr('src');
   $('iframe:first').attr('src',ref);
});

最新更新