前面兩篇其實(shí)都是為了寫一下leaflet-heatmap.js
最后搜了一下github https://github.com/Leaflet/Leaflet.heat
加載了leaflet.js和heatmap.js,就可以用leaflet-heatmap.js來繪制熱力地圖了。
- 首先,這是要展示的數(shù)據(jù),有max代表所有數(shù)據(jù)的最大值,lat和Ing代表經(jīng)緯度的值,count是要展示的數(shù)據(jù),后面配置會(huì)有講到,所以max應(yīng)該是count中的最大值。
// don't forget to include leaflet-heatmap.js
var testData = {
max: 8,
data: [{lat: 24.6408, lng:46.7728, count: 3},{lat: 50.75, lng:-1.55, count: 1}, ...]
};
- 很熟悉,就是我們講leaflet的基礎(chǔ)層的初始化。
var baseLayer = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: '...',
maxZoom: 18
}
);
- cfg中所有heatmapjs的參數(shù)都可以用。另外加了額外的參數(shù),都有說明
var cfg = {
// radius should be small ONLY if scaleRadius is true (or small radius is intended)
// if scaleRadius is false it will be the constant radius used in pixels
"radius": 2,
"maxOpacity": .8,
// scales the radius based on map zoom
"scaleRadius": true,
// if set to false the heatmap uses the global maximum for colorization
// if activated: uses the data maximum within the current map boundaries
// (there will always be a red spot with useLocalExtremas true)
"useLocalExtrema": true,
// which field name in your data represents the latitude - default "lat"
latField: 'lat',
// which field name in your data represents the longitude - default "lng"
lngField: 'lng',
// which field name in your data represents the data value - default "value"
valueField: 'count'
};
- 初始化 heatmapLayer ,也就是將熱力圖看作一層,還記得說地圖的時(shí)候,是說它們是一層一層堆積的么?
var heatmapLayer = new HeatmapOverlay(cfg);
var map = new L.Map('map-canvas', {
center: new L.LatLng(25.6586, -80.3568),
zoom: 4,
layers: [baseLayer, heatmapLayer]
});
heatmapLayer.setData(testData);
setDate每次改變值,熱力圖也是會(huì)更新的。
原生態(tài)的配色被吐槽太丑,現(xiàn)在的大家覺得有好一點(diǎn)么?

作者給的圖

咱的配色
看了一下代碼,也就200來行,主要是重寫了setData,addData的方法,另外跟地圖銜接的有addTo和onRemove ,使之適應(yīng)熱力圖。