您可以使用jQuery可见的检查,如果您的视图中的地图元素是用户可见。然后如果视图是可见的,则开始动画。
jquery visible tutorial
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毫秒。
来源
2016-02-03 14:02:29
Tim
嗨,对不起,我没有回复,你的答案似乎对我很好,但我有一些意想不到的事情要解决。我会尽快回来看看它是否有效。谢谢你的可爱答案 – Goran
听起来不错。我希望这个答案适合你。在你的研究中,如果你发现解决这个问题的其他创造性的方式,请分享它们,这样我们都可以学习。谢谢! – Tim