Last active
July 7, 2025 15:41
-
-
Save ArthurDelannoyazerty/1e60ce2b8e8284a9cf91d174292fe17b to your computer and use it in GitHub Desktop.
Generate a earth grid and display them in a folium intercative HTML page
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
import folium | |
import s2geometry as s2 | |
from folium.plugins import Draw | |
def get_grid_coords(min_lat, max_lat, min_lng, max_lng, level, max_cells=0): | |
"""Generate S2 cells covering a specified region at a given level.""" | |
region = s2.S2LatLngRect( | |
s2.S2LatLng.FromDegrees(min_lat, min_lng), | |
s2.S2LatLng.FromDegrees(max_lat, max_lng) | |
) | |
coverer = s2.S2RegionCoverer() | |
coverer.set_min_level(level) | |
coverer.set_max_level(level) | |
if max_cells > 0: | |
coverer.set_max_cells(max_cells) | |
covering = coverer.GetCovering(region) | |
grid_coords = [] | |
for cell_id in covering: | |
cell = s2.S2Cell(cell_id) | |
vertices = [] | |
for i in range(4): | |
vertex = cell.GetVertex(i) | |
latlng = s2.S2LatLng(vertex) | |
vertices.append([latlng.lat().degrees(), latlng.lng().degrees()]) | |
# Close the polygon by adding the first point at the end | |
vertices.append(vertices[0]) | |
grid_coords.append(vertices) | |
return grid_coords | |
def display_map(polygons:list, output_filepath, center_lat, center_lon): | |
"""Save the polygons on a map on a html page with an Earth background.""" | |
m = folium.Map(location=[center_lat, center_lon], | |
zoom_start=3, | |
tiles='OpenStreetMap', | |
control_scale=True, | |
) | |
Draw(export=True).add_to(m) | |
# Add S2 cells to the map | |
for polygon in polygons: | |
folium.Polygon( | |
locations=polygon, | |
color='blue', | |
weight=1, | |
fill=True, | |
fill_opacity=0.2, | |
).add_to(m) | |
m.save(output_filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.