Google Maps API v3 - how to detect when map change

2020-02-07 01:24发布

Is there a way to detect when the user clicks the default fullscreen mode button?

These are the map options I'm using:

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

3条回答
霸刀☆藐视天下
2楼-- · 2020-02-07 01:51

You can use HTML5 Fullscreen API which has the fullscreenchange event:

"When fullscreen mode is successfully engaged, the document which contains the element receives a fullscreenchange event. When fullscreen mode is exited, the document again receives a fullscreenchange event".

Please note that

"For the moment not all browsers are using the unprefixed version of the API".

So, for instance, in Mozilla Firefox the event handler would look like this

document.onmozfullscreenchange = function(event) { 
    console.log("Full screen change")
}
查看更多
Ridiculous、
3楼-- · 2020-02-07 01:57

This solution it is working for me:

/** 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!');
    }
});
查看更多
▲ chillily
4楼-- · 2020-02-07 01:58

I'm not sure if you want to detect the actual click event or just the state change between full screen and not. I needed to do the latter. The two things you need to know are that a) when the map size changes, the map will fire the bounds_changed event and b) within your event handler for that, you need to compare the map div's size with the size of the entire screen. Do this like so:

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');
    }
}

Note that getDiv() returns your own div that you passed to the Map() constructor. That div doesn't get resized for full screen - its child does. So that part where I'm getting the child of the map's div is correct but a little unwieldy. You could also rewrite that more briefly like this and it will work but this could break in the future if Google changes the map div's class name:

if ( $( '.gm-style' ).height() == window.innerHeight &&
     $( '.gm-style' ).width()  == window.innerWidth ) {
查看更多
登录 后发表回答