所以我在带有动画标记的页面底部有谷歌地图。标记有动画,但我希望动画在地图滚动到视图时启动 - 当用户最终向下滚动以查看地图时,动画不会结束。 我正在使用谷歌地图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);
}
}
答案 0 :(得分:2)
您可以使用jquery visible来检查用户是否可以看到视图上的地图元素。然后,如果视图可见,则启动动画。
//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毫秒检查一次。