2016-02-03 71 views
2

因此我在带有动画标记的页面底部显示谷歌地图。标记有放下动画,但我希望在地图滚动到视图时开始动画 - 当用户最终向下滚动以查看地图时,没有该动画结束。 我正在使用谷歌地图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); 
    } 
} 

回答

2

您可以使用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毫秒。

+0

嗨,对不起,我没有回复,你的答案似乎对我很好,但我有一些意想不到的事情要解决。我会尽快回来看看它是否有效。谢谢你的可爱答案 – Goran

+0

听起来不错。我希望这个答案适合你。在你的研究中,如果你发现解决这个问题的其他创造性的方式,请分享它们,这样我们都可以学习。谢谢! – Tim