Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Oops forgot file
Browse files Browse the repository at this point in the history
mpiannucci committed Nov 6, 2024
1 parent 1edded9 commit 65a71d3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions xpublish_edr/formats/to_geojson.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
Generate GeoJSON responses for an xarray dataset for EDR queries
"""

import geopandas as gpd
import xarray as xr
from fastapi import Response


def to_geojson(ds: xr.Dataset):
"""Return a GeoJSON response from an xarray dataset"""
ds = ds.squeeze()
x_col = ds.cf["X"].name
y_col = ds.cf["Y"].name
if "T" in ds.cf:
time_col = ds.cf["T"].name
else:
time_col = None

df = ds.to_dataframe().reset_index()
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[x_col], df[y_col]))

# Map the time to a string if applicable
# TODO: Handle timezone?
if time_col:
gdf[time_col] = gdf[time_col].map(lambda t: t.isoformat())

json = gdf.to_json()

return Response(
json,
media_type="application/json",
)

0 comments on commit 65a71d3

Please sign in to comment.