From 188f597f614c06db6d0ed240a6cf9451f59b6cae Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sun, 20 Jan 2019 22:13:54 +0100 Subject: [PATCH 01/11] GeoJson: split off style data from geojson --- folium/features.py | 97 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 25 deletions(-) diff --git a/folium/features.py b/folium/features.py index 4d54e7e700..7d467d803f 100644 --- a/folium/features.py +++ b/folium/features.py @@ -9,6 +9,8 @@ import json import warnings +import functools +import operator from branca.colormap import LinearColormap, StepColormap from branca.element import (Element, Figure, JavascriptLink, MacroElement) @@ -393,17 +395,37 @@ class GeoJson(Layer): """ _template = Template(u""" {% macro script(this, kwargs) %} + let {{ this.get_name() }}_style_function = function (feature) { + switch({{ this.feature_identifier }}) { + {%- for style, ids_list in this.style_map.items() if not style == 'default' %} + {% for id_val in ids_list %}case "{{ id_val }}": {% endfor %} + return {{ style }}; + {%- endfor %} + default: + return {{ this.style_map['default'] }}; + } + } {%- 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_map.get_name() }}.fitBounds(e.target.getBounds());} - }); - }; + let {{ this.get_name() }}_highlight_function = function (feature) { + switch({{ this.feature_identifier }}) { + {%- for style, ids_list in this.highlight_map.items() if not style == 'default' %} + {% for id_val in ids_list %}case "{{ id_val }}": {% endfor %} + return {{ style }}; + {%- endfor %} + default: + return {{ this.highlight_map['default'] }}; + } + } + {{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) { + layer.on({ + mouseout: function(e) { + e.target.setStyle({{ this.get_name() }}_style_function(e.target.feature));}, + mouseover: function(e) { + e.target.setStyle({{ this.get_name() }}_highlight_function(e.target.feature));}, + click: function(e) { + {{ this.parent_map.get_name() }}.fitBounds(e.target.getBounds());} + }); + }; {%- endif %} var {{this.get_name()}} = L.geoJson( {{ this.json }}, @@ -416,7 +438,7 @@ class GeoJson(Layer): {%- endif %} } ).addTo({{ this._parent.get_name()}} ); - {{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;}); + {{ this.get_name() }}.setStyle({{ this.get_name() }}_style_function); {% endmacro %} """) # noqa @@ -446,13 +468,17 @@ def __init__(self, data, style_function=None, name=None, else: raise ValueError('Cannot render objects with any missing geometries. {!r}'.format(data)) - self.style_function = style_function or (lambda x: {}) + self.convert_to_feature_collection() + self.style_function = style_function or (lambda x: {}) self.highlight = highlight_function is not None self.highlight_function = highlight_function or (lambda x: {}) - self.smooth_factor = smooth_factor + self.feature_identifier = self.find_identifier(self.data['features'][0]) + self.style_map = {} + self.highlight_map = {} + self._validate_function(self.style_function, 'style_function') self._validate_function(self.highlight_function, 'highlight_function') @@ -464,6 +490,15 @@ def __init__(self, data, style_function=None, name=None, self.parent_map = None self.json = None + def convert_to_feature_collection(self): + """Convert data into a FeatureCollection if it is not already.""" + if 'features' not in self.data.keys(): + # Catch case when GeoJSON is just a single Feature or a geometry. + if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa + # Catch case when GeoJSON is just a geometry. + self.data = {'type': 'Feature', 'geometry': self.data} + self.data = {'type': 'FeatureCollection', 'features': [self.data]} + def _validate_function(self, func, name): """ Tests `self.style_function` and `self.highlight_function` to ensure @@ -476,20 +511,25 @@ def _validate_function(self, func, name): 'data[\'features\'] and returns a dictionary.' .format(name)) + def find_identifier(self, feature): + if 'id' in feature: + return 'feature.id' + elif 'properties' in feature and 'name' in feature['properties']: + return 'feature.properties.name' + else: + raise ValueError( + 'Could not determine a unique identifier for each feature.') + def style_data(self): """ Applies `self.style_function` to each feature of `self.data` and returns a corresponding JSON output. """ - if 'features' not in self.data.keys(): - # Catch case when GeoJSON is just a single Feature or a geometry. - if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa - # Catch case when GeoJSON is just a geometry. - self.data = {'type': 'Feature', 'geometry': self.data} - self.data = {'type': 'FeatureCollection', 'features': [self.data]} - for feature in self.data['features']: + name = functools.reduce(operator.getitem, + self.feature_identifier.split('.')[1:], + feature) feature_style = self.style_function(feature) for key, value in feature_style.items(): if isinstance(value, MacroElement): @@ -499,11 +539,18 @@ def style_data(self): value.render() # Replace objects with their Javascript var names: feature_style[key] = "{{'" + value.get_name() + "'}}" - - feature.setdefault('properties', {}).setdefault('style', {}) \ - .update(feature_style) - feature.setdefault('properties', {}).setdefault('highlight', {}) \ - .update(self.highlight_function(feature)) + key = json.dumps(feature_style, sort_keys=True) + self.style_map.setdefault(key, []).append(name) + + feature_highlight = self.highlight_function(feature) + key = json.dumps(feature_highlight, sort_keys=True) + self.highlight_map.setdefault(key, []).append(name) + + for mapping in (self.style_map, self.highlight_map): + key_longest = sorted([(len(v), k) for k, v in mapping.items()], + reverse=True)[0][1] + mapping['default'] = key_longest + del(mapping[key_longest]) data_json = json.dumps(self.data, sort_keys=True) # Remove quotes around Jinja2 template expressions: From 2e1d0a4010c03f4fc2ec9842d8b3970fe5f589b8 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sun, 20 Jan 2019 23:09:55 +0100 Subject: [PATCH 02/11] GeoJson: allow non-embbed urls and files --- folium/features.py | 47 +++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/folium/features.py b/folium/features.py index 7d467d803f..bff0d7f11b 100644 --- a/folium/features.py +++ b/folium/features.py @@ -427,8 +427,17 @@ class GeoJson(Layer): }); }; {%- endif %} - var {{this.get_name()}} = L.geoJson( - {{ this.json }}, + {%- if this.embed %} + let {{ this.get_name() }}_data = {{ this.json }}; + {%- else %} + let {{ this.get_name() }}_data; + $.ajax({url: "{{ this.embed_link }}", dataType: 'json', async: false, + success: function(data) { + {{ this.get_name() }}_data = data; + }}); + {%- endif %} + var {{ this.get_name() }} = L.geoJson( + {{ this.get_name() }}_data, { {%- if this.smooth_factor is not none %} smoothFactor: {{ this.smooth_factor }}, @@ -436,30 +445,38 @@ class GeoJson(Layer): {%- if this.highlight %} onEachFeature: {{ this.get_name() }}_onEachFeature, {%- endif %} + style: {{ this.get_name() }}_style_function, } ).addTo({{ this._parent.get_name()}} ); - {{ this.get_name() }}.setStyle({{ this.get_name() }}_style_function); {% 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): + smooth_factor=None, highlight_function=None, tooltip=None, + embed=True): super(GeoJson, self).__init__(name=name, overlay=overlay, control=control, show=show) self._name = 'GeoJson' + self.embed = embed + self.embed_link = None + self.json = None if isinstance(data, dict): self.embed = True self.data = data elif isinstance(data, text_type) or isinstance(data, binary_type): - self.embed = True if data.lower().startswith(('http:', 'ftp:', 'https:')): self.data = requests.get(data).json() + if not self.embed: + self.embed_link = data elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string + self.embed = True self.data = json.loads(data) else: # This is a filename with open(data) as f: self.data = json.loads(f.read()) + if not self.embed: + self.embed_link = data elif hasattr(data, '__geo_interface__'): self.embed = True if hasattr(data, 'to_crs'): @@ -488,7 +505,6 @@ def __init__(self, data, style_function=None, name=None, self.add_child(Tooltip(tooltip)) self.parent_map = None - self.json = None def convert_to_feature_collection(self): """Convert data into a FeatureCollection if it is not already.""" @@ -498,6 +514,8 @@ def convert_to_feature_collection(self): # Catch case when GeoJSON is just a geometry. self.data = {'type': 'Feature', 'geometry': self.data} self.data = {'type': 'FeatureCollection', 'features': [self.data]} + if not self.embed: + raise ValueError('Data is not a FeatureCollection.') def _validate_function(self, func, name): """ @@ -526,6 +544,9 @@ def style_data(self): returns a corresponding JSON output. """ + def to_key(d): + return json.dumps(d, sort_keys=True).replace('"{{', '{{').replace('}}"', '}}') + for feature in self.data['features']: name = functools.reduce(operator.getitem, self.feature_identifier.split('.')[1:], @@ -539,12 +560,10 @@ def style_data(self): value.render() # Replace objects with their Javascript var names: feature_style[key] = "{{'" + value.get_name() + "'}}" - key = json.dumps(feature_style, sort_keys=True) - self.style_map.setdefault(key, []).append(name) + self.style_map.setdefault(to_key(feature_style), []).append(name) feature_highlight = self.highlight_function(feature) - key = json.dumps(feature_highlight, sort_keys=True) - self.highlight_map.setdefault(key, []).append(name) + self.highlight_map.setdefault(to_key(feature_highlight), []).append(name) for mapping in (self.style_map, self.highlight_map): key_longest = sorted([(len(v), k) for k, v in mapping.items()], @@ -552,10 +571,6 @@ def style_data(self): mapping['default'] = key_longest del(mapping[key_longest]) - data_json = json.dumps(self.data, sort_keys=True) - # Remove quotes around Jinja2 template expressions: - return data_json.replace('"{{', '{{').replace('}}"', '}}') - def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) @@ -566,7 +581,9 @@ def _get_self_bounds(self): def render(self, **kwargs): self.parent_map = get_obj_in_upper_tree(self, Map) - self.json = self.style_data() if self.embed else json.dumps(self.data) + self.style_data() + if self.embed: + self.json = json.dumps(self.data, sort_keys=True) super(GeoJson, self).render() From e183bc8c602332cb0456e6f9d581f3adef2213e9 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Mon, 21 Jan 2019 23:42:40 +0100 Subject: [PATCH 03/11] GeoJson: refactoring --- folium/features.py | 246 +++++++++++++++++++++++++++------------------ 1 file changed, 148 insertions(+), 98 deletions(-) diff --git a/folium/features.py b/folium/features.py index bff0d7f11b..248430ac8e 100644 --- a/folium/features.py +++ b/folium/features.py @@ -374,13 +374,16 @@ class GeoJson(Layer): 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. + embed: bool, default True + Whether to embed the data in the html file or not. Note that disabling + embedding is only supported if you provide a file link or URL. Examples -------- - >>> # Providing file that shall be embedded. - >>> GeoJson(open('foo.json')) - >>> # Providing filename that shall not be embedded. + >>> # Providing filename that shall be embedded. >>> GeoJson('foo.json') + >>> # Providing filename that shall not be embedded. + >>> GeoJson('foo.json', embed=False) >>> # Providing dict. >>> GeoJson(json.load(open('foo.json'))) >>> # Providing string. @@ -395,7 +398,8 @@ class GeoJson(Layer): """ _template = Template(u""" {% macro script(this, kwargs) %} - let {{ this.get_name() }}_style_function = function (feature) { + {%- if this.style %} + function {{ this.get_name() }}_styler(feature) { switch({{ this.feature_identifier }}) { {%- for style, ids_list in this.style_map.items() if not style == 'default' %} {% for id_val in ids_list %}case "{{ id_val }}": {% endfor %} @@ -405,8 +409,9 @@ class GeoJson(Layer): return {{ this.style_map['default'] }}; } } + {%- endif %} {%- if this.highlight %} - let {{ this.get_name() }}_highlight_function = function (feature) { + function {{ this.get_name() }}_highlighter(feature) { switch({{ this.feature_identifier }}) { {%- for style, ids_list in this.highlight_map.items() if not style == 'default' %} {% for id_val in ids_list %}case "{{ id_val }}": {% endfor %} @@ -416,51 +421,53 @@ class GeoJson(Layer): return {{ this.highlight_map['default'] }}; } } - {{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) { + {%- endif %} + function {{this.get_name()}}_onEachFeature(feature, layer) { layer.on({ + {%- if this.highlight %} mouseout: function(e) { - e.target.setStyle({{ this.get_name() }}_style_function(e.target.feature));}, + {{ this.get_name() }}.resetStyle(e.target); + }, mouseover: function(e) { - e.target.setStyle({{ this.get_name() }}_highlight_function(e.target.feature));}, + e.target.setStyle({{ this.get_name() }}_highlighter(e.target.feature)); + }, + {%- endif %} click: function(e) { - {{ this.parent_map.get_name() }}.fitBounds(e.target.getBounds());} + {{ this.parent_map.get_name() }}.fitBounds(e.target.getBounds()); + } }); }; - {%- endif %} - {%- if this.embed %} - let {{ this.get_name() }}_data = {{ this.json }}; - {%- else %} - let {{ this.get_name() }}_data; - $.ajax({url: "{{ this.embed_link }}", dataType: 'json', async: false, - success: function(data) { - {{ this.get_name() }}_data = data; - }}); - {%- endif %} - var {{ this.get_name() }} = L.geoJson( - {{ this.get_name() }}_data, - { + var {{ this.get_name() }} = L.geoJson(null, { {%- if this.smooth_factor is not none %} smoothFactor: {{ this.smooth_factor }}, {%- endif %} - {%- if this.highlight %} onEachFeature: {{ this.get_name() }}_onEachFeature, + {% if this.style %} + style: {{ this.get_name() }}_styler, {%- endif %} - style: {{ this.get_name() }}_style_function, - } - ).addTo({{ this._parent.get_name()}} ); + }).addTo({{ this._parent.get_name() }}); + {%- if this.embed %} + {{ this.get_name() }}.addData({{ this.json }}); + {%- else %} + $.ajax({url: "{{ this.embed_link }}", dataType: 'json', async: true, + success: function(data) { + {{ this.get_name() }}.addData(data); + }}); + {%- endif %} {% 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, - embed=True): + def __init__(self, data, style_function=None, highlight_function=None, + name=None, overlay=True, control=True, show=True, + smooth_factor=None, tooltip=None, embed=True): super(GeoJson, self).__init__(name=name, overlay=overlay, control=control, show=show) self._name = 'GeoJson' self.embed = embed self.embed_link = None self.json = None + self.parent_map = None + if isinstance(data, dict): self.embed = True self.data = data @@ -483,94 +490,75 @@ def __init__(self, data, style_function=None, name=None, data = data.to_crs(epsg='4326') self.data = json.loads(json.dumps(data.__geo_interface__)) # noqa else: - raise ValueError('Cannot render objects with any missing geometries. {!r}'.format(data)) - - self.convert_to_feature_collection() + raise ValueError('Cannot render objects with any missing geometries' + ': {!r}'.format(data)) - self.style_function = style_function or (lambda x: {}) - self.highlight = highlight_function is not None - self.highlight_function = highlight_function or (lambda x: {}) self.smooth_factor = smooth_factor - - self.feature_identifier = self.find_identifier(self.data['features'][0]) - self.style_map = {} - self.highlight_map = {} - - self._validate_function(self.style_function, 'style_function') - self._validate_function(self.highlight_function, 'highlight_function') + self.style = style_function is not None + self.highlight = highlight_function is not None + if self.style or self.highlight: + self.convert_to_feature_collection() + self.feature_identifier = self.find_identifier() + if self.style: + self._validate_function(style_function, 'style_function') + self.style_function = style_function + self.style_map = {} + if self.highlight: + self._validate_function(highlight_function, 'highlight_function') + self.highlight_function = highlight_function + self.highlight_map = {} if isinstance(tooltip, (GeoJsonTooltip, Tooltip)): self.add_child(tooltip) elif tooltip is not None: self.add_child(Tooltip(tooltip)) - self.parent_map = None - def convert_to_feature_collection(self): """Convert data into a FeatureCollection if it is not already.""" - if 'features' not in self.data.keys(): - # Catch case when GeoJSON is just a single Feature or a geometry. - if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa - # Catch case when GeoJSON is just a geometry. - self.data = {'type': 'Feature', 'geometry': self.data} - self.data = {'type': 'FeatureCollection', 'features': [self.data]} - if not self.embed: - raise ValueError('Data is not a FeatureCollection.') + if self.data['type'] == 'FeatureCollection': + return + if not self.embed: + raise ValueError('Data is not a FeatureCollection, but it should be' + ' to apply style or highlight. Because `embed=' + 'False` it cannot be converted into one.\n' + 'Either set `embed=True` or disable styling.') + # Catch case when GeoJSON is just a single Feature or a geometry. + if 'geometry' not in self.data.keys(): + # Catch case when GeoJSON is just a geometry. + self.data = {'type': 'Feature', 'geometry': self.data} + self.data = {'type': 'FeatureCollection', 'features': [self.data]} + + def find_identifier(self): + """Find a unique identifier for each feature, create it if needed.""" + features = self.data['features'] + n = len(features) + feature = features[0] + if 'id' in feature and len(set(feat['id'] for feat in features)) == n: + return 'feature.id' + for key in feature.get('properties', []): + if len(set(feat['properties'][key] for feat in features)) == n: + return 'feature.properties.{}'.format(key) + if self.embed: + for i, feature in enumerate(self.data['features']): + feature['id'] = str(i) + return 'feature.id' + raise ValueError( + 'There is no unique identifier for each feature and because ' + '`embed=False` it cannot be added. Consider adding an `id` ' + 'field or set `embed=True`. ' + ) def _validate_function(self, func, name): """ Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries. """ - test_feature = self.data if self.data.get('features') is None \ - else self.data['features'][0] + test_feature = self.data['features'][0] if not callable(func) or not isinstance(func(test_feature), dict): raise ValueError('{} should be a function that accepts items from ' 'data[\'features\'] and returns a dictionary.' .format(name)) - def find_identifier(self, feature): - if 'id' in feature: - return 'feature.id' - elif 'properties' in feature and 'name' in feature['properties']: - return 'feature.properties.name' - else: - raise ValueError( - 'Could not determine a unique identifier for each feature.') - - def style_data(self): - """ - Applies `self.style_function` to each feature of `self.data` and - returns a corresponding JSON output. - - """ - def to_key(d): - return json.dumps(d, sort_keys=True).replace('"{{', '{{').replace('}}"', '}}') - - for feature in self.data['features']: - name = functools.reduce(operator.getitem, - self.feature_identifier.split('.')[1:], - feature) - feature_style = self.style_function(feature) - for key, value in feature_style.items(): - if isinstance(value, MacroElement): - # Make sure objects are rendered: - if value._parent is None: - value._parent = self - value.render() - # Replace objects with their Javascript var names: - feature_style[key] = "{{'" + value.get_name() + "'}}" - self.style_map.setdefault(to_key(feature_style), []).append(name) - - feature_highlight = self.highlight_function(feature) - self.highlight_map.setdefault(to_key(feature_highlight), []).append(name) - - for mapping in (self.style_map, self.highlight_map): - key_longest = sorted([(len(v), k) for k, v in mapping.items()], - reverse=True)[0][1] - mapping['default'] = key_longest - del(mapping[key_longest]) - def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) @@ -581,12 +569,74 @@ def _get_self_bounds(self): def render(self, **kwargs): self.parent_map = get_obj_in_upper_tree(self, Map) - self.style_data() + if self.style or self.highlight: + mapper = GeoJsonMapper(self.data, self.feature_identifier) + if self.style: + self.style_map = mapper.get_style_map(self.style_function) + if self.highlight: + self.highlight_map = mapper.get_highlight_map(self.highlight_function) # noqa if self.embed: self.json = json.dumps(self.data, sort_keys=True) super(GeoJson, self).render() +class GeoJsonMapper: + """Create dicts that map styling to GeoJson features. + + Used in the GeoJson class. Users don't have to call this class directly. + """ + + def __init__(self, data, feature_identifier): + self.data = data + self.feature_identifier = feature_identifier + + def get_style_map(self, style_function): + """Return a dict that maps style parameters to features.""" + return self._create_mapping(style_function, 'style') + + def get_highlight_map(self, highlight_function): + """Return a dict that maps highlight parameters to features.""" + return self._create_mapping(highlight_function, 'highlight') + + def _create_mapping(self, func, switch): + """Internal function to create the mapping.""" + mapping = {} + for feature in self.data['features']: + content = func(feature) + if switch == 'style': + for key, value in content.items(): + if isinstance(value, MacroElement): + # Make sure objects are rendered: + if value._parent is None: + value._parent = self + value.render() + # Replace objects with their Javascript var names: + content[key] = "{{'" + value.get_name() + "'}}" + key = self._to_key(content) + mapping.setdefault(key, []).append(self.get_feature_id(feature)) + self._set_default_key(mapping) + return mapping + + def get_feature_id(self, feature): + """Return a value identifying the feature.""" + fields = self.feature_identifier.split('.')[1:] + return functools.reduce(operator.getitem, fields, feature) + + @staticmethod + def _to_key(d): + """Convert dict to str and enable Jinja2 template syntax.""" + as_str = json.dumps(d, sort_keys=True) + return as_str.replace('"{{', '{{').replace('}}"', '}}') + + @staticmethod + def _set_default_key(mapping): + """Replace the field with the most features with a 'default' field.""" + key_longest = sorted([(len(v), k) for k, v in mapping.items()], + reverse=True)[0][1] + mapping['default'] = key_longest + del (mapping[key_longest]) + + class TopoJson(Layer): """ Creates a TopoJson object for plotting into a Map. From d8ce22eac3057354969167ec84c5a1033d7c78e0 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Mon, 21 Jan 2019 23:53:46 +0100 Subject: [PATCH 04/11] Some fixes --- folium/features.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/folium/features.py b/folium/features.py index 248430ac8e..07094e7976 100644 --- a/folium/features.py +++ b/folium/features.py @@ -467,35 +467,37 @@ def __init__(self, data, style_function=None, highlight_function=None, self.embed_link = None self.json = None self.parent_map = None + self.smooth_factor = smooth_factor + self.style = style_function is not None + self.highlight = highlight_function is not None if isinstance(data, dict): self.embed = True self.data = data elif isinstance(data, text_type) or isinstance(data, binary_type): if data.lower().startswith(('http:', 'ftp:', 'https:')): - self.data = requests.get(data).json() + if self.embed or self.style or self.highlight: + self.data = requests.get(data).json() if not self.embed: self.embed_link = data elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string self.embed = True self.data = json.loads(data) else: # This is a filename - with open(data) as f: - self.data = json.loads(f.read()) + if self.embed or self.style or self.highlight: + with open(data) as f: + self.data = json.loads(f.read()) if not self.embed: self.embed_link = data elif hasattr(data, '__geo_interface__'): self.embed = True if hasattr(data, 'to_crs'): data = data.to_crs(epsg='4326') - self.data = json.loads(json.dumps(data.__geo_interface__)) # noqa + self.data = json.loads(json.dumps(data.__geo_interface__)) else: raise ValueError('Cannot render objects with any missing geometries' ': {!r}'.format(data)) - self.smooth_factor = smooth_factor - self.style = style_function is not None - self.highlight = highlight_function is not None if self.style or self.highlight: self.convert_to_feature_collection() self.feature_identifier = self.find_identifier() @@ -570,7 +572,8 @@ def _get_self_bounds(self): def render(self, **kwargs): self.parent_map = get_obj_in_upper_tree(self, Map) if self.style or self.highlight: - mapper = GeoJsonMapper(self.data, self.feature_identifier) + mapper = GeoJsonMapper(self.data, self.feature_identifier, + self) if self.style: self.style_map = mapper.get_style_map(self.style_function) if self.highlight: @@ -586,9 +589,10 @@ class GeoJsonMapper: Used in the GeoJson class. Users don't have to call this class directly. """ - def __init__(self, data, feature_identifier): + def __init__(self, data, feature_identifier, geojson_obj): self.data = data self.feature_identifier = feature_identifier + self.geojson_obj = geojson_obj def get_style_map(self, style_function): """Return a dict that maps style parameters to features.""" @@ -608,7 +612,7 @@ def _create_mapping(self, func, switch): if isinstance(value, MacroElement): # Make sure objects are rendered: if value._parent is None: - value._parent = self + value._parent = self.geojson_obj value.render() # Replace objects with their Javascript var names: content[key] = "{{'" + value.get_name() + "'}}" From b153d80c5a6d10c817cfde35aef15f1890f056b4 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Mon, 21 Jan 2019 23:59:27 +0100 Subject: [PATCH 05/11] Minor changes --- folium/features.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/folium/features.py b/folium/features.py index 07094e7976..5661e95a36 100644 --- a/folium/features.py +++ b/folium/features.py @@ -500,7 +500,6 @@ def __init__(self, data, style_function=None, highlight_function=None, if self.style or self.highlight: self.convert_to_feature_collection() - self.feature_identifier = self.find_identifier() if self.style: self._validate_function(style_function, 'style_function') self.style_function = style_function @@ -530,6 +529,17 @@ def convert_to_feature_collection(self): self.data = {'type': 'Feature', 'geometry': self.data} self.data = {'type': 'FeatureCollection', 'features': [self.data]} + def _validate_function(self, func, name): + """ + Tests `self.style_function` and `self.highlight_function` to ensure + they are functions returning dictionaries. + """ + test_feature = self.data['features'][0] + if not callable(func) or not isinstance(func(test_feature), dict): + raise ValueError('{} should be a function that accepts items from ' + 'data[\'features\'] and returns a dictionary.' + .format(name)) + def find_identifier(self): """Find a unique identifier for each feature, create it if needed.""" features = self.data['features'] @@ -550,17 +560,6 @@ def find_identifier(self): 'field or set `embed=True`. ' ) - def _validate_function(self, func, name): - """ - Tests `self.style_function` and `self.highlight_function` to ensure - they are functions returning dictionaries. - """ - test_feature = self.data['features'][0] - if not callable(func) or not isinstance(func(test_feature), dict): - raise ValueError('{} should be a function that accepts items from ' - 'data[\'features\'] and returns a dictionary.' - .format(name)) - def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) @@ -572,18 +571,19 @@ def _get_self_bounds(self): def render(self, **kwargs): self.parent_map = get_obj_in_upper_tree(self, Map) if self.style or self.highlight: - mapper = GeoJsonMapper(self.data, self.feature_identifier, - self) + mapper = GeoJsonStyleMapper(self.data, self.find_identifier(), + self) if self.style: self.style_map = mapper.get_style_map(self.style_function) if self.highlight: - self.highlight_map = mapper.get_highlight_map(self.highlight_function) # noqa + self.highlight_map = mapper.get_highlight_map( + self.highlight_function) if self.embed: self.json = json.dumps(self.data, sort_keys=True) super(GeoJson, self).render() -class GeoJsonMapper: +class GeoJsonStyleMapper: """Create dicts that map styling to GeoJson features. Used in the GeoJson class. Users don't have to call this class directly. From e8e9f8b3a0bf187aca02d64ecbf8b3d4e5bee516 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Tue, 22 Jan 2019 00:23:45 +0100 Subject: [PATCH 06/11] Fix linter --- folium/features.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/folium/features.py b/folium/features.py index 5661e95a36..ebca1d97bf 100644 --- a/folium/features.py +++ b/folium/features.py @@ -457,7 +457,7 @@ class GeoJson(Layer): {% endmacro %} """) # noqa - def __init__(self, data, style_function=None, highlight_function=None, + def __init__(self, data, style_function=None, highlight_function=None, # noqa name=None, overlay=True, control=True, show=True, smooth_factor=None, tooltip=None, embed=True): super(GeoJson, self).__init__(name=name, overlay=overlay, From a2664250f0e4fedac9a48c0a9b312eea4da718a4 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sun, 24 Feb 2019 19:27:21 +0100 Subject: [PATCH 07/11] Fix missing feature_identifier attr --- folium/features.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/folium/features.py b/folium/features.py index ebca1d97bf..dc10f7cee6 100644 --- a/folium/features.py +++ b/folium/features.py @@ -508,6 +508,7 @@ def __init__(self, data, style_function=None, highlight_function=None, # noqa self._validate_function(highlight_function, 'highlight_function') self.highlight_function = highlight_function self.highlight_map = {} + self.feature_identifier = self.find_identifier() if isinstance(tooltip, (GeoJsonTooltip, Tooltip)): self.add_child(tooltip) @@ -571,7 +572,7 @@ def _get_self_bounds(self): def render(self, **kwargs): self.parent_map = get_obj_in_upper_tree(self, Map) if self.style or self.highlight: - mapper = GeoJsonStyleMapper(self.data, self.find_identifier(), + mapper = GeoJsonStyleMapper(self.data, self.feature_identifier, self) if self.style: self.style_map = mapper.get_style_map(self.style_function) From c6e9407b941482b47b1bdebe706b3cdcd5e4410d Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sun, 24 Feb 2019 19:35:27 +0100 Subject: [PATCH 08/11] Set `self.data` even when not embedding it. --- folium/features.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/folium/features.py b/folium/features.py index dc10f7cee6..b03a17ea3f 100644 --- a/folium/features.py +++ b/folium/features.py @@ -476,17 +476,15 @@ def __init__(self, data, style_function=None, highlight_function=None, # noqa self.data = data elif isinstance(data, text_type) or isinstance(data, binary_type): if data.lower().startswith(('http:', 'ftp:', 'https:')): - if self.embed or self.style or self.highlight: - self.data = requests.get(data).json() + self.data = requests.get(data).json() if not self.embed: self.embed_link = data elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string self.embed = True self.data = json.loads(data) else: # This is a filename - if self.embed or self.style or self.highlight: - with open(data) as f: - self.data = json.loads(f.read()) + with open(data) as f: + self.data = json.loads(f.read()) if not self.embed: self.embed_link = data elif hasattr(data, '__geo_interface__'): From 9fb349e83000bd7bed881da8b548ab2758dd79df Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sun, 24 Feb 2019 19:37:32 +0100 Subject: [PATCH 09/11] Small changes to error messages. --- folium/features.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/folium/features.py b/folium/features.py index b03a17ea3f..1363f7df40 100644 --- a/folium/features.py +++ b/folium/features.py @@ -518,10 +518,11 @@ def convert_to_feature_collection(self): if self.data['type'] == 'FeatureCollection': return if not self.embed: - raise ValueError('Data is not a FeatureCollection, but it should be' - ' to apply style or highlight. Because `embed=' - 'False` it cannot be converted into one.\n' - 'Either set `embed=True` or disable styling.') + raise ValueError( + 'Data is not a FeatureCollection, but it should be to apply ' + 'style or highlight. Because `embed=False` it cannot be ' + 'converted into one.\nEither change your geojson data to a ' + 'FeatureCollection, set `embed=True` or disable styling.') # Catch case when GeoJSON is just a single Feature or a geometry. if 'geometry' not in self.data.keys(): # Catch case when GeoJSON is just a geometry. @@ -556,7 +557,7 @@ def find_identifier(self): raise ValueError( 'There is no unique identifier for each feature and because ' '`embed=False` it cannot be added. Consider adding an `id` ' - 'field or set `embed=True`. ' + 'field to your geojson data or set `embed=True`. ' ) def _get_self_bounds(self): From 8d921a5f8b8b49d3959b7dd4978f5df5dea17b22 Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sat, 9 Mar 2019 14:28:37 +0100 Subject: [PATCH 10/11] Move GeoJson data conversion to method --- folium/features.py | 50 +++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/folium/features.py b/folium/features.py index 1363f7df40..434e126d6e 100644 --- a/folium/features.py +++ b/folium/features.py @@ -471,48 +471,52 @@ def __init__(self, data, style_function=None, highlight_function=None, # noqa self.style = style_function is not None self.highlight = highlight_function is not None + self.data = self.process_data(data) + + if self.style or self.highlight: + self.convert_to_feature_collection() + if self.style: + self._validate_function(style_function, 'style_function') + self.style_function = style_function + self.style_map = {} + if self.highlight: + self._validate_function(highlight_function, 'highlight_function') + self.highlight_function = highlight_function + self.highlight_map = {} + self.feature_identifier = self.find_identifier() + + if isinstance(tooltip, (GeoJsonTooltip, Tooltip)): + self.add_child(tooltip) + elif tooltip is not None: + self.add_child(Tooltip(tooltip)) + + def process_data(self, data): + """Convert an unknown data input into a geojson dictionary.""" if isinstance(data, dict): self.embed = True - self.data = data + return data elif isinstance(data, text_type) or isinstance(data, binary_type): if data.lower().startswith(('http:', 'ftp:', 'https:')): - self.data = requests.get(data).json() if not self.embed: self.embed_link = data + return requests.get(data).json() elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string self.embed = True - self.data = json.loads(data) + return json.loads(data) else: # This is a filename - with open(data) as f: - self.data = json.loads(f.read()) if not self.embed: self.embed_link = data + with open(data) as f: + return json.loads(f.read()) elif hasattr(data, '__geo_interface__'): self.embed = True if hasattr(data, 'to_crs'): data = data.to_crs(epsg='4326') - self.data = json.loads(json.dumps(data.__geo_interface__)) + return json.loads(json.dumps(data.__geo_interface__)) else: raise ValueError('Cannot render objects with any missing geometries' ': {!r}'.format(data)) - if self.style or self.highlight: - self.convert_to_feature_collection() - if self.style: - self._validate_function(style_function, 'style_function') - self.style_function = style_function - self.style_map = {} - if self.highlight: - self._validate_function(highlight_function, 'highlight_function') - self.highlight_function = highlight_function - self.highlight_map = {} - self.feature_identifier = self.find_identifier() - - if isinstance(tooltip, (GeoJsonTooltip, Tooltip)): - self.add_child(tooltip) - elif tooltip is not None: - self.add_child(Tooltip(tooltip)) - def convert_to_feature_collection(self): """Convert data into a FeatureCollection if it is not already.""" if self.data['type'] == 'FeatureCollection': From 1907c3fe6e255a6616b44e26183ae07718a8547c Mon Sep 17 00:00:00 2001 From: Frank <33519926+Conengmo@users.noreply.github.com> Date: Sat, 9 Mar 2019 14:28:56 +0100 Subject: [PATCH 11/11] Fix TimeSliderChoropleth plugin --- folium/plugins/time_slider_choropleth.py | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/folium/plugins/time_slider_choropleth.py b/folium/plugins/time_slider_choropleth.py index 776e592dbd..bdd0f4d01e 100644 --- a/folium/plugins/time_slider_choropleth.py +++ b/folium/plugins/time_slider_choropleth.py @@ -7,11 +7,12 @@ from branca.element import Figure, JavascriptLink from folium.features import GeoJson +from folium.map import Layer from jinja2 import Template -class TimeSliderChoropleth(GeoJson): +class TimeSliderChoropleth(Layer): """ Creates a TimeSliderChoropleth plugin to append into a map with Map.add_child. @@ -106,21 +107,7 @@ class TimeSliderChoropleth(GeoJson): {% 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 %} - } - {% endif %} + {{this.data}} ).addTo({{this._parent.get_name()}} ); @@ -142,9 +129,10 @@ class TimeSliderChoropleth(GeoJson): def __init__(self, data, styledict, name=None, overlay=True, control=True, show=True): - super(TimeSliderChoropleth, self).__init__(data, name=name, - overlay=overlay, + super(TimeSliderChoropleth, self).__init__(name=name, overlay=overlay, control=control, show=show) + self.data = json.dumps(GeoJson.process_data(GeoJson({}), data)) + if not isinstance(styledict, dict): raise ValueError('styledict must be a dictionary, got {!r}'.format(styledict)) # noqa for val in styledict.values():