Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
175 commits
Select commit Hold shift + click to select a range
287ac36
Update features.py
jtbaker Jun 15, 2018
2491e19
Cleaned up code linting for this commit.
jtbaker Jun 15, 2018
6290a5b
Update features.py
jtbaker Jun 15, 2018
fda9729
Further linting.
jtbaker Jun 15, 2018
bde7a2b
Hopefully last linting.
jtbaker Jun 15, 2018
b5f9282
Update features.py
jtbaker Jun 15, 2018
8e5168c
Update features.py
jtbaker Jun 16, 2018
73b1f4d
Update features.py
jtbaker Jun 16, 2018
d03bf2f
lint
jtbaker Jun 16, 2018
8ce80a6
lint
jtbaker Jun 16, 2018
bb325f4
lint
jtbaker Jun 16, 2018
bd2a12f
lint
jtbaker Jun 16, 2018
c73686e
lint
jtbaker Jun 16, 2018
5b9cb8b
lint
jtbaker Jun 16, 2018
5525df0
Update features.py
jtbaker Jun 16, 2018
cc89971
Update features.py
jtbaker Jun 16, 2018
bb825f0
Update features.py
jtbaker Jun 19, 2018
5c9c425
More lint checking.
jtbaker Jun 19, 2018
16d44f0
Update features.py
jtbaker Jun 19, 2018
2fb3437
Update features.py
jtbaker Jun 19, 2018
9933f58
Update features.py
jtbaker Jun 19, 2018
c8d404d
Update features.py
jtbaker Jun 19, 2018
90d7de9
Update features.py
jtbaker Jun 19, 2018
bfd277b
Merge pull request #1 from python-visualization/master
jtbaker Jun 23, 2018
84811a0
PC-2018.1.2 <jasonbaker@Earl.local Overwrite remote https://github.co…
jtbaker Jun 23, 2018
76c9622
PC-2018.1.2 <jasonbaker@Earl.local Create baseRefactoring.xml, Intell…
jtbaker Jun 23, 2018
f69bb30
Revert "PC-2018.1.2 <jasonbaker@Earl.local Create baseRefactoring.xml…
jtbaker Jun 23, 2018
cf116fe
Revert "PC-2018.1.2 <jasonbaker@Earl.local Overwrite remote https://g…
jtbaker Jun 23, 2018
f9e3eb8
PC-2018.1.2 <jasonbaker@Earl.local Update vcs.xml
jtbaker Jun 24, 2018
d9f4109
PC-2018.1.2 <jasonbaker@Earl.local Merge branch 'master'
jtbaker Jun 24, 2018
ac3e03e
PC-2018.1.2 <jasonbaker@Earl.local Create code.style.schemes, laf.xml…
jtbaker Jun 24, 2018
3dc30cb
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
25e80a1
Merge pull request #2 from jtbaker/New-Tooltip
jtbaker Jun 24, 2018
405245c
Merge branch 'patch-2' into master
jtbaker Jun 24, 2018
ee8c427
Merge pull request #3 from jtbaker/master
jtbaker Jun 24, 2018
12e04f8
Missed a line remove when resolving conflicts.
jtbaker Jun 24, 2018
5a00b8b
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
f40d145
Merge pull request #4 from jtbaker/New-Tooltip
jtbaker Jun 24, 2018
e1431a2
PC-2018.1.2 <jasonbaker@Earl.local Update Default.xml
jtbaker Jun 24, 2018
86b29df
PC-2018.1.2 <jasonbaker@Earl.local Create editor.xml
jtbaker Jun 24, 2018
844ec5b
PC-2018.1.2 <jasonbaker@Earl.local Merge branch 'master'
jtbaker Jun 24, 2018
9364c3f
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
b95f840
Merge branch 'patch-2' into New-Tooltip
jtbaker Jun 24, 2018
856aa80
Merge pull request #5 from jtbaker/New-Tooltip
jtbaker Jun 24, 2018
7eaa85e
Merge pull request #6 from jtbaker/patch-2
jtbaker Jun 24, 2018
e4978be
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
1e5242f
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
7c7e29d
Updated Tooltip class args to inherit from object.
jtbaker Jun 24, 2018
c0937e0
Merge remote-tracking branch 'origin/New-Tooltip' into New-Tooltip
jtbaker Jun 24, 2018
ab9da22
Updated Tooltip class args to inherit from object.
jtbaker Jun 24, 2018
2a7cdea
Merge pull request #7 from jtbaker/New-Tooltip
jtbaker Jun 24, 2018
6e158bd
In GeoJson:
jtbaker Jun 27, 2018
9070673
Merge pull request #8 from jtbaker/New-Tooltip
jtbaker Jun 27, 2018
b899c42
Missed a whitespace lint on that last commit.
jtbaker Jun 27, 2018
4f2e36c
Merge pull request #9 from jtbaker/New-Tooltip
jtbaker Jun 27, 2018
bb8b3ee
Adding a convenience import from folium.features for the Tooltip class
jtbaker Jun 27, 2018
cdce807
Merge pull request #10 from jtbaker/New-Tooltip
jtbaker Jun 27, 2018
de5606a
PC-2018.1.2 <jasonbaker@Earl.local Create laf.xml, filetypes.xml, key…
jtbaker Jun 28, 2018
76af841
PC-2018.1.2 <jasonbaker@Earl.local Create github_settings.xml, Defaul…
jtbaker Jun 29, 2018
31a7685
PC-2018.1.2 <jasonbaker@Earl.local Create git.xml
jtbaker Jun 29, 2018
c0ea0b5
PC-2018.1.2 <jasonbaker@Earl.local Create ui.lnf.xml, Default.xml
jtbaker Jul 10, 2018
8fa9122
PC-2018.1.2 <jasonbaker@Earl.local Update Default.xml
jtbaker Jul 10, 2018
cc5aaf0
Updated Tooltip class args to inherit from object.
jtbaker Jul 10, 2018
b8cd620
Updated Tooltip class args to inherit from object.
jtbaker Jul 10, 2018
6d41b99
Moving GeoJSON template to Tooltip class.
jtbaker Jul 10, 2018
806cded
Adding name reference to self.add_child method.
jtbaker Jul 10, 2018
7f9a48e
Tooltip now inherits from MacroElement, and template runs in Macro
jtbaker Jul 11, 2018
d256e0d
Tooltip now inherits from MacroElement, and template runs in Macro
jtbaker Jul 11, 2018
f80b68c
Nested tooltip isInstance testing inside of 'if tooltip' test.
jtbaker Jul 11, 2018
dee1522
Nested tooltip isInstance testing inside of 'if tooltip' test.
jtbaker Jul 11, 2018
c1b67fe
Merge pull request #11 from jtbaker/New-Tooltip
jtbaker Jul 11, 2018
ad2596c
Current Docstring Reference.
jtbaker Jul 11, 2018
5f4768b
Added Tooltip support for more vector and map layers.
jtbaker Jul 11, 2018
9c38662
Added Tooltip support for more vector and map layers.
jtbaker Jul 11, 2018
f54ebcb
Added Tooltip support for more Marker layers.
jtbaker Jul 11, 2018
3d8a1be
Merge pull request #12 from jtbaker/New-Tooltip
jtbaker Jul 11, 2018
b7da78d
Updated Tooltip class args to inherit from object.
jtbaker Jul 12, 2018
11eb4f1
Updated Tooltip class args to inherit from object.
jtbaker Jul 12, 2018
c2b575c
Added style argument to Tooltip. Tooltip now wraps an HTML div element
jtbaker Jul 12, 2018
f80874a
Merge pull request #13 from jtbaker/New-Tooltip
jtbaker Jul 12, 2018
d54fc0a
Added style argument to Tooltip. Tooltip now wraps an HTML div element
jtbaker Jul 12, 2018
72e0516
Merge pull request #14 from jtbaker/New-Tooltip
jtbaker Jul 12, 2018
a2cf404
Reworded text section of docstring.
jtbaker Jul 12, 2018
118e751
Merge pull request #15 from jtbaker/New-Tooltip
jtbaker Jul 12, 2018
d761bb4
Typo correction.
jtbaker Jul 13, 2018
b85a6d3
Added a `validate_tooltip` method to `Marker` that every item which i…
jtbaker Jul 15, 2018
2478531
PC-2018.1.2 <jasonbaker@Earl.local Create diff.xml
jtbaker Jul 15, 2018
eac16da
PC-2018.1.2 <jasonbaker@Earl.local Update github_settings.xml
jtbaker Jul 17, 2018
0725b4b
Update features.py
jtbaker Jun 15, 2018
99db68d
Cleaned up code linting for this commit.
jtbaker Jun 15, 2018
200155b
Update features.py
jtbaker Jun 15, 2018
f7cee1b
Further linting.
jtbaker Jun 15, 2018
9b5ecc8
Hopefully last linting.
jtbaker Jun 15, 2018
4e54b19
Update features.py
jtbaker Jun 15, 2018
6ef92db
Update features.py
jtbaker Jun 16, 2018
1f3c402
Update features.py
jtbaker Jun 16, 2018
f860855
lint
jtbaker Jun 16, 2018
292d54d
lint
jtbaker Jun 16, 2018
7a7ee05
lint
jtbaker Jun 16, 2018
cdda09d
lint
jtbaker Jun 16, 2018
bbfbb49
lint
jtbaker Jun 16, 2018
98e7f45
lint
jtbaker Jun 16, 2018
461bf11
Update features.py
jtbaker Jun 16, 2018
875c6ba
Update features.py
jtbaker Jun 16, 2018
3eb8816
Update features.py
jtbaker Jun 19, 2018
c2fa01e
More lint checking.
jtbaker Jun 19, 2018
9226117
Update features.py
jtbaker Jun 19, 2018
e5e3e48
Update features.py
jtbaker Jun 19, 2018
9d00638
Update features.py
jtbaker Jun 19, 2018
46a8f05
Update features.py
jtbaker Jun 19, 2018
a530153
Update features.py
jtbaker Jun 19, 2018
f8eea8a
PC-2018.1.2 <jasonbaker@Earl.local Overwrite remote https://github.co…
jtbaker Jun 23, 2018
3f9ebab
PC-2018.1.2 <jasonbaker@Earl.local Create baseRefactoring.xml, Intell…
jtbaker Jun 23, 2018
812ec07
Revert "PC-2018.1.2 <jasonbaker@Earl.local Create baseRefactoring.xml…
jtbaker Jun 23, 2018
f3e66a4
Revert "PC-2018.1.2 <jasonbaker@Earl.local Overwrite remote https://g…
jtbaker Jun 23, 2018
a3d9af2
PC-2018.1.2 <jasonbaker@Earl.local Create code.style.schemes, laf.xml…
jtbaker Jun 24, 2018
4c5f94a
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
1774c1b
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
aad6580
PC-2018.1.2 <jasonbaker@Earl.local Update Default.xml
jtbaker Jun 24, 2018
2d536db
PC-2018.1.2 <jasonbaker@Earl.local Create editor.xml
jtbaker Jun 24, 2018
9098a75
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
0be87d5
Updated code for line length limitation, verbiage, and indentations.
jtbaker Jun 24, 2018
919f7d9
Merge branch 'master' of https://github.com/jtbaker/folium
jtbaker Jul 17, 2018
cc74c27
Rebasing my master.
jtbaker Jul 17, 2018
5d700fc
Suggested changes implemented.
jtbaker Jul 17, 2018
7a3f4c5
Merge branch 'patch-2' into New-Tooltip
jtbaker Jul 17, 2018
789072d
Merge pull request #16 from jtbaker/New-Tooltip
jtbaker Jul 17, 2018
8fc0bee
Stickler lint changes.
jtbaker Jul 18, 2018
cba08d6
PC-2018.1.2 <jasonbaker@Earl.local Create vcs.xml
jtbaker Jul 19, 2018
1f9dbf2
Reworked template to HTML table tag format.
jtbaker Jul 19, 2018
391119a
Merge pull request #17 from jtbaker/New-Tooltip
jtbaker Jul 19, 2018
6d931bd
Line length.
jtbaker Jul 19, 2018
ba52b1e
Merge pull request #18 from jtbaker/New-Tooltip
jtbaker Jul 19, 2018
52df6eb
Cosmetic changes
Conengmo Jul 20, 2018
1805fb8
Fix Marker template, no kwargs
Conengmo Jul 20, 2018
907c50e
Move Tooltip creation to separate function
Conengmo Jul 20, 2018
08dd0f1
All Marker children pass tooltip argument to parent
Conengmo Jul 20, 2018
5deee0e
GeoJson/TopoJson template without tooltip
Conengmo Jul 20, 2018
d972fd0
Separate Tooltip creation func for GeoJson/TopoJson
Conengmo Jul 20, 2018
453bd76
Don't use tooltip in ClickForMarker
Conengmo Jul 20, 2018
643a61b
Small linter fixes
Conengmo Jul 20, 2018
bd51b9e
PC-2018.1.2 <jasonbaker@Earl.local Merge branch 'master'
jtbaker Jul 27, 2018
0033a09
Merge pull request #19 from Conengmo/tooltip
jtbaker Jul 31, 2018
09b410a
PC-2018.1.2 <jasonbaker@Earl.local Create ide.general.xml
jtbaker Jul 31, 2018
888096c
Merge pull request #20 from python-visualization/master
jtbaker Jul 31, 2018
a4cd159
Split tooltip class in regular and geojson version
Conengmo Jul 31, 2018
50e029b
Docstrings, add checks in render
Conengmo Jul 31, 2018
a1b47a3
Util func to convert to lowerCamelCase
Conengmo Aug 2, 2018
0048179
Tooltip options validation
Conengmo Aug 2, 2018
1a64e8e
Single if-statement for type checking
Conengmo Aug 2, 2018
1813eac
Remove 'style' and 'highlight' from keys
Conengmo Aug 2, 2018
208f399
Assert `permanent` option is not used in GeoJsonTooltip
Conengmo Aug 2, 2018
a912b7e
Some cosmetic changes
Conengmo Aug 2, 2018
c441159
Merge remote-tracking branch 'remotes/upstream/master' into tooltip-s…
Conengmo Aug 2, 2018
ea6da8e
Merge remote-tracking branch 'remotes/upstream/master' into patch-2
Conengmo Aug 2, 2018
511261c
Small change to trigger tests
Conengmo Aug 2, 2018
205c9d4
Merge pull request #22 from Conengmo/tooltip-split
jtbaker Aug 2, 2018
8b06fde
Add function to handle non-primitives in GeoJSON fields.
jtbaker Aug 2, 2018
036f191
Switch `toLocaleString` to `localize`.
jtbaker Aug 2, 2018
c5a43bd
Add Function to handle non-primitives in GeoJSON fields.
jtbaker Aug 2, 2018
efbd8a4
Switch `toLocaleString` to `localize`, along with all references.
jtbaker Aug 2, 2018
a93a4cb
Convert template to reference `this.options`.
jtbaker Aug 2, 2018
78021f5
create JS function to handle representation of non-primitive data in
jtbaker Aug 2, 2018
02621f9
Merge branch 'patch-2' into tooltip-split
jtbaker Aug 2, 2018
c8d2c7b
Reverted changes to Marker that were out of the scope of this PR.
jtbaker Aug 3, 2018
3edd6b5
Merge remote-tracking branch 'origin/tooltip-split' into tooltip-split
jtbaker Aug 3, 2018
cbe4622
Merge pull request #23 from jtbaker/tooltip-split
jtbaker Aug 3, 2018
e72f858
Remove stowaway xmls
Conengmo Aug 7, 2018
285d79a
Linter: remove unused pytest import
Conengmo Aug 7, 2018
678e459
Rename function to parse_options
Conengmo Aug 7, 2018
ba10631
Correct GeoJsonTooltip._name
Conengmo Aug 7, 2018
c928625
Typos and clarifications
Conengmo Aug 7, 2018
738992c
Change Leaflet URL for doc build
Conengmo Aug 7, 2018
3f3c8bf
Revert Leaflet docs urls to include version
Conengmo Aug 7, 2018
ba78359
Update CHANGES.txt
Conengmo Aug 8, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- Added `zoom_control` to `Map` to toggle zoom controls as per enhancement (#795) (okomarov #899)
- Change default `date_options` in TimestampedGeoJson (andy23512 #914)
- Added gradient argument to HeatMapWithTime (jtbaker #925)
- Added `Tooltip` and `GeoJsonTooltip` classes (jtbaker #883)

API changes

Expand Down
4 changes: 3 additions & 1 deletion folium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
from folium.features import (
ClickForMarker, ColorLine, CustomIcon, DivIcon, GeoJson,
LatLngPopup, RegularPolygonMarker, TopoJson, Vega, VegaLite,
GeoJsonTooltip,
)

from folium.raster_layers import TileLayer, WmsTileLayer

from folium.folium import Map

from folium.map import (
FeatureGroup, FitBounds, Icon, LayerControl, Marker, Popup
FeatureGroup, FitBounds, Icon, LayerControl, Marker, Popup, Tooltip
)

from folium.vector_layers import Circle, CircleMarker, PolyLine, Polygon, Rectangle # noqa
Expand Down Expand Up @@ -52,6 +53,7 @@
'LayerControl',
'Marker',
'Popup',
'Tooltip',
'TileLayer',
'ClickForMarker',
'CustomIcon',
Expand Down
259 changes: 191 additions & 68 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
import json

from branca.colormap import LinearColormap
from branca.element import (CssLink, Element, Figure, JavascriptLink, MacroElement) # noqa
from branca.utilities import (_locations_tolist, _parse_size, image_to_url, iter_points, none_max, none_min) # noqa
from branca.element import (Element, Figure, JavascriptLink, MacroElement)
from branca.utilities import (_locations_tolist, _parse_size, image_to_url,
none_max, none_min)

from folium.map import (FeatureGroup, Icon, Layer, Marker, Tooltip)

from folium.map import FeatureGroup, Icon, Layer, Marker
from folium.utilities import get_bounds
from folium.vector_layers import PolyLine

Expand Down Expand Up @@ -49,10 +51,9 @@ class RegularPolygonMarker(Marker):
radius: int, default 15
Marker radius, in pixels
popup: string or folium.Popup, default None
Input text or visualization for object. Can pass either text,
or a folium.Popup object.
If None, no popup will be displayed.

Input text or visualization for object displayed when clicking.
tooltip: str or folium.Tooltip, default None
Display a text when hovering over the object.

https://humangeo.github.io/leaflet-dvf/

Expand All @@ -72,17 +73,16 @@ class RegularPolygonMarker(Marker):
rotation: {{this.rotation}},
radius: {{this.radius}}
}
)
.addTo({{this._parent.get_name()}});
).addTo({{this._parent.get_name()}});
{% endmacro %}
""")

def __init__(self, location, color='black', opacity=1, weight=2,
fill_color='blue', fill_opacity=1,
number_of_sides=4, rotation=0, radius=15, popup=None):
fill_color='blue', fill_opacity=1, number_of_sides=4,
rotation=0, radius=15, popup=None, tooltip=None):
super(RegularPolygonMarker, self).__init__(
_locations_tolist(location),
popup=popup
popup=popup, tooltip=tooltip
)
self._name = 'RegularPolygonMarker'
self.color = color
Expand Down Expand Up @@ -325,6 +325,9 @@ class GeoJson(Layer):
How much to simplify the polyline on each zoom level. More means
better performance and smoother look, and less means more accurate
representation. Leaflet defaults to 1.0.
tooltip: GeoJsonTooltip, Tooltip or str, default None
Display a text when hovering over the object. Can utilize the data,
see folium.GeoJsonTooltip for info on how to do that.

Examples
--------
Expand All @@ -345,52 +348,46 @@ class GeoJson(Layer):

"""
_template = Template(u"""
{% macro script(this, kwargs) %}

{% if this.highlight %}
{{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) {
layer.on({
mouseout: function(e) {
e.target.setStyle(e.target.feature.properties.style);},
mouseover: function(e) {
e.target.setStyle(e.target.feature.properties.highlight);},
click: function(e) {
{{this._parent.get_name()}}.fitBounds(e.target.getBounds());}
});
};
{% endif %}

var {{this.get_name()}} = L.geoJson(
{% if this.embed %}{{this.style_data()}}{% else %}"{{this.data}}"{% endif %}
{% if this.smooth_factor is not none or this.highlight %}
, {
{% if this.smooth_factor is not none %}
smoothFactor:{{this.smooth_factor}}
{% endif %}

{% if this.highlight %}
{% if this.smooth_factor is not none %}
,
{% endif %}
onEachFeature: {{this.get_name()}}_onEachFeature
{% endif %}
}
{% macro script(this, kwargs) %}
{% if this.highlight %}
{{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) {
layer.on({
mouseout: function(e) {
e.target.setStyle(e.target.feature.properties.style);},
mouseover: function(e) {
e.target.setStyle(e.target.feature.properties.highlight);},
click: function(e) {
{{this._parent.get_name()}}.fitBounds(e.target.getBounds());}
});
};
{% endif %}
var {{this.get_name()}} = L.geoJson(
{% if this.embed %}{{this.style_data()}}{% else %}"{{this.data}}"{% endif %}
{% if this.smooth_factor is not none or this.highlight %}
, {
{% if this.smooth_factor is not none %}
smoothFactor:{{this.smooth_factor}}
{% endif %}

{% if this.highlight %}
{% if this.smooth_factor is not none %}
,
{% endif %}
)
{% if this.tooltip %}.bindTooltip("{{this.tooltip.__str__()}}"){% endif %}
.addTo({{this._parent.get_name()}});
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});

{% endmacro %}
""") # noqa
onEachFeature: {{this.get_name()}}_onEachFeature
{% endif %}
}
{% endif %}
).addTo({{this._parent.get_name()}});
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});
{% endmacro %}
""") # noqa

def __init__(self, data, style_function=None, name=None,
overlay=True, control=True, show=True,
smooth_factor=None, highlight_function=None, tooltip=None):
super(GeoJson, self).__init__(name=name, overlay=overlay,
control=control, show=show)
self._name = 'GeoJson'
self.tooltip = tooltip
if isinstance(data, dict):
self.embed = True
self.data = data
Expand All @@ -410,7 +407,6 @@ def __init__(self, data, style_function=None, name=None,
self.data = json.loads(json.dumps(data.__geo_interface__)) # noqa
else:
raise ValueError('Unhandled object {!r}.'.format(data))

self.style_function = style_function or (lambda x: {})

self.highlight = highlight_function is not None
Expand All @@ -419,6 +415,11 @@ def __init__(self, data, style_function=None, name=None,

self.smooth_factor = smooth_factor

if isinstance(tooltip, (GeoJsonTooltip, Tooltip)):
self.add_child(tooltip)
elif tooltip is not None:
self.add_child(Tooltip(tooltip))

def style_data(self):
"""
Applies `self.style_function` to each feature of `self.data` and
Expand Down Expand Up @@ -476,6 +477,9 @@ class TopoJson(Layer):
How much to simplify the polyline on each zoom level. More means
better performance and smoother look, and less means more accurate
representation. Leaflet defaults to 1.0.
tooltip: GeoJsonTooltip, Tooltip or str, default None
Display a text when hovering over the object. Can utilize the data,
see folium.GeoJsonTooltip for info on how to do that.

