2015-10-27 22 views
-1

我正在開發基於Google Maps API的應用程序:基本上我有我的國家的郵政編碼,我需要顯示它們。我可以使用JavaScript jQuery改進數千個元素的渲染嗎?

這裏是一個展示我的當前實現視頻 - 在地圖上>https://vid.me/S6PL

郵政代碼創建感謝google.maps.OverlayView類我擴展和創建一個自定義PostalCodeOverlay(這是由圓圈表示)。它draw方法如下:

PostalCodeOverlay.prototype.draw = function() { 

     var overlayProjection = this.getProjection(); 
     // Handle some positioning stuff here with some properties created before during construction 
     var center = overlayProjection.fromLatLngToDivPixel(new google.maps.LatLng(this.centerLat, this.centerLng)); 
     var div = this.postalCodeOverlayDiv; 
     div.style.position = 'absolute'; 
     div.style.left = (center.x - (width/2)) + 'px'; 
     div.style.top = (center.y - (height/2)) + 'px'; 
     div.style["-moz-border-radius"] = "50%"; 
     div.style["-webkit-border-radius"] = "50%"; 
     div.style["border-radius"] = "50%"; 
     // As I show it the first time with an animation and 
     // the APIs call this method several times (e.g. when 
     // the zoom level of the map changes), I have a custom 
     // boolean property that tells me whether it's the first 
     // time or not 
     if (!this.justCreated) {   
      div.style.width = width + "px"; 
      div.style.height = height + "px"; 
     } 
     else { 
      this.justCreated = false; 
      var $postalCodeOverlayDiv = $(div); // here I get a jQuery reference to the div which represents the overlay (the circle). 
      $postalCodeOverlayDiv.css({ 
       "width": "0", 
       "height": "0", 
       "opacity": "0" 
      }); 
      // Animate it a bit so that it looks nicer when it 
      // is drawn the first time. 
      $postalCodeOverlayDiv.animate({ 
       "opacity": "1", 
       "width": width + "px", 
       "height": height + "px" 
      }, 500); 

     } 
}; 

現在,你可以從視頻中看到,圓圈創建順利當縮放水平較高,導致每視界的郵政編碼密度較低。

但是,當我開始縮小,你可以看到,這些漂亮的效果都將丟失,因爲有每個視範圍更郵政編碼現在(區域變寬)。

我取從通過AJAX數據庫中的郵政編碼(我緩存他們感謝Google Geocoding本地API在我的DB)。當邊界被改變時(我使用map.addListener('bounds_changed', function() {...})),獲取它們的查詢很快並且一旦發出請求就會返回。返回的JSON包含搜索到的特定範圍內的所有郵政編碼,計算爲用戶在地圖中移動(如您從視頻中看到的那樣)。然後我遍歷這個JSON和每個條目(代表郵政編碼),我創建一個帶有相關信息的new PostalCodeOverlay(...params...)

因爲你已經瞭解的問題是渲染:當涉及到渲染數千個元素的JavaScript引擎缺乏了一下,地圖掛。

我可以發佈代碼,但我不認爲這是必要的,我認爲它足以向您展示視頻和覆蓋層我使用(無論如何,如果有什麼東西不清楚,請告訴我,我會更新)。

這是解決這些問題的最佳途徑?如果底層數據集較大時,是否有辦法讓JavaScript/jQuery更平滑地處理動畫?或者,也許有一些我不知道的Google地圖功能,我可以在我創建的疊加層中使用它們?

無論如何,一些建議,將不勝感激。

感謝您的關注。

+0

爲什麼標記爲「太寬」? – tonix

+1

在文檔中看到這篇文章:[太多標記!](https://developers.google.com/maps/articles/toomanymarkers) – geocodezip

回答

2

Google爲Too Many Markers提供此文檔以提供建議。那裏有很多選擇。

如果在視圖中繪製了數百個元素,您還希望擺脫jQuery動畫。 jQuery動畫涉及定時器上數以千計的繪圖循環。乘以數百或數千個元素,而不僅僅是CPU可以有效跟上。你也可以嘗試使用CSS動畫,而不是使用jQuery動畫,這可能會更有效。

因此,也許如果縮放級別超過某個閾值(因此可能導致郵件代碼丟失),則跳過動畫並直接設置CSS屬性。

除此之外,您可以通過刪除邊界半徑或簡化一些其他CSS樣式來查看更有效的繪製郵政編碼的方式(您不顯示涉及顯示該div的所有內容,因此我們無法制作更具體的建議)。同樣,只有在縮小超出某個閾值時才能做到這一點。

而且,對於縮小了很多的情況,您可能希望跳過重疊代碼的渲染,因爲它們都非常小並且非常接近,以至於它們無論如何都不會提供很多價值。這裏面臨的挑戰是如何在保存整體CPU的同時如何做到這一點。您只能在給定的屏幕段中顯示一個郵政編碼,或在縮小超出某個閾值時不顯示郵政編碼。

相關問題