2016-04-08 86 views
1

我試圖在側面板中的圖像和地圖上的多邊形之間進行交互,所以當側面板通過mousescroll移動時,具有相同名稱的相應多邊形被帶入焦點。Mapbox側面板和多邊形交互

我的current attempt根據需要沒有響應mousescrolls。除了我採取的方法之外,還有另一種方法嗎?

$('.sidebar').bind('mousewheel', function(e){ 
    $("#help").html(' '); 
    var winTop = $(this).scrollTop(); 
    var $imgs = $('.sidebar').find('img'); 
    var $midElement; 
    var distance = null; 
    var currDistance = 0; 
    var minHeight = $(window).scrollTop(); 
    var maxHeight = $(window).height(); 

    var img_h=$('.sidebar').find('img'); 
    var img_h1=img_h.height()/2; 

    var middleHeightA = (maxHeight + minHeight)/2; 
    var middleHeight = middleHeightA - img_h1; 
    $.each($imgs, function() { 

    currDistance = Math.abs(middleHeight - $(this).position().top); 
if (distance == null || currDistance < distance) { 
    /*$midElement = $(element);*/ 
    distance = currDistance; 
     for (j=0;j<polygons1.length;j++) { 
      polygons1[j].setStyle({color: '#fff',fillColor:'#000', weight:'1px'}); 
     } 

    var scrid=$(this).attr('id'); 
     for (j=0;j<help.length;j++) { 
      id=help[j]; 
      if(id==scrid) 
      {    
       polygons1[j].openPopup(polygons1[j].getBounds().getCenter());  
       map.setView(polygons1[j].getBounds().getCenter(),10); 
       polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'}); 
       $('.thumbnail').removeClass('active'); 
       $('.'+scrid).addClass('active');     
      } 
     } 
} 



    var scrid=$(this).attr('id'); 
     for (j=0;j<help.length;j++) { 
      id=help[j]; 
      if(id==scrid) 
      {    
       polygons1[j].openPopup(polygons1[j].getBounds().getCenter());  
       map.setView(polygons1[j].getBounds().getCenter(),10); 
       polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'}); 
      } 
     }  
}*/ 
+0

在Chrome 49.0.2623.110中,它似乎可以正常工作(也就是說,各種功能會在滾動鼠標滾輪時滾動顯示)。它有點跳動,因爲它每次鼠標輪移動時重新對焦,但它確實響應。 – nathansnider

+0

謝謝。我不知道我錯過了什麼,所以行爲更快,更流暢。 – user259124

+0

看起來好像太頻繁地調用'setView'和'openPopup'會產生跳動。你真的用高亮例程兩次運行for循環,還是複製粘貼錯誤? – nathansnider

回答

2

我建議您使用debounce函數。去抖功能限制了函數可以觸發的速率。這個想法是讓多邊形的焦點不是每次觸發鼠標滾輪事件,而是用一種冷卻時間來關注它們。

去抖功能已在許多庫中實現,例如在lodash中。所有你需要做的就是把你的mousewheel回調包在裏面。喜歡的東西:

$('.sidebar').bind('mousewheel', _.debounce(function(e){ 
    $("#help").html(' '); 
    ... 
), 100}); 

注重options PARAM,在lodash實施,很可能你想使用其中的一種,例如maxWait