2016-02-03 70 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