UNPKG

2.11 kBJavaScriptView Raw
1goog.require('ol.Map');
2goog.require('ol.Overlay');
3goog.require('ol.View');
4goog.require('ol.layer.Tile');
5goog.require('ol.source.TileJSON');
6goog.require('ol.source.TileUTFGrid');
7
8var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg';
9
10var mapLayer = new ol.layer.Tile({
11 source: new ol.source.TileJSON({
12 url: 'https://api.tiles.mapbox.com/v4/mapbox.geography-class.json?secure&access_token=' + key
13 })
14});
15
16
17var gridSource = new ol.source.TileUTFGrid({
18 url: 'https://api.tiles.mapbox.com/v4/mapbox.geography-class.json?secure&access_token=' + key
19});
20
21var gridLayer = new ol.layer.Tile({source: gridSource});
22
23var view = new ol.View({
24 center: [0, 0],
25 zoom: 1
26});
27
28var mapElement = document.getElementById('map');
29var map = new ol.Map({
30 layers: [mapLayer, gridLayer],
31 target: mapElement,
32 view: view
33});
34
35var infoElement = document.getElementById('country-info');
36var flagElement = document.getElementById('country-flag');
37var nameElement = document.getElementById('country-name');
38
39var infoOverlay = new ol.Overlay({
40 element: infoElement,
41 offset: [15, 15],
42 stopEvent: false
43});
44map.addOverlay(infoOverlay);
45
46var displayCountryInfo = function(coordinate) {
47 var viewResolution = /** @type {number} */ (view.getResolution());
48 gridSource.forDataAtCoordinateAndResolution(coordinate, viewResolution,
49 function(data) {
50 // If you want to use the template from the TileJSON,
51 // load the mustache.js library separately and call
52 // info.innerHTML = Mustache.render(gridSource.getTemplate(), data);
53 mapElement.style.cursor = data ? 'pointer' : '';
54 if (data) {
55 flagElement.src = 'data:image/png;base64,' + data['flag_png'];
56 nameElement.innerHTML = data['admin'];
57 }
58 infoOverlay.setPosition(data ? coordinate : undefined);
59 });
60};
61
62map.on('pointermove', function(evt) {
63 if (evt.dragging) {
64 return;
65 }
66 var coordinate = map.getEventCoordinate(evt.originalEvent);
67 displayCountryInfo(coordinate);
68});
69
70map.on('click', function(evt) {
71 displayCountryInfo(evt.coordinate);
72});