Last active
August 8, 2017 11:31
-
-
Save deeplook/1758c1ad82f0e288eb78ab1cd5d697b4 to your computer and use it in GitHub Desktop.
A little tool to render GeoJSON files as layers in an HTML output map file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| A little tool to render GeoJSON files as layers in an HTML output map file. | |
| The output map shows the region covered by the combined bounding box of all | |
| GeoJSON input files. This was tested only with Python 3.5, but should also | |
| work on Python >= 2.7. | |
| The pygeoj package does calculate the bounding box correctly only for version | |
| >= 0.2.5. Any existing bbox attributes inside a GeoJSON file are ignored. | |
| No kind of styling is applied to the GeoJSON features here, yet. | |
| Example: | |
| python mapit.py > map12.html | |
| python mapit.py 1.geojson 2.geojson > map12.html | |
| """ | |
| import os | |
| import sys | |
| import folium # pip install folium | |
| import pygeoj # pip install pygeoj>=0.2.5 | |
| __author__ = "Dinu Gherman" | |
| __date__ = "2017-07-07" | |
| __license__ = "GPL3" | |
| __version__ = "0.3" | |
| def combine_bboxes(bboxes): | |
| """ | |
| Return a combined bounding box from a list of individual ones. | |
| """ | |
| λ0r, φ0r, λ1r, φ1r = bboxes[0] | |
| for bbox in bboxes[1:]: | |
| λ0, φ0, λ1, φ1 = bbox | |
| if λ0 < λ0r: λ0r = λ0 | |
| if φ0 < φ0r: φ0r = φ0 | |
| if λ1 > λ1r: λ1r = λ1 | |
| if φ0 > φ1r: φ0r = φ1 | |
| return (λ0r, φ0r, λ1r, φ1r) | |
| def main(geo_paths): | |
| """ | |
| Render one or more GeoJSON files as seperate layers in an HTML output map. | |
| """ | |
| map = folium.Map(tiles="OpenStreetMap") # "Stamen Toner", ... | |
| for geo_path in geo_paths: | |
| name = os.path.basename(geo_path) | |
| folium.GeoJson(open(geo_path), name=name).add_to(map) | |
| boxes = [pygeoj.load(path).bbox for path in geo_paths] | |
| λ0, φ0, λ1, φ1 = combine_bboxes(boxes) | |
| map.fit_bounds([(φ0, λ0), (φ1, λ1)]) | |
| folium.LayerControl().add_to(map) | |
| fp = os.fdopen(sys.stdout.fileno(), 'wb') | |
| map.save(fp) | |
| # map.save("output.html") | |
| if __name__ == "__main__": | |
| main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment