Clusters defer
by Vladimir Vershinin
HTML
<script src="https://unpkg.com/[email protected]/lodash.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v5.3.0/build/ol.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/lib/style.css">
<div id="app">
<vl-map ref="map" data-projection="EPSG:4326">
<vl-view ref="mapView" :zoom.sync="zoom" :center.sync="center"></vl-view>
<vl-layer-tile>
<vl-source-osm />
</vl-layer-tile>
<vl-layer-vector id="features" render-mode="image">
<vl-source-cluster :distance="50">
<vl-source-vector ref="featuresSource" @mounted="getFeatures"></vl-source-vector>
</vl-source-cluster>
<vl-style-func :factory="makeClusterStyleFunc"></vl-style-func>
</vl-layer-vector>
</vl-map>
</div>
CSS
html, body, #app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
new Vue({
el: '#app',
data () {
return {
zoom: 2,
center: [0, 0],
places: _.range(0, 1000).map(i => {
let geom = [
_.random(-50, 50),
_.random(-50, 50),
]
return {
id: 'random-' + i,
geom,
}
}),
}
},
methods: {
getFeatures() {
const sourceVm = this.$refs.featuresSource
sourceVm.$source.clear()
console.log(sourceVm, sourceVm.id, Object.prototype.hasOwnProperty(sourceVm, 'id'), 'id' in sourceVm)
const features = this.places.map(place => {
const geometry = new ol.geom.Point(place.geom)
geometry.transform('EPSG:4326', 'EPSG:3857')
let feature = new ol.Feature({ geometry })
feature.setProperties(place)
feature.setId(place.id)
return feature
})
sourceVm.$source.addFeatures(features)
},
makeClusterStyleFunc () {
const cache = {}
return function __clusterStyleFunc (feature) {
const size = feature.get('features').length
let style = cache[size]
if (!style) {
style = VueLayers.olExt.createStyle({
imageRadius: 10,
strokeColor: '#fff',
fillColor: '#3399cc',
text: size.toString(),
textFillColor: '#fff',
})
cache[size] = style
}
return [style]
}
},
},
})