Examples
--------
Expand All @@ -496,29 +500,26 @@ class TopoJson(Layer):

"""
_template = Template(u"""
{% macro script(this, kwargs) %}
var {{this.get_name()}}_data = {{this.style_data()}};
var {{this.get_name()}} = L.geoJson(topojson.feature(
{{this.get_name()}}_data,
{{this.get_name()}}_data.{{this.object_path}})
{% if this.smooth_factor is not none %}
, {smoothFactor: {{this.smooth_factor}}}
{% endif %}
)
{% if this.tooltip %}.bindTooltip("{{this.tooltip.__str__()}}"){% endif %}
.addTo({{this._parent.get_name()}});
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});

{% endmacro %}
""") # noqa
{% macro script(this, kwargs) %}
var {{this.get_name()}}_data = {{this.style_data()}};
var {{this.get_name()}} = L.geoJson(topojson.feature(
{{this.get_name()}}_data,
{{this.get_name()}}_data.{{this.object_path}})
{% if this.smooth_factor is not none %}
, {smoothFactor: {{this.smooth_factor}}}
{% endif %}
).addTo({{this._parent.get_name()}});
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});
{% endmacro %}
""") # noqa

def __init__(self, data, object_path, style_function=None,
name=None, overlay=True, control=True, show=True,
smooth_factor=None, tooltip=None):
super(TopoJson, self).__init__(name=name, overlay=overlay,
control=control, show=show)
self._name = 'TopoJson'
self.tooltip = tooltip

