|
| 1 | +# Loading event handlers from a CommonJS module |
| 2 | + |
| 3 | +```{code-cell} ipython3 |
| 4 | +--- |
| 5 | +nbsphinx: hidden |
| 6 | +--- |
| 7 | +import folium |
| 8 | +``` |
| 9 | + |
| 10 | +## Loading Event handlers from javascript |
| 11 | +Folium supports event handlers via the `JsCode` class. However, for more than a few lines of code, it becomes unwieldy to write javascript inside python using |
| 12 | +only strings. For more complex code, it is much nicer to write javascript inside js files. This allows editor support, such as syntax highlighting, code completion |
| 13 | +and linting. |
| 14 | + |
| 15 | +Suppose we have the following javascript file: |
| 16 | + |
| 17 | +``` |
| 18 | +/* located in js/handlers.js */ |
| 19 | +on_each_feature = function(f, l) { |
| 20 | + l.bindPopup(function() { |
| 21 | + return '<h5>' + dayjs.unix(f.properties.timestamp).format() + '</h5>'; |
| 22 | + }); |
| 23 | +} |
| 24 | +
|
| 25 | +source = function(responseHandler, errorHandler) { |
| 26 | + var url = 'https://api.wheretheiss.at/v1/satellites/25544'; |
| 27 | +
|
| 28 | + fetch(url) |
| 29 | + .then((response) => { |
| 30 | + return response.json().then((data) => { |
| 31 | + var { id, timestamp, longitude, latitude } = data; |
| 32 | +
|
| 33 | + return { |
| 34 | + 'type': 'FeatureCollection', |
| 35 | + 'features': [{ |
| 36 | + 'type': 'Feature', |
| 37 | + 'geometry': { |
| 38 | + 'type': 'Point', |
| 39 | + 'coordinates': [longitude, latitude] |
| 40 | + }, |
| 41 | + 'properties': { |
| 42 | + 'id': id, |
| 43 | + 'timestamp': timestamp |
| 44 | + } |
| 45 | + }] |
| 46 | + }; |
| 47 | + }) |
| 48 | + }) |
| 49 | + .then(responseHandler) |
| 50 | + .catch(errorHandler); |
| 51 | +} |
| 52 | +
|
| 53 | +module.exports = { |
| 54 | + source, |
| 55 | + on_each_feature |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +Now we can load it as follows inside our python code: |
| 60 | + |
| 61 | +```{code-cell} ipython3 |
| 62 | +from js_loader import install_js_loader |
| 63 | +from folium.plugins import Realtime |
| 64 | +install_js_loader() |
| 65 | +
|
| 66 | +from js import handlers |
| 67 | +
|
| 68 | +m = folium.Map() |
| 69 | +
|
| 70 | +rt = Realtime(handlers.source, |
| 71 | + on_each_feature=handlers.on_each_feature, |
| 72 | + interval=1000) |
| 73 | +rt.add_js_link("dayjs", "https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js") |
| 74 | +rt.add_to(m) |
| 75 | +m |
| 76 | +``` |
0 commit comments