1 |
|
2 | var Nanocomponent = require('../')
|
3 | var nanologger = require('nanologger')
|
4 | var leaflet = require('leaflet')
|
5 | var onIdle = require('on-idle')
|
6 | var html = require('bel')
|
7 |
|
8 | module.exports = Leaflet
|
9 |
|
10 | function Leaflet () {
|
11 | if (!(this instanceof Leaflet)) return new Leaflet()
|
12 | Nanocomponent.call(this)
|
13 |
|
14 | this._log = nanologger('leaflet')
|
15 | this.map = null
|
16 | this.coords = [0, 0]
|
17 | }
|
18 |
|
19 | Leaflet.prototype = Object.create(Nanocomponent.prototype)
|
20 |
|
21 | Leaflet.prototype.createElement = function (coords) {
|
22 | this.coords = coords
|
23 | return html`
|
24 | <div style="height: 500px">
|
25 | <div id="map"></div>
|
26 | </div>
|
27 | `
|
28 | }
|
29 |
|
30 | Leaflet.prototype.update = function (coords) {
|
31 | if (!this.map) return this._log.warn('missing map', 'failed to update')
|
32 | if (coords[0] !== this.coords[0] || coords[1] !== this.coords[1]) {
|
33 | var self = this
|
34 | onIdle(function () {
|
35 | self.coords = coords
|
36 | self._log.info('update-map', coords)
|
37 | self.map.setView(coords, 12)
|
38 | })
|
39 | }
|
40 | return false
|
41 | }
|
42 |
|
43 | Leaflet.prototype.beforerender = function (el) {
|
44 | var coords = this.coords
|
45 | this._log.info('create-map', coords)
|
46 |
|
47 | var map = leaflet.map(el).setView(coords, 12)
|
48 | leaflet.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', {
|
49 | attribution: 'Map tiles by <a href="https://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
|
50 | subdomains: 'abcd',
|
51 | minZoom: 0,
|
52 | maxZoom: 20,
|
53 | ext: 'png'
|
54 | }).addTo(map)
|
55 | this.map = map
|
56 | }
|
57 |
|
58 | Leaflet.prototype.load = function () {
|
59 | this._log.info('load')
|
60 | this.map.invalidateSize()
|
61 | }
|
62 |
|
63 | Leaflet.prototype.unload = function () {
|
64 | this._log.info('unload')
|
65 |
|
66 | this.map.remove()
|
67 | this.map = null
|
68 | this.coords = [0, 0]
|
69 | }
|