if 'read' in dir(data):
self.embed = True
self.data = json.load(data)
Expand All @@ -538,6 +539,11 @@ def style_function(x):

self.smooth_factor = smooth_factor

if isinstance(tooltip, (GeoJsonTooltip, Tooltip)):
self.add_child(tooltip)
elif tooltip is not None:
self.add_child(Tooltip(tooltip))

def style_data(self):
"""
Applies self.style_function to each feature of self.data and returns
Expand Down Expand Up @@ -595,10 +601,127 @@ def get_bounds(self):
self.data['transform']['translate'][1] + self.data['transform']['scale'][1] * ymax, # noqa
self.data['transform']['translate'][0] + self.data['transform']['scale'][0] * xmax # noqa
]

]


class GeoJsonTooltip(Tooltip):
"""
Create a tooltip that uses data from either geojson or topojson.

Parameters
----------
fields: list or tuple.
Labels of GeoJson/TopoJson 'properties' or GeoPandas GeoDataFrame
columns you'd like to display.
aliases: list/tuple of strings, same length/order as fields, default None.
Optional aliases you'd like to display in the tooltip as field name
instead of the keys of `fields`.
labels: bool, default True.
Set to False to disable displaying the field names or aliases.
localize: bool, default False.
This will use JavaScript's .toLocaleString() to format 'clean' values
as strings for the user's location; i.e. 1,000,000.00 comma separators,
float truncation, etc.
*Available for most of JavaScript's primitive types (any data you'll
serve into the template).
style: str, default None.
HTML inline style properties like font and colors. Will be applied to
a div with the text in it.
sticky: bool, default True
Whether the tooltip should follow the mouse.
**kwargs: Assorted.
These values will map directly to the Leaflet Options. More info
available here: https://leafletjs.com/reference-1.2.0#tooltip

