UNPKG

1.93 kBJavaScriptView Raw
1// // adapted from https://github.com/timwis/choo-leaflet-demo/blob/master/src/map.js
2var Nanocomponent = require('../')
3var nanologger = require('nanologger')
4var leaflet = require('leaflet')
5var onIdle = require('on-idle')
6var html = require('bel')
7
8module.exports = Leaflet
9
10function Leaflet () {
11 if (!(this instanceof Leaflet)) return new Leaflet()
12 Nanocomponent.call(this)
13
14 this._log = nanologger('leaflet')
15 this.map = null // capture leaflet
16 this.coords = [0, 0] // null island
17}
18
19Leaflet.prototype = Object.create(Nanocomponent.prototype)
20
21Leaflet.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
30Leaflet.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
43Leaflet.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> &mdash; Map data &copy; <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
58Leaflet.prototype.load = function () {
59 this._log.info('load')
60 this.map.invalidateSize()
61}
62
63Leaflet.prototype.unload = function () {
64 this._log.info('unload')
65
66 this.map.remove()
67 this.map = null
68 this.coords = [0, 0]
69}