UNPKG

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