generated from ioos/ioos-python-package-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
Oops forgot file
1 parent
1edded9
commit 65a71d3
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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", | ||
) |