Examples
--------
# Provide fields and aliases, with Style.
>>> Tooltip(
>>> fields=['CNTY_NM', 'census-pop-2015', 'census-md-income-2015'],
>>> aliases=['County', '2015 Census Population', '2015 Median Income'],
>>> localize=True,
>>> style=('background-color: grey; color: white; font-family:'
>>> 'courier new; font-size: 24px; padding: 10px;')
>>> )
# Provide fields, with labels off and fixed tooltip positions.
>>> Tooltip(fields=('CNTY_NM',), labels=False, sticky=False)
"""
_template = Template(u"""
{% macro script(this, kwargs) %}
{{ this._parent.get_name() }}.bindTooltip(
function(layer){
// Convert non-primitive to String.
let handleObject = (feature)=>typeof(feature)=='object' ? JSON.stringify(feature) : feature;
let fields = {{ this.fields }};
{% if this.aliases %}
let aliases = {{ this.aliases }};
{% endif %}
return '<table{% if this.style %} style="{{this.style}}"{% endif%}>' +
String(
fields.map(
columnname=>
`<tr style="text-align: left;">{% if this.labels %}
<th style="padding: 4px; padding-right: 10px;">{% if this.aliases %}
${aliases[fields.indexOf(columnname)]
{% if this.localize %}.toLocaleString(){% endif %}}
{% else %}
${ columnname{% if this.localize %}.toLocaleString(){% endif %}}
{% endif %}</th>
{% endif %}
<td style="padding: 4px;">${handleObject(layer.feature.properties[columnname])
{% if this.localize %}.toLocaleString(){% endif %}}</td></tr>`
).join(''))
+'</table>'
}, {{ this.options }});
{% endmacro %}
""")

def __init__(self, fields, aliases=None, labels=True,
localize=False, style=None, sticky=True, **kwargs):
super(GeoJsonTooltip, self).__init__(
text='', style=style, sticky=sticky, **kwargs
)
self._name = "GeoJsonTooltip"

assert isinstance(fields, (list, tuple)), "Please pass a list or " \
"tuple to fields."
if aliases is not None:
assert isinstance(aliases, (list, tuple))
assert len(fields) == len(aliases), "fields and aliases must have" \
" the same length."
assert isinstance(labels, bool), "labels requires a boolean value."
assert isinstance(localize, bool), "localize must be bool."
assert 'permanent' not in kwargs, "The `permanent` option does not " \
"work with GeoJsonTooltip."

self.fields = fields
self.aliases = aliases
self.labels = labels
self.localize = localize
if style:
assert isinstance(style, str), \
"Pass a valid inline HTML style property string to style."
# noqa outside of type checking.
self.style = style

def render(self, **kwargs):
"""Renders the HTML representation of the element."""
if isinstance(self._parent, GeoJson):
keys = tuple(self._parent.data['features'][0]['properties'].keys())
elif isinstance(self._parent, TopoJson):
obj_name = self._parent.object_path.split('.')[-1]
keys = tuple(self._parent.data['objects'][obj_name][
'geometries'][0]['properties'].keys())
else:
raise TypeError('You cannot add a GeoJsonTooltip to anything else '
'than a GeoJson or TopoJson object.')
keys = tuple(x for x in keys if x not in ('style', 'highlight'))
for value in self.fields:
assert value in keys, ("The field {} is not available in the data. "
"Choose from: {}.".format(value, keys))
super(GeoJsonTooltip, self).render(**kwargs)


class DivIcon(MacroElement):
"""
Represents a lightweight icon for markers that uses a simple `div`
Expand Down
Loading