Skip to content

Improve iter_points #728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 20, 2017
Merged
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
32 changes: 4 additions & 28 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from branca.utilities import (_locations_tolist, _parse_size, image_to_url, iter_points, none_max, none_min) # noqa

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

from jinja2 import Template
Expand Down Expand Up @@ -510,37 +510,13 @@ def style_data(self):
feature.setdefault('properties', {}).setdefault('highlight', {}).update(self.highlight_function(feature)) # noqa
return json.dumps(self.data, sort_keys=True)

def get_bounds(self):
def _get_self_bounds(self):
"""
Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]]
in the form [[lat_min, lon_min], [lat_max, lon_max]].

"""
if not self.embed:
raise ValueError('Cannot compute bounds of non-embedded GeoJSON.')

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]}

bounds = [[None, None], [None, None]]
for feature in self.data['features']:
for point in iter_points(feature.get('geometry', {}).get('coordinates', {})): # noqa
bounds = [
[
none_min(bounds[0][0], point[1]),
none_min(bounds[0][1], point[0]),
],
[
none_max(bounds[1][0], point[1]),
none_max(bounds[1][1], point[0]),
],
]
return bounds

return get_bounds(self.data, lonlat=True)

class TopoJson(Layer):
"""
Expand Down
54 changes: 38 additions & 16 deletions folium/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,33 +338,53 @@ def none_max(x, y):
return max(x, y)


def iter_points(x):
"""Iterates over a list representing a feature, and returns a list of points,
whatever the shape of the array (Point, MultiPolyline, etc).
def iter_coords(obj):
"""
if isinstance(x, (list, tuple)):
if len(x):
if isinstance(x[0], (list, tuple)):
out = []
for y in x:
out += iter_points(y)
return out
else:
return [x]
Returns all the coordinate tuples from a geometry or feature.

"""
if isinstance(obj, (tuple, list)):
coords = obj
elif 'features' in obj:
coords = [geom['geometry']['coordinates'] for geom in obj['features']]
elif 'geometry' in obj:
coords = obj['geometry']['coordinates']
else:
coords = obj.get('coordinates', obj)
for coord in coords:
if isinstance(coord, (float, int)):
yield tuple(coords)
break
else:
return []
for f in iter_coords(coord):
yield f


def _locations_mirror(x):
"""
Mirrors the points in a list-of-list-of-...-of-list-of-points.
For example:
>>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]])
[[[2, 1], [4, 3]], [6, 5], [8, 7]]

"""
if hasattr(x, '__iter__'):
if hasattr(x[0], '__iter__'):
return list(map(_locations_mirror, x))
else:
return list(x[::-1])
else:
raise ValueError('List/tuple type expected. Got {!r}.'.format(x))
return x


def get_bounds(locations):
def get_bounds(locations, lonlat=False):
"""
Computes the bounds of the object in the form
[[lat_min, lon_min], [lat_max, lon_max]]

"""
bounds = [[None, None], [None, None]]
for point in iter_points(locations):
for point in iter_coords(locations):
bounds = [
[
none_min(bounds[0][0], point[0]),
Expand All @@ -375,4 +395,6 @@ def get_bounds(locations):
none_max(bounds[1][1], point[1]),
],
]
if lonlat:
bounds = _locations_mirror(bounds)
return bounds