openlayers入門開發系列之熱力圖篇
阿新 • • 發佈:2018-11-19
本篇的重點內容是利用openlayers實現熱力圖功能,效果圖如下:
實現思路
- 熱力圖介面設計
//熱力圖 "<div style='height:25px;background:#30A4D5;margin-top:2px;width: 98%;margin-left: 3px;'>" + "<span style='margin-left:5px;font-size: 13px;color:white;'>熱力圖</span>" + "</div>" + '<div id="heatmapFeatureLayer" style="padding:5px;">' + '<div style="float:left;">' + '<input type="checkbox" name="heatmapFeatureLayer" id="heatmap1" style="width: 15px;height: 15px;vertical-align: middle;margin: auto;"/>' + '<label style="font-weight: normal;vertical-align: middle;margin: auto;">熱力圖</label>' + '</div>' + '</div>' +
- 熱力圖點選事件
//載入熱力圖 $("#heatmapFeatureLayer input").bind("click", function () { if (this.checked) { if(!bxmap.olHeatMap.isLoad){ bxmap.olHeatMap.Init(bmap); } else{ bxmap.olHeatMap.showHeatMapLayer(); }//圖例面板顯示 $("#map_tl").css("display","block"); $("#map_tl>img").attr('src', getRootPath() +"js/main/olHeatMap/lend_dz.png"); $("#map_tl>img").css("width","165px"); $("#map_tl>img").css("height","165px"); }else { bxmap.olHeatMap.hideHeatMapLayer(); //圖例面板隱藏 $("#map_tl").hide(); } })
- 熱力圖初始化以及核心程式碼實現
Init:function(bmap){ //載入熱力圖 this.map = bmap.getMap(); this.isLoad = true; this.initHeatMapLayer(dz); }, /** * 初始化載入-熱力圖 */ initHeatMapLayer:function(data){ var num = data.features.length; if (num > 0) { var features = new Array(num); for (var i = 0; i < num; i++) { var geo = data.features[i].geometry; var coordinate = [geo.x, geo.y]; features[i] = new ol.Feature({ geometry: new ol.geom.Point(coordinate), weight: data.features[i].attributes[field_dz] }); } this.loadHeatLayer(features); } }, loadHeatLayer:function(features){ var self = bxmap.olHeatMap; self.layer = self.createHeatMap({ features: features, radius: self.radius, gradient: self.gradient1 });//建立熱力圖層 self.map.addLayer(self.layer); self.map.getView().on('change:resolution', self.handleHeatMap); //縮放至範圍 self.map.getView().fit(self.layer.getSource().getExtent(), self.map.getSize()); }, /** * 建立熱力圖層 * @method createHeatmap * @param features 渲染熱力圖的要素集 * @return Heatmap 返回熱力圖層 */ createHeatMap:function(options){ var vector = new ol.layer.Heatmap({ source: new ol.source.Vector({//熱力圖資料來源 features: options.features }), id: 'heat', extent: options.extent, weight: weightFunction,//設定權重,值在0-1之間 gradient: options.gradient, blur: 15,//預設15 radius: options.radius || 8//預設8 }); /* *設定權重 */ function weightFunction(feature) { var weight = feature.get('weight'); weight = parseFloat(weight); //weight = parseFloat(weight) / 10; return weight; } return vector; }, ……