Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 12 additions & 2 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,8 @@ class TopoJson(JSCSSMixin, Layer):
embedded in Leaflet's JavaScript.
* If dict, then data will be converted to JSON and embedded
in the JavaScript.
* If str, then data will be passed to the JavaScript as-is.
* If str, it can be a TopoJSON string, a URL or a path to a file.
The data will be loaded and embedded in the JavaScript.

object_path: str
The path of the desired object into the TopoJson structure.
Expand Down Expand Up @@ -981,7 +982,7 @@ class TopoJson(JSCSSMixin, Layer):
--------
>>> # Providing file that shall be embedded.
>>> TopoJson(open("foo.json"), "object.myobject")
>>> # Providing filename that shall not be embedded.
>>> # Providing filename.
>>> TopoJson("foo.json", "object.myobject")
>>> # Providing dict.
>>> TopoJson(json.load(open("foo.json")), "object.myobject")
Expand Down Expand Up @@ -1047,6 +1048,15 @@ def __init__(
elif type(data) is dict:
self.embed = True
self.data = data
elif isinstance(data, str):
self.embed = True
if data.lower().startswith(("http:", "ftp:", "https:")):
self.data = requests.get(data).json()
elif data.lstrip()[:1] == "{":
self.data = json.loads(data)
else:
with open(data, "rb") as f:
self.data = json.load(f)
else:
self.embed = False
self.data = data
Expand Down
19 changes: 19 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,25 @@ def test_topojson_popup(popup):
assert f"{topojson.get_name()}.bindPopup(" in map_.get_root().render()


@pytest.mark.parametrize("as_filename", [False, True])
def test_topojson_from_str(as_filename):
"""TopoJson accepts a TopoJSON string or a filename, as documented."""
path = os.path.join(os.path.dirname(__file__), "or_counties_topo.json")
if as_filename:
data = path
else:
with open(path) as f:
data = f.read()

map_ = folium.Map()
topojson = folium.TopoJson(data, "objects.or_counties_geo").add_to(map_)
map_.get_root().render()

assert isinstance(topojson.data, dict)
assert topojson.data["type"] == "Topology"
assert topojson.get_bounds() is not None


@pytest.mark.parametrize("detail_type", [folium.GeoJsonPopup, folium.GeoJsonTooltip])
@pytest.mark.parametrize(
"properties, fields",
Expand Down