Created
November 5, 2016 23:20
-
-
Save timwis/0f2d3388931b73c466fd9d87c49940c4 to your computer and use it in GitHub Desktop.
leaflet in choo using isSameNode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const html = require('choo/html') | |
const L = require('leaflet') | |
module.exports = () => { | |
let cachedEl | |
let cachedCoords | |
let map | |
return function (coords) { | |
let currentCoords = coords | |
const defaultZoom = 12 | |
if (coords && (!cachedCoords || !coordsMatch(coords, cachedCoords))) { | |
cachedCoords = coords | |
if (map) map.setView(coords) | |
} | |
if (!cachedEl) { | |
console.log('creating map el') | |
cachedEl = html` | |
<div style="height: 500px" onload=${onload} onunload=${onunload}></div> | |
` | |
return cachedEl | |
} else { | |
console.log('returning proxy el') | |
const proxy = document.createElement('div') | |
proxy.isSameNode = function (fromNode) { | |
return fromNode.isSameNode(cachedEl) | |
} | |
return proxy | |
} | |
function onload (el) { | |
map = L.map(el).setView(currentCoords, defaultZoom) | |
L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', { | |
attribution: 'Map tiles by <a href="http://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>', | |
subdomains: 'abcd', | |
minZoom: 0, | |
maxZoom: 20, | |
ext: 'png' | |
}).addTo(map) | |
} | |
function onunload (el) { | |
if (map) { | |
map.remove() | |
map = null | |
} | |
} | |
} | |
} | |
function coordsMatch (a, b) { | |
return a[0] === b[0] && a[1] === b[1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment