Google Maps API v3 - 如何检测地图何时变为全屏模式?

9

有没有办法检测用户是否点击了默认的全屏模式按钮?

这是我正在使用的地图选项:

var mapOptions = {
            center: {
                lat: 40.907192,
                lng: 20.036871
            },
            zoom: 2,
            fullscreenControl: true
        };

我曾经遇到过同样的问题。请查看我的解决方案 -> https://stackoverflow.com/questions/47699755/toogle-fullscreen-view-event-for-google-maps/47700054#47700054 - megapixel23
4个回答

13

我不确定您是想检测实际的点击事件还是全屏和非全屏之间的状态更改。我需要做后者。你需要知道的两件事是:a)当地图大小改变时,地图会触发bounds_changed事件,b)在该事件的处理程序中,您需要将地图div的大小与整个屏幕的大小进行比较。请按以下方式执行:

google.maps.event.addListener( map, 'bounds_changed', onBoundsChanged );

function onBoundsChanged() {
    if ( $(map.getDiv()).children().eq(0).height() == window.innerHeight &&
         $(map.getDiv()).children().eq(0).width()  == window.innerWidth ) {
        console.log( 'FULL SCREEN' );
    }
    else {
        console.log ('NOT FULL SCREEN');
    }
}

请注意,getDiv() 返回您传递给Map()构造函数的自己的div。该div不会被调整为全屏 - 它的子元素会被调整。所以,我获取地图div的子元素的那部分是正确的,但有点笨重。您也可以像这样更简洁地重写它,它将起作用,但如果Google更改了地图div的类名,这可能会导致故障:

if ( $( '.gm-style' ).height() == window.innerHeight &&
     $( '.gm-style' ).width()  == window.innerWidth ) {

3
当地图被平移/缩放而不切换到全屏时,也会触发“bounds_changed”事件。 - Philipp
bounds_changed事件还会在您的代码中某处使用fitBounds()方法时触发。为此,我不得不设置一个标志并检查事件是否是由于fitBounds()方法触发的。 - Jamshaid K.

6
由于我没有使用jQuery,所以需要对DaveBurns的回答进行一些修改。此外,我需要使用clientHeight和clientWidth。
window.google.maps.event.addListener(
  map,
  'bounds_changed',
  onBoundsChanged,
);

function onBoundsChanged() {
  if (
    map.getDiv().firstChild.clientHeight === window.innerHeight &&
    map.getDiv().firstChild.clientWidth === window.innerWidth
  ) {
    console.log('FULL SCREEN');
  } else {
    console.log('NOT FULL SCREEN');
  }
}

5
这个解决方案对我而言是有效的:
/** Full Screen event */

$(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', function() {
    var isFullScreen = document.fullScreen ||
        document.mozFullScreen ||
        document.webkitIsFullScreen;
    if (isFullScreen) {
        console.log('fullScreen!');
    } else {
        console.log('NO fullScreen!');
    }
});

对于IE11,还需添加“MSFullscreenChange”。 - JohnnyFun
1
我认为,这将在浏览器全屏时触发。这不是我想要的。我想要一个只有在地图全屏时才会触发的事件。而那个事件是 bounds_changed。请参考 @DaveBurns 的答案。 - Jamshaid K.

4
你可以使用 HTML5全屏API,其中包含 fullscreenchange 事件:

“当成功进入全屏模式时,包含该元素的文档会接收到fullscreenchange事件。当退出全屏模式时,文档再次接收到fullscreenchange事件。”

请注意:

“目前并非所有浏览器都使用未加前缀的API版本。”

例如,在Mozilla Firefox中,事件处理程序将如下所示:
document.onmozfullscreenchange = function(event) { 
    console.log("Full screen change")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接