Skip to content

Instantly share code, notes, and snippets.

@ArthurDelannoyazerty
Last active July 7, 2025 15:41
Show Gist options
  • Save ArthurDelannoyazerty/1e60ce2b8e8284a9cf91d174292fe17b to your computer and use it in GitHub Desktop.
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
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)
@ArthurDelannoyazerty
Copy link
Author

ArthurDelannoyazerty commented Jul 7, 2025

if __name__ == "__main__":
    # Define the region and level
    min_lat, max_lat = -50.0, 50.0   # https://www.coordonnees-gps.fr/
    min_lng, max_lng = -60, 60
    level = 5                       # http://s2geometry.io/resources/s2cell_statistics
    max_cells = 0                   #If 0 then no limit
    grid_coords = get_grid_coords(min_lat, max_lat, min_lng, max_lng, level, max_cells)

    
    # Define the region and level
    min_lat, max_lat = 45.0, 50.0   # https://www.coordonnees-gps.fr/
    min_lng, max_lng = 20, 40
    level = 6                       # http://s2geometry.io/resources/s2cell_statistics
    max_cells = 0                   #If 0 then no limit
    grid_coords2 = get_grid_coords(min_lat, max_lat, min_lng, max_lng, level, max_cells)
    
    grid_coords.extend(grid_coords2)

    center_lat = (min_lat + max_lat) / 2
    center_lng = (min_lng + max_lng) / 2

    display_map(grid_coords, 'test.html', center_lat, center_lng)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment