UNPKG

1.84 kBJavaScriptView Raw
1goog.require('ol.Map');
2goog.require('ol.View');
3goog.require('ol.events.condition');
4goog.require('ol.format.GeoJSON');
5goog.require('ol.interaction.DragBox');
6goog.require('ol.interaction.Select');
7goog.require('ol.layer.Tile');
8goog.require('ol.layer.Vector');
9goog.require('ol.source.OSM');
10goog.require('ol.source.Vector');
11
12
13var vectorSource = new ol.source.Vector({
14 url: 'data/geojson/countries.geojson',
15 format: new ol.format.GeoJSON()
16});
17
18
19var map = new ol.Map({
20 layers: [
21 new ol.layer.Tile({
22 source: new ol.source.OSM()
23 }),
24 new ol.layer.Vector({
25 source: vectorSource
26 })
27 ],
28 target: 'map',
29 view: new ol.View({
30 center: [0, 0],
31 zoom: 2
32 })
33});
34
35// a normal select interaction to handle click
36var select = new ol.interaction.Select();
37map.addInteraction(select);
38
39var selectedFeatures = select.getFeatures();
40
41// a DragBox interaction used to select features by drawing boxes
42var dragBox = new ol.interaction.DragBox({
43 condition: ol.events.condition.platformModifierKeyOnly
44});
45
46map.addInteraction(dragBox);
47
48dragBox.on('boxend', function() {
49 // features that intersect the box are added to the collection of
50 // selected features
51 var extent = dragBox.getGeometry().getExtent();
52 vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
53 selectedFeatures.push(feature);
54 });
55});
56
57// clear selection when drawing a new box and when clicking on the map
58dragBox.on('boxstart', function() {
59 selectedFeatures.clear();
60});
61
62var infoBox = document.getElementById('info');
63
64selectedFeatures.on(['add', 'remove'], function() {
65 var names = selectedFeatures.getArray().map(function(feature) {
66 return feature.get('name');
67 });
68 if (names.length > 0) {
69 infoBox.innerHTML = names.join(', ');
70 } else {
71 infoBox.innerHTML = 'No countries selected';
72 }
73});