1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| import Feature from 'ol/Feature.js'; import Map from 'ol/Map.js'; import Point from 'ol/geom/Point.js'; import View from 'ol/View.js'; import { Circle as CircleStyle, Fill, Stroke, Style, Text, } from 'ol/style.js'; import {Cluster, OSM, Vector as VectorSource} from 'ol/source.js'; import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js'; import {boundingExtent} from 'ol/extent.js';
const distanceInput = document.getElementById('distance'); const minDistanceInput = document.getElementById('min-distance');
const count = 20000; const features = new Array(count); const e = 4500000; for (let i = 0; i < count; ++i) { const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; features[i] = new Feature(new Point(coordinates)); }
const source = new VectorSource({ features: features, });
const clusterSource = new Cluster({ distance: parseInt(distanceInput.value, 10), minDistance: parseInt(minDistanceInput.value, 10), source: source, });
const styleCache = {}; const clusters = new VectorLayer({ source: clusterSource, style: function (feature) { const size = feature.get('features').length; let style = styleCache[size]; if (!style) { style = new Style({ image: new CircleStyle({ radius: 10, stroke: new Stroke({ color: '#fff', }), fill: new Fill({ color: '#3399CC', }), }), text: new Text({ text: size.toString(), fill: new Fill({ color: '#fff', }), }), }); styleCache[size] = style; } return style; }, });
const raster = new TileLayer({ source: new OSM(), });
const map = new Map({ layers: [raster, clusters], target: 'map', view: new View({ center: [0, 0], zoom: 2, }), });
distanceInput.addEventListener('input', function () { clusterSource.setDistance(parseInt(distanceInput.value, 10)); });
minDistanceInput.addEventListener('input', function () { clusterSource.setMinDistance(parseInt(minDistanceInput.value, 10)); });
map.on('click', (e) => { clusters.getFeatures(e.pixel).then((clickedFeatures) => { if (clickedFeatures.length) { const features = clickedFeatures[0].get('features'); if (features.length > 1) { const extent = boundingExtent( features.map((r) => r.getGeometry().getCoordinates()) ); map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]}); } } }); });
|