0
# Utilities and Styling
1
2
Helper functions, color maps, JavaScript integration utilities, and styling tools for advanced customization and programmatic map control.
3
4
## Capabilities
5
6
### JavaScript Integration
7
8
Tools for embedding custom JavaScript code and creating dynamic interactive behaviors.
9
10
```python { .api }
11
class JsCode:
12
"""
13
Wrapper for embedding JavaScript code in map elements.
14
15
Parameters:
16
- js_code: str, JavaScript code to embed
17
18
Returns:
19
JsCode instance that can be used in place of strings for dynamic behavior
20
"""
21
def __init__(self, js_code): ...
22
```
23
24
### Color Maps and Scales
25
26
Color mapping functionality for data-driven visualizations and styling.
27
28
```python { .api }
29
class ColorMap:
30
"""
31
Base class for color mapping functionality.
32
33
Parameters:
34
- colors: list, color values (hex, rgb, or named colors)
35
- index: list, data values corresponding to colors (optional)
36
- vmin: float, minimum data value (default 0)
37
- vmax: float, maximum data value (default 1)
38
- caption: str, colormap legend title
39
40
Returns:
41
ColorMap instance
42
"""
43
def __init__(
44
self,
45
colors,
46
index=None,
47
vmin=0,
48
vmax=1,
49
caption=''
50
): ...
51
52
def to_step(self, n=6, data=None, method='linear', quantiles=None): ...
53
def to_linear(self): ...
54
55
class LinearColormap:
56
"""
57
Linear interpolation between color stops for continuous data visualization.
58
59
Parameters:
60
- colors: list, color values for interpolation
61
- index: list, data values at color stops (optional)
62
- vmin: float, minimum data value (default 0)
63
- vmax: float, maximum data value (default 1)
64
- caption: str, colormap legend title
65
66
Returns:
67
LinearColormap instance
68
"""
69
def __init__(
70
self,
71
colors,
72
index=None,
73
vmin=0,
74
vmax=1,
75
caption=''
76
): ...
77
78
def scale(self, vmin, vmax): ...
79
def to_step(self, n=6, data=None, method='linear', quantiles=None): ...
80
81
class StepColormap:
82
"""
83
Discrete color steps for categorical or binned data visualization.
84
85
Parameters:
86
- colors: list, discrete color values
87
- index: list, bin edges or category values
88
- vmin: float, minimum data value (default 0)
89
- vmax: float, maximum data value (default 1)
90
- caption: str, colormap legend title
91
92
Returns:
93
StepColormap instance
94
"""
95
def __init__(
96
self,
97
colors,
98
index=None,
99
vmin=0,
100
vmax=1,
101
caption=''
102
): ...
103
104
def scale(self, vmin, vmax): ...
105
def to_linear(self): ...
106
```
107
108
### Base Elements and HTML Components
109
110
Foundation classes for creating custom HTML elements and containers (imported from branca).
111
112
```python { .api }
113
class Element:
114
"""
115
Base class for all HTML elements in folium maps.
116
117
Parameters:
118
- template: Template, Jinja2 template for rendering
119
120
Returns:
121
Element instance
122
"""
123
def __init__(self, template=None): ...
124
125
def render(self, **kwargs): ...
126
def add_child(self, child, name=None, index=None): ...
127
def add_to(self, parent): ...
128
129
class Figure:
130
"""
131
Top-level container for complete HTML documents and maps.
132
133
Parameters:
134
- width: str or int, figure width (default '100%')
135
- height: str or int, figure height (default '100%')
136
- left: str, left margin (default '0%')
137
- top: str, top margin (default '0%')
138
- position: str, CSS positioning (default 'relative')
139
- title: str, HTML document title
140
141
Returns:
142
Figure instance
143
"""
144
def __init__(
145
self,
146
width='100%',
147
height='100%',
148
left='0%',
149
top='0%',
150
position='relative',
151
title=None
152
): ...
153
154
def save(self, outfile): ...
155
def show_in_browser(self): ...
156
157
class Html:
158
"""
159
HTML content element for embedding raw HTML.
160
161
Parameters:
162
- data: str, HTML content
163
- script: bool, treat as script tag (default False)
164
165
Returns:
166
Html instance
167
"""
168
def __init__(self, data, script=False): ...
169
170
class Div:
171
"""
172
HTML div container element.
173
174
Parameters:
175
- text: str, text content for the div
176
- script: bool, treat as script tag (default False)
177
178
Returns:
179
Div instance
180
"""
181
def __init__(self, text='', script=False): ...
182
183
class IFrame:
184
"""
185
HTML iframe element for embedding external content.
186
187
Parameters:
188
- html: str, HTML content to embed
189
- width: str or int, iframe width (default '100%')
190
- height: str or int, iframe height (default '100%')
191
192
Returns:
193
IFrame instance
194
"""
195
def __init__(
196
self,
197
html='',
198
width='100%',
199
height='100%'
200
): ...
201
```
202
203
### Resource Linking
204
205
Components for including external CSS and JavaScript resources.
206
207
```python { .api }
208
class CssLink:
209
"""
210
Link to external CSS stylesheet.
211
212
Parameters:
213
- href: str, CSS file URL
214
- download: bool, mark for download (default False)
215
216
Returns:
217
CssLink instance
218
"""
219
def __init__(self, href, download=False): ...
220
221
class JavascriptLink:
222
"""
223
Link to external JavaScript file.
224
225
Parameters:
226
- src: str, JavaScript file URL
227
- download: bool, mark for download (default False)
228
229
Returns:
230
JavascriptLink instance
231
"""
232
def __init__(self, src, download=False): ...
233
234
class Link:
235
"""
236
Generic HTML link element.
237
238
Parameters:
239
- href: str, link URL
240
- download: bool, mark for download (default False)
241
242
Returns:
243
Link instance
244
"""
245
def __init__(self, href, download=False): ...
246
```
247
248
### Advanced Element Base Classes
249
250
Base classes for complex interactive map elements.
251
252
```python { .api }
253
class MacroElement:
254
"""
255
Base class for complex map elements that generate HTML, CSS, and JavaScript.
256
257
Returns:
258
MacroElement instance
259
"""
260
def __init__(self): ...
261
262
def render(self, **kwargs): ...
263
def add_child(self, child, name=None, index=None): ...
264
def add_to(self, parent): ...
265
```
266
267
## Usage Examples
268
269
### Custom JavaScript Behaviors
270
271
```python
272
import folium
273
from folium.utilities import JsCode
274
275
m = folium.Map(location=[45.52, -122.67], zoom_start=12)
276
277
# Custom JavaScript for dynamic marker behavior
278
marker_js = JsCode("""
279
function(e) {
280
var marker = e.target;
281
var popup = marker.getPopup();
282
var currentTime = new Date().toLocaleTimeString();
283
popup.setContent('Clicked at: ' + currentTime);
284
marker.openPopup();
285
}
286
""")
287
288
# Add marker with custom click behavior
289
marker = folium.Marker([45.52, -122.67], popup='Click me!')
290
291
# Note: In practice, custom JavaScript events are added via the _template system
292
# This is a simplified example of the JsCode usage pattern
293
294
marker.add_to(m)
295
m.save('custom_js.html')
296
```
297
298
### Color-mapped Data Visualization
299
300
```python
301
import folium
302
from folium import LinearColormap, StepColormap
303
import pandas as pd
304
import numpy as np
305
306
# Sample data
307
data = pd.DataFrame({
308
'location': [[45.51, -122.68], [45.52, -122.67], [45.53, -122.66]],
309
'temperature': [15.2, 18.7, 22.1],
310
'category': ['cold', 'moderate', 'warm']
311
})
312
313
m = folium.Map(location=[45.52, -122.67], zoom_start=13)
314
315
# Create linear colormap for temperature
316
temp_colormap = LinearColormap(
317
colors=['blue', 'cyan', 'yellow', 'red'],
318
vmin=data['temperature'].min(),
319
vmax=data['temperature'].max(),
320
caption='Temperature (°C)'
321
)
322
temp_colormap.add_to(m)
323
324
# Add temperature-colored circles
325
for idx, row in data.iterrows():
326
color = temp_colormap(row['temperature'])
327
folium.CircleMarker(
328
location=row['location'],
329
radius=15,
330
popup=f"Temperature: {row['temperature']}°C",
331
color=color,
332
fill=True,
333
fillColor=color,
334
fillOpacity=0.7
335
).add_to(m)
336
337
# Create step colormap for categories
338
category_colors = ['blue', 'orange', 'red']
339
category_colormap = StepColormap(
340
colors=category_colors,
341
index=['cold', 'moderate', 'warm'],
342
caption='Temperature Category'
343
)
344
category_colormap.add_to(m)
345
346
m.save('colormap_example.html')
347
```
348
349
### Advanced Custom Element
350
351
```python
352
import folium
353
from branca.element import Template, MacroElement
354
355
# Create custom element class
356
class CustomLegend(MacroElement):
357
"""Custom legend element with dynamic content."""
358
359
_template = Template("""
360
{% macro script(this, kwargs) %}
361
var legend = L.control({position: 'bottomright'});
362
legend.onAdd = function (map) {
363
var div = L.DomUtil.create('div', 'info legend');
364
div.innerHTML = `
365
<h4>{{ this.title }}</h4>
366
{% for item in this.items %}
367
<i style="background:{{ item.color }}"></i> {{ item.label }}<br>
368
{% endfor %}
369
`;
370
return div;
371
};
372
legend.addTo({{ this._parent.get_name() }});
373
{% endmacro %}
374
""")
375
376
def __init__(self, title, items):
377
super().__init__()
378
self._name = 'CustomLegend'
379
self.title = title
380
self.items = items
381
382
# Use custom legend
383
m = folium.Map(location=[45.52, -122.67], zoom_start=12)
384
385
# Add some colored markers
386
colors = ['red', 'blue', 'green']
387
labels = ['High', 'Medium', 'Low']
388
locations = [[45.51, -122.68], [45.52, -122.67], [45.53, -122.66]]
389
390
for color, label, location in zip(colors, labels, locations):
391
folium.Marker(
392
location,
393
popup=f'Category: {label}',
394
icon=folium.Icon(color=color)
395
).add_to(m)
396
397
# Add custom legend
398
legend_items = [
399
{'color': 'red', 'label': 'High Priority'},
400
{'color': 'blue', 'label': 'Medium Priority'},
401
{'color': 'green', 'label': 'Low Priority'}
402
]
403
404
custom_legend = CustomLegend('Priority Levels', legend_items)
405
custom_legend.add_to(m)
406
407
m.save('custom_legend.html')
408
```
409
410
### Dynamic Styling with Data
411
412
```python
413
import folium
414
from folium import LinearColormap
415
import pandas as pd
416
import numpy as np
417
418
# Generate sample data
419
np.random.seed(42)
420
n_points = 50
421
data = pd.DataFrame({
422
'lat': np.random.normal(45.52, 0.02, n_points),
423
'lon': np.random.normal(-122.67, 0.02, n_points),
424
'value': np.random.exponential(10, n_points),
425
'category': np.random.choice(['A', 'B', 'C'], n_points)
426
})
427
428
m = folium.Map(location=[45.52, -122.67], zoom_start=12)
429
430
# Create value-based colormap
431
value_colormap = LinearColormap(
432
colors=['green', 'yellow', 'orange', 'red'],
433
vmin=data['value'].min(),
434
vmax=data['value'].max(),
435
caption='Data Value'
436
)
437
438
# Category colors
439
category_colors = {'A': 'circle', 'B': 'square', 'C': 'triangle'}
440
441
# Add points with dynamic styling
442
for idx, row in data.iterrows():
443
# Color based on value
444
color = value_colormap(row['value'])
445
446
# Size based on value (normalized)
447
size = 5 + (row['value'] / data['value'].max()) * 15
448
449
folium.CircleMarker(
450
location=[row['lat'], row['lon']],
451
radius=size,
452
popup=f"Value: {row['value']:.2f}<br>Category: {row['category']}",
453
color='black',
454
weight=1,
455
fillColor=color,
456
fillOpacity=0.7,
457
tooltip=f"Category {row['category']}"
458
).add_to(m)
459
460
# Add colormap to map
461
value_colormap.add_to(m)
462
463
m.save('dynamic_styling.html')
464
```
465
466
### Complex Figure with Multiple Maps
467
468
```python
469
import folium
470
from branca.element import Figure
471
472
# Create figure container
473
fig = Figure(width='100%', height='600px')
474
475
# Create two maps
476
map1 = folium.Map(location=[45.52, -122.67], zoom_start=11)
477
map2 = folium.Map(location=[40.7128, -74.0060], zoom_start=11)
478
479
# Add content to maps
480
folium.Marker([45.52, -122.67], popup='Portland, OR').add_to(map1)
481
folium.Marker([40.7128, -74.0060], popup='New York, NY').add_to(map2)
482
483
# Add maps to figure with custom positioning
484
map1_html = map1._repr_html_()
485
map2_html = map2._repr_html_()
486
487
# Create side-by-side layout
488
combined_html = f"""
489
<div style="display: flex; width: 100%; height: 100%;">
490
<div style="width: 50%; height: 100%;">
491
{map1_html}
492
</div>
493
<div style="width: 50%; height: 100%;">
494
{map2_html}
495
</div>
496
</div>
497
"""
498
499
# Add to figure
500
fig.html.add_child(folium.Html(combined_html))
501
502
# Save combined figure
503
fig.save('dual_maps.html')
504
```
505
506
### Performance Optimization with Preprocessing
507
508
```python
509
import folium
510
from folium import LinearColormap
511
import pandas as pd
512
import numpy as np
513
514
# Large dataset simulation
515
n_points = 1000
516
data = pd.DataFrame({
517
'lat': np.random.normal(45.52, 0.1, n_points),
518
'lon': np.random.normal(-122.67, 0.1, n_points),
519
'value': np.random.exponential(5, n_points)
520
})
521
522
# Preprocess data for optimal performance
523
# Bin similar values to reduce color calculations
524
data['value_binned'] = pd.cut(data['value'], bins=10, labels=False)
525
526
m = folium.Map(location=[45.52, -122.67], zoom_start=10)
527
528
# Create colormap with discrete steps
529
colors = ['darkgreen', 'green', 'lightgreen', 'yellow', 'orange',
530
'darkorange', 'red', 'darkred', 'purple', 'darkviolet']
531
colormap = LinearColormap(colors=colors, vmin=0, vmax=9, caption='Value Bins')
532
533
# Add optimized markers
534
for bin_value in range(10):
535
bin_data = data[data['value_binned'] == bin_value]
536
if len(bin_data) == 0:
537
continue
538
539
color = colors[bin_value]
540
541
# Create feature group for each bin
542
group = folium.FeatureGroup(name=f'Bin {bin_value}')
543
544
for idx, row in bin_data.iterrows():
545
folium.CircleMarker(
546
location=[row['lat'], row['lon']],
547
radius=5,
548
color=color,
549
fillColor=color,
550
fillOpacity=0.6,
551
popup=f"Value: {row['value']:.2f}",
552
weight=1
553
).add_to(group)
554
555
group.add_to(m)
556
557
# Add controls
558
folium.LayerControl(collapsed=False).add_to(m)
559
colormap.add_to(m)
560
561
m.save('optimized_large_dataset.html')
562
```