UNPKG

2.45 kBJavaScriptView Raw
1goog.require('ol.Map');
2goog.require('ol.View');
3goog.require('ol.format.GeoJSON');
4goog.require('ol.layer.Vector');
5goog.require('ol.source.Vector');
6goog.require('ol.style.Fill');
7goog.require('ol.style.Stroke');
8goog.require('ol.style.Style');
9goog.require('ol.style.Text');
10
11
12var style = new ol.style.Style({
13 fill: new ol.style.Fill({
14 color: 'rgba(255, 255, 255, 0.6)'
15 }),
16 stroke: new ol.style.Stroke({
17 color: '#319FD3',
18 width: 1
19 }),
20 text: new ol.style.Text({
21 font: '12px Calibri,sans-serif',
22 fill: new ol.style.Fill({
23 color: '#000'
24 }),
25 stroke: new ol.style.Stroke({
26 color: '#fff',
27 width: 3
28 })
29 })
30});
31
32var vectorLayer = new ol.layer.Vector({
33 source: new ol.source.Vector({
34 url: 'data/geojson/countries.geojson',
35 format: new ol.format.GeoJSON()
36 }),
37 style: function(feature) {
38 style.getText().setText(feature.get('name'));
39 return style;
40 }
41});
42
43var map = new ol.Map({
44 layers: [vectorLayer],
45 target: 'map',
46 view: new ol.View({
47 center: [0, 0],
48 zoom: 1
49 })
50});
51
52var highlightStyle = new ol.style.Style({
53 stroke: new ol.style.Stroke({
54 color: '#f00',
55 width: 1
56 }),
57 fill: new ol.style.Fill({
58 color: 'rgba(255,0,0,0.1)'
59 }),
60 text: new ol.style.Text({
61 font: '12px Calibri,sans-serif',
62 fill: new ol.style.Fill({
63 color: '#000'
64 }),
65 stroke: new ol.style.Stroke({
66 color: '#f00',
67 width: 3
68 })
69 })
70});
71
72var featureOverlay = new ol.layer.Vector({
73 source: new ol.source.Vector(),
74 map: map,
75 style: function(feature) {
76 highlightStyle.getText().setText(feature.get('name'));
77 return highlightStyle;
78 }
79});
80
81var highlight;
82var displayFeatureInfo = function(pixel) {
83
84 var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
85 return feature;
86 });
87
88 var info = document.getElementById('info');
89 if (feature) {
90 info.innerHTML = feature.getId() + ': ' + feature.get('name');
91 } else {
92 info.innerHTML = ' ';
93 }
94
95 if (feature !== highlight) {
96 if (highlight) {
97 featureOverlay.getSource().removeFeature(highlight);
98 }
99 if (feature) {
100 featureOverlay.getSource().addFeature(feature);
101 }
102 highlight = feature;
103 }
104
105};
106
107map.on('pointermove', function(evt) {
108 if (evt.dragging) {
109 return;
110 }
111 var pixel = map.getEventPixel(evt.originalEvent);
112 displayFeatureInfo(pixel);
113});
114
115map.on('click', function(evt) {
116 displayFeatureInfo(evt.pixel);
117});