Cluster稍微複雜一點,但是依照1-4步驟應該可以順利的完成並顯示Cluster在地圖上面。
要注意的是層級結構,也就是誰包含誰,我記得我一開始學習的時候都搞不清楚,比起上一篇Heatmap雖然Cluster比較複雜,但只要注意結構我想,應該可以順利地呈現吧!!
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "https://wmts.nlsc.gov.tw/wmts/EMAP5/default/EPSG:3857/{z}/{y}/{x}.png",
crossOrigin: "anonymous",
minZoom: 6,
maxZoom: 20,
}),
}),
],
target: "map",
view: new ol.View({
projection: "EPSG:3857",
center: ol.proj.fromLonLat([120.846642, 23.488793]),
zoom: 7.5,
maxZoom: 20,
minZoom: 5,
enableRotation: false,
}),
controls: [],
});
// 1.建立source,放features
const vectorSource = new ol.source.Vector({
url: "test.geojson",
format: new ol.format.GeoJSON(),
});
// 2.建立cluster source,將1.vectorSource放到clusterSource中並設定距離參數
const clusterSource = new ol.source.Cluster({
distance: 10,
minDistance: 10,
source: vectorSource,
});
// 3.加入cluster source到layer中,並設定樣式
const styleCache = {};// dict的Cache寫法,直接把物件存起來,這樣後續渲染使用的時候就不用重新產物件
const vectorLayer = new ol.layer.Vector({
source: clusterSource,
style: function (feature) {
// 取得cluster的count數量
const size = feature.get("features").length;
let style = styleCache[size];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 15,
stroke: new ol.style.Stroke({
color: "#000",
}),
fill: new ol.style.Fill({
color: "#ff7f00",
}),
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: "#fff",
}),
scale: 2.5
}),
});
styleCache[size] = style;
}
return style;
},
});
// 4.記得加入到地圖中
map.addLayer(vectorLayer);
https://github.com/weijung0923/learning-openlayers-micromastery/tree/day15