当地图滚动到视图中时,如何使谷歌地图标记动画?

3

我在页面底部使用了谷歌地图并添加了动画标记。标记有下落动画,但我希望当地图滚动到视图中时动画才开始。否则,当用户向下滚动查看地图时,动画已经结束了。我正在使用谷歌地图API。

我的代码:

var marker;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {lat: 59.325, lng: 18.070}
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: {lat: 59.327, lng: 18.067}
  });
  marker.addListener('click', toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
1个回答

2
您可以使用 jQuery Visible 来检查用户是否能够看到视图中的地图元素。如果视图可见,则开始动画。 jQuery Visible 教程 jQuery Visible GitHub
//set an interval that keeps checking if the user can see the map
//the interval will keep calling your initMap()
var myVar = setInterval(function () { initMap() }, 10);

function initMap() {
// check if the user can see the map using $('#map').visible()
    if ($('#map').visible()) {
        //if the user can see the map stop checking
        clearInterval(myVar);

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 13,
            center: { lat: 59.325, lng: 18.070 }
        });

        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: { lat: 59.327, lng: 18.067 }
        });
        marker.addListener('click', toggleBounce);
    }
}



function toggleBounce() {
    if (marker.getAnimation() !== null) {
        marker.setAnimation(null);
    } else {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}

如果您想的话,可以编辑此代码,先加载地图,然后在用户能够看到地图后再添加标记。
//set an interval that keeps checking if the user can see the map
//the interval will keep calling your initMap()
var myVar = setInterval(function () { addMarker() }, 100);

function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: { lat: 59.325, lng: 18.070 }
    });

    function addMarker() {
        // check if the user can see the map using $('#map').visible()
        if ($('#map').visible()) {
            //if the user can see the map stop checking
            clearInterval(myVar);

            marker = new google.maps.Marker({
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: { lat: 59.327, lng: 18.067 }
            });
            marker.addListener('click', toggleBounce);
        }
    }
}

希望这能帮到你!
快速提醒,如果你想要的话可以更改间隔时间... 我设定的是每10毫秒检查一次。

嗨,很抱歉我还没有回复你,你的答案看起来不错,但我有一些意外的事情要解决。我会尽快回来看看它是否有效。谢谢你可爱的回答。 - Goran
听起来不错,Goran。我希望这个答案对你有用。如果在你的研究中发现其他创造性的解决问题的方法,请分享给我们,这样我们就可以一起学习。谢谢! - Tim

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