giswqs commited on
Commit
9ad0e2d
β€’
1 Parent(s): 15bd62d

Add timelapse app

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
.gitignore ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ # *.html
6
+ private/
7
+ .vscode/
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ pip-wheel-metadata/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ target/
79
+
80
+ # Jupyter Notebook
81
+ .ipynb_checkpoints
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
98
+ __pypackages__/
99
+
100
+ # Celery stuff
101
+ celerybeat-schedule
102
+ celerybeat.pid
103
+
104
+ # SageMath parsed files
105
+ *.sage.py
106
+
107
+ # Environments
108
+ .env
109
+ .venv
110
+ env/
111
+ venv/
112
+ ENV/
113
+ env.bak/
114
+ venv.bak/
115
+
116
+ # Spyder project settings
117
+ .spyderproject
118
+ .spyproject
119
+
120
+ # Rope project settings
121
+ .ropeproject
122
+
123
+ # mkdocs documentation
124
+ /site
125
+
126
+ # mypy
127
+ .mypy_cache/
128
+ .dmypy.json
129
+ dmypy.json
130
+
131
+ # Pyre type checker
132
+ .pyre/
Home.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+ st.sidebar.title("Support")
23
+ st.sidebar.info(
24
+ """
25
+ If you want to reward my work, I'd love a cup of coffee from you. Thanks!
26
+ [buymeacoffee.com/giswqs](http://buymeacoffee.com/giswqs)
27
+ """
28
+ )
29
+
30
+
31
+ st.title("Streamlit for Geospatial Applications")
32
+
33
+ st.markdown(
34
+ """
35
+ This multi-page web app demonstrates various interactive web apps created using [streamlit](https://streamlit.io) and open-source mapping libraries,
36
+ such as [leafmap](https://leafmap.org), [geemap](https://geemap.org), [pydeck](https://deckgl.readthedocs.io), and [kepler.gl](https://docs.kepler.gl/docs/keplergl-jupyter).
37
+ This is an open-source project and you are very welcome to contribute your comments, questions, resources, and apps as [issues](https://github.com/giswqs/streamlit-geospatial/issues) or
38
+ [pull requests](https://github.com/giswqs/streamlit-geospatial/pulls) to the [GitHub repository](https://github.com/giswqs/streamlit-geospatial).
39
+
40
+ """
41
+ )
42
+
43
+ st.info("Click on the left sidebar menu to navigate to the different apps.")
44
+
45
+ st.subheader("Timelapse of Satellite Imagery")
46
+ st.markdown(
47
+ """
48
+ The following timelapse animations were created using the Timelapse web app. Click `Timelapse` on the left sidebar menu to create your own timelapse for any location around the globe.
49
+ """
50
+ )
51
+
52
+ row1_col1, row1_col2 = st.columns(2)
53
+ with row1_col1:
54
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/spain.gif")
55
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/las_vegas.gif")
56
+
57
+ with row1_col2:
58
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/goes.gif")
59
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/fire.gif")
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Qiusheng Wu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Procfile ADDED
@@ -0,0 +1 @@
 
 
1
+ web: sh setup.sh && streamlit run Home.py
app-bk.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from multiapp import MultiApp
3
+ from apps import (
4
+ basemaps,
5
+ census,
6
+ cesium,
7
+ deck,
8
+ device_loc,
9
+ gee,
10
+ gee_datasets,
11
+ heatmap,
12
+ home,
13
+ housing,
14
+ # hurricane,
15
+ plotly_maps,
16
+ raster,
17
+ timelapse,
18
+ vector,
19
+ wms,
20
+ xy,
21
+ )
22
+
23
+ st.set_page_config(layout="wide")
24
+
25
+
26
+ apps = MultiApp()
27
+
28
+ # Add all your application here
29
+
30
+ apps.add_app("Home", home.app)
31
+ apps.add_app("Create Timelapse", timelapse.app)
32
+ # apps.add_app("Hurricane Mapping", hurricane.app)
33
+ apps.add_app("U.S. Real Estate Data", housing.app)
34
+ apps.add_app("U.S. Census Data", census.app)
35
+ apps.add_app("Visualize Raster Data", raster.app)
36
+ apps.add_app("Visualize Vector Data", vector.app)
37
+ apps.add_app("Search Basemaps", basemaps.app)
38
+ apps.add_app("Pydeck Gallery", deck.app)
39
+ apps.add_app("Heatmaps", heatmap.app)
40
+ apps.add_app("Add Points from XY", xy.app)
41
+ apps.add_app("Add Web Map Service (WMS)", wms.app)
42
+ apps.add_app("Google Earth Engine (GEE)", gee.app)
43
+ apps.add_app("Awesome GEE Community Datasets", gee_datasets.app)
44
+ apps.add_app("Geolocation", device_loc.app)
45
+ apps.add_app("Cesium 3D Map", cesium.app)
46
+ apps.add_app("Plotly", plotly_maps.app)
47
+
48
+ # The main app
49
+ apps.run()
app.py CHANGED
@@ -1,4 +1,50 @@
1
  import streamlit as st
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
 
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+ st.title("Streamlit for Geospatial Applications")
23
+
24
+ st.markdown(
25
+ """
26
+ This multi-page web app demonstrates various interactive web apps created using [streamlit](https://streamlit.io) and open-source mapping libraries,
27
+ such as [leafmap](https://leafmap.org), [geemap](https://geemap.org), [pydeck](https://deckgl.readthedocs.io), and [kepler.gl](https://docs.kepler.gl/docs/keplergl-jupyter).
28
+ This is an open-source project and you are very welcome to contribute your comments, questions, resources, and apps as [issues](https://github.com/giswqs/streamlit-geospatial/issues) or
29
+ [pull requests](https://github.com/giswqs/streamlit-geospatial/pulls) to the [GitHub repository](https://github.com/giswqs/streamlit-geospatial).
30
+
31
+ """
32
+ )
33
+
34
+ st.info("Click on the left sidebar menu to navigate to the different apps.")
35
+
36
+ st.subheader("Timelapse of Satellite Imagery")
37
+ st.markdown(
38
+ """
39
+ The following timelapse animations were created using the Timelapse web app. Click `Timelapse` on the left sidebar menu to create your own timelapse for any location around the globe.
40
+ """
41
+ )
42
+
43
+ row1_col1, row1_col2 = st.columns(2)
44
+ with row1_col1:
45
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/spain.gif")
46
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/las_vegas.gif")
47
+
48
+ with row1_col2:
49
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/goes.gif")
50
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/fire.gif")
apps/basemaps.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+
5
+ def app():
6
+ st.title("Searching Basemaps")
7
+ st.markdown(
8
+ """
9
+ This app is a demonstration of searching and loading basemaps from [xyzservices](https://github.com/geopandas/xyzservices) and [Quick Map Services (QMS)](https://github.com/nextgis/quickmapservices). Selecting from 1000+ basemaps with a few clicks.
10
+ """
11
+ )
12
+
13
+ with st.expander("See demo"):
14
+ st.image("https://i.imgur.com/0SkUhZh.gif")
15
+
16
+ row1_col1, row1_col2 = st.columns([3, 1])
17
+ width = 800
18
+ height = 600
19
+ tiles = None
20
+
21
+ with row1_col2:
22
+
23
+ checkbox = st.checkbox("Search Quick Map Services (QMS)")
24
+ keyword = st.text_input("Enter a keyword to search and press Enter:")
25
+ empty = st.empty()
26
+
27
+ if keyword:
28
+ options = leafmap.search_xyz_services(keyword=keyword)
29
+ if checkbox:
30
+ qms = leafmap.search_qms(keyword=keyword)
31
+ if qms is not None:
32
+ options = options + qms
33
+
34
+ tiles = empty.multiselect(
35
+ "Select XYZ tiles to add to the map:", options)
36
+
37
+ with row1_col1:
38
+ m = leafmap.Map()
39
+
40
+ if tiles is not None:
41
+ for tile in tiles:
42
+ m.add_xyz_service(tile)
43
+
44
+ m.to_streamlit(width, height)
apps/census.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+
5
+ def app():
6
+ st.title("Using U.S. Census Data")
7
+ st.markdown(
8
+ """
9
+ This app is a demonstration of using the [U.S. Census Bureau](https://www.census.gov/) TIGERweb Web Map Service (WMS). A complete list of WMS layers can be found [here](https://tigerweb.geo.census.gov/tigerwebmain/TIGERweb_wms.html).
10
+ """
11
+ )
12
+
13
+ if "first_index" not in st.session_state:
14
+ st.session_state["first_index"] = 60
15
+ else:
16
+ st.session_state["first_index"] = 0
17
+
18
+ row1_col1, row1_col2 = st.columns([3, 1])
19
+ width = 800
20
+ height = 600
21
+
22
+ census_dict = leafmap.get_census_dict()
23
+ with row1_col2:
24
+
25
+ wms = st.selectbox("Select a WMS", list(census_dict.keys()), index=11)
26
+ layer = st.selectbox(
27
+ "Select a layer",
28
+ census_dict[wms]["layers"],
29
+ index=st.session_state["first_index"],
30
+ )
31
+
32
+ with row1_col1:
33
+ m = leafmap.Map()
34
+ m.add_census_data(wms, layer)
35
+ m.to_streamlit(width, height)
apps/cesium.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import leafmap
2
+ import streamlit as st
3
+
4
+
5
+ def app():
6
+ st.title("Cesium 3D Map")
7
+ html = "data/html/sfo_buildings.html"
8
+ leafmap.cesium_to_streamlit(html, height=800)
apps/deck.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import pydeck as pdk
4
+ import pandas as pd
5
+
6
+
7
+ def globe_view():
8
+
9
+ """
10
+ GlobeView
11
+ =========
12
+
13
+ Over 33,000 power plants of the world plotted by their production capacity (given by height)
14
+ and fuel type (green if renewable) on an experimental deck.gl GlobeView.
15
+ """
16
+
17
+ COUNTRIES = "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_admin_0_scale_rank.geojson"
18
+ POWER_PLANTS = "https://raw.githubusercontent.com/ajduberstein/geo_datasets/master/global_power_plant_database.csv"
19
+
20
+ df = pd.read_csv(POWER_PLANTS)
21
+
22
+ def is_green(fuel_type):
23
+ """Return a green RGB value if a facility uses a renewable fuel type"""
24
+ if fuel_type.lower() in (
25
+ "nuclear",
26
+ "water",
27
+ "wind",
28
+ "hydro",
29
+ "biomass",
30
+ "solar",
31
+ "geothermal",
32
+ ):
33
+ return [10, 230, 120]
34
+ return [230, 158, 10]
35
+
36
+ df["color"] = df["primary_fuel"].apply(is_green)
37
+
38
+ view_state = pdk.ViewState(latitude=51.47, longitude=0.45, zoom=2, min_zoom=2)
39
+
40
+ # Set height and width variables
41
+ view = pdk.View(type="_GlobeView", controller=True, width=1000, height=700)
42
+
43
+ layers = [
44
+ pdk.Layer(
45
+ "GeoJsonLayer",
46
+ id="base-map",
47
+ data=COUNTRIES,
48
+ stroked=False,
49
+ filled=True,
50
+ get_fill_color=[200, 200, 200],
51
+ ),
52
+ pdk.Layer(
53
+ "ColumnLayer",
54
+ id="power-plant",
55
+ data=df,
56
+ get_elevation="capacity_mw",
57
+ get_position=["longitude", "latitude"],
58
+ elevation_scale=100,
59
+ pickable=True,
60
+ auto_highlight=True,
61
+ radius=20000,
62
+ get_fill_color="color",
63
+ ),
64
+ ]
65
+
66
+ r = pdk.Deck(
67
+ views=[view],
68
+ initial_view_state=view_state,
69
+ tooltip={"text": "{name}, {primary_fuel} plant, {country}"},
70
+ layers=layers,
71
+ # Note that this must be set for the globe to be opaque
72
+ parameters={"cull": True},
73
+ )
74
+
75
+ return r
76
+
77
+
78
+ def geojson_layer():
79
+
80
+ """
81
+ GeoJsonLayer
82
+ ===========
83
+
84
+ Property values in Vancouver, Canada, adapted from the deck.gl example pages. Input data is in a GeoJSON format.
85
+ """
86
+
87
+ DATA_URL = "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json"
88
+ LAND_COVER = [
89
+ [[-123.0, 49.196], [-123.0, 49.324], [-123.306, 49.324], [-123.306, 49.196]]
90
+ ]
91
+
92
+ INITIAL_VIEW_STATE = pdk.ViewState(
93
+ latitude=49.254, longitude=-123.13, zoom=11, max_zoom=16, pitch=45, bearing=0
94
+ )
95
+
96
+ polygon = pdk.Layer(
97
+ "PolygonLayer",
98
+ LAND_COVER,
99
+ stroked=False,
100
+ # processes the data as a flat longitude-latitude pair
101
+ get_polygon="-",
102
+ get_fill_color=[0, 0, 0, 20],
103
+ )
104
+
105
+ geojson = pdk.Layer(
106
+ "GeoJsonLayer",
107
+ DATA_URL,
108
+ opacity=0.8,
109
+ stroked=False,
110
+ filled=True,
111
+ extruded=True,
112
+ wireframe=True,
113
+ get_elevation="properties.valuePerSqm / 20",
114
+ get_fill_color="[255, 255, properties.growth * 255]",
115
+ get_line_color=[255, 255, 255],
116
+ )
117
+
118
+ r = pdk.Deck(layers=[polygon, geojson], initial_view_state=INITIAL_VIEW_STATE)
119
+ return r
120
+
121
+
122
+ def terrain():
123
+
124
+ """
125
+ TerrainLayer
126
+ ===========
127
+
128
+ Extruded terrain using AWS Open Data Terrain Tiles and Mapbox Satellite imagery
129
+ """
130
+
131
+ # Import Mapbox API Key from environment
132
+ MAPBOX_API_KEY = os.environ["MAPBOX_API_KEY"]
133
+
134
+ # AWS Open Data Terrain Tiles
135
+ TERRAIN_IMAGE = (
136
+ "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
137
+ )
138
+
139
+ # Define how to parse elevation tiles
140
+ ELEVATION_DECODER = {
141
+ "rScaler": 256,
142
+ "gScaler": 1,
143
+ "bScaler": 1 / 256,
144
+ "offset": -32768,
145
+ }
146
+
147
+ SURFACE_IMAGE = f"https://api.mapbox.com/v4/mapbox.satellite/{{z}}/{{x}}/{{y}}@2x.png?access_token={MAPBOX_API_KEY}"
148
+
149
+ terrain_layer = pdk.Layer(
150
+ "TerrainLayer",
151
+ elevation_decoder=ELEVATION_DECODER,
152
+ texture=SURFACE_IMAGE,
153
+ elevation_data=TERRAIN_IMAGE,
154
+ )
155
+
156
+ view_state = pdk.ViewState(
157
+ latitude=46.24, longitude=-122.18, zoom=11.5, bearing=140, pitch=60
158
+ )
159
+
160
+ r = pdk.Deck(terrain_layer, initial_view_state=view_state)
161
+ return r
162
+
163
+
164
+ def app():
165
+
166
+ st.title("Pydeck Gallery")
167
+
168
+ options = ["GeoJsonLayer", "GlobeView", "TerrainLayer"]
169
+
170
+ option = st.selectbox("Select a pydeck layer type", options)
171
+
172
+ if option == "GeoJsonLayer":
173
+ st.header("Property values in Vancouver, Canada")
174
+ st.pydeck_chart(geojson_layer())
175
+ # elif option == "GlobeView":
176
+ # st.pydeck_chart(globe_view())
177
+ elif option == "TerrainLayer":
178
+ st.pydeck_chart(terrain())
apps/device_loc.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from bokeh.models.widgets import Button
3
+ from bokeh.models import CustomJS
4
+ from streamlit_bokeh_events import streamlit_bokeh_events
5
+ import leafmap.foliumap as leafmap
6
+
7
+
8
+ def app():
9
+
10
+ loc_button = Button(label="Get Device Location", max_width=150)
11
+ loc_button.js_on_event(
12
+ "button_click",
13
+ CustomJS(
14
+ code="""
15
+ navigator.geolocation.getCurrentPosition(
16
+ (loc) => {
17
+ document.dispatchEvent(new CustomEvent("GET_LOCATION", {detail: {lat: loc.coords.latitude, lon: loc.coords.longitude}}))
18
+ }
19
+ )
20
+ """
21
+ ),
22
+ )
23
+ result = streamlit_bokeh_events(
24
+ loc_button,
25
+ events="GET_LOCATION",
26
+ key="get_location",
27
+ refresh_on_update=False,
28
+ override_height=75,
29
+ debounce_time=0,
30
+ )
31
+
32
+ if result:
33
+ if "GET_LOCATION" in result:
34
+ loc = result.get("GET_LOCATION")
35
+ lat = loc.get("lat")
36
+ lon = loc.get("lon")
37
+ st.write(f"Lat, Lon: {lat}, {lon}")
38
+
39
+ m = leafmap.Map(center=(lat, lon), zoom=16)
40
+ m.add_basemap("ROADMAP")
41
+ popup = f"lat, lon: {lat}, {lon}"
42
+ m.add_marker(location=(lat, lon), popup=popup)
43
+ m.to_streamlit()
apps/gee.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import streamlit as st
3
+ import geemap.foliumap as geemap
4
+
5
+
6
+ def nlcd():
7
+
8
+ st.header("National Land Cover Database (NLCD)")
9
+
10
+ row1_col1, row1_col2 = st.columns([3, 1])
11
+ width = 950
12
+ height = 600
13
+
14
+ Map = geemap.Map()
15
+
16
+ # Select the seven NLCD epoches after 2000.
17
+ years = ["2001", "2004", "2006", "2008", "2011", "2013", "2016"]
18
+
19
+ # Get an NLCD image by year.
20
+ def getNLCD(year):
21
+ # Import the NLCD collection.
22
+ dataset = ee.ImageCollection("USGS/NLCD_RELEASES/2016_REL")
23
+
24
+ # Filter the collection by year.
25
+ nlcd = dataset.filter(ee.Filter.eq("system:index", year)).first()
26
+
27
+ # Select the land cover band.
28
+ landcover = nlcd.select("landcover")
29
+ return landcover
30
+
31
+ with row1_col2:
32
+ selected_year = st.multiselect("Select a year", years)
33
+ add_legend = st.checkbox("Show legend")
34
+
35
+ if selected_year:
36
+ for year in selected_year:
37
+ Map.addLayer(getNLCD(year), {}, "NLCD " + year)
38
+
39
+ if add_legend:
40
+ Map.add_legend(
41
+ legend_title="NLCD Land Cover Classification", builtin_legend="NLCD"
42
+ )
43
+ with row1_col1:
44
+ Map.to_streamlit(width=width, height=height)
45
+
46
+ else:
47
+ with row1_col1:
48
+ Map.to_streamlit(width=width, height=height)
49
+
50
+
51
+ def search_data():
52
+
53
+ st.header("Search Earth Engine Data Catalog")
54
+
55
+ Map = geemap.Map()
56
+
57
+ if "ee_assets" not in st.session_state:
58
+ st.session_state["ee_assets"] = None
59
+ if "asset_titles" not in st.session_state:
60
+ st.session_state["asset_titles"] = None
61
+
62
+ col1, col2 = st.columns([2, 1])
63
+
64
+ dataset = None
65
+ with col2:
66
+ keyword = st.text_input("Enter a keyword to search (e.g., elevation)", "")
67
+ if keyword:
68
+ ee_assets = geemap.search_ee_data(keyword)
69
+ asset_titles = [x["title"] for x in ee_assets]
70
+ dataset = st.selectbox("Select a dataset", asset_titles)
71
+ if len(ee_assets) > 0:
72
+ st.session_state["ee_assets"] = ee_assets
73
+ st.session_state["asset_titles"] = asset_titles
74
+
75
+ if dataset is not None:
76
+ with st.expander("Show dataset details", True):
77
+ index = asset_titles.index(dataset)
78
+ html = geemap.ee_data_html(st.session_state["ee_assets"][index])
79
+ st.markdown(html, True)
80
+
81
+ ee_id = ee_assets[index]["ee_id_snippet"]
82
+ uid = ee_assets[index]["uid"]
83
+ st.markdown(f"""**Earth Engine Snippet:** `{ee_id}`""")
84
+
85
+ vis_params = st.text_input(
86
+ "Enter visualization parameters as a dictionary", {}
87
+ )
88
+ layer_name = st.text_input("Enter a layer name", uid)
89
+ button = st.button("Add dataset to map")
90
+ if button:
91
+ vis = {}
92
+ try:
93
+ if vis_params.strip() == "":
94
+ # st.error("Please enter visualization parameters")
95
+ vis_params = "{}"
96
+ vis = eval(vis_params)
97
+ if not isinstance(vis, dict):
98
+ st.error("Visualization parameters must be a dictionary")
99
+ try:
100
+ Map.addLayer(eval(ee_id), vis, layer_name)
101
+ except Exception as e:
102
+ st.error(f"Error adding layer: {e}")
103
+ except Exception as e:
104
+ st.error(f"Invalid visualization parameters: {e}")
105
+
106
+ with col1:
107
+ Map.to_streamlit()
108
+ else:
109
+ with col1:
110
+ Map.to_streamlit()
111
+
112
+
113
+ def app():
114
+ st.title("Google Earth Engine Applications")
115
+
116
+ apps = ["National Land Cover Database (NLCD)", "Search Earth Engine Data Catalog"]
117
+
118
+ selected_app = st.selectbox("Select an app", apps)
119
+
120
+ if selected_app == "National Land Cover Database (NLCD)":
121
+ nlcd()
122
+ elif selected_app == "Search Earth Engine Data Catalog":
123
+ search_data()
apps/gee_datasets.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import streamlit as st
3
+ import geemap.foliumap as geemap
4
+
5
+ WIDTH = 1060
6
+ HEIGHT = 600
7
+
8
+
9
+ def function():
10
+ st.write("Not implemented yet.")
11
+ Map = geemap.Map()
12
+ Map.to_streamlit(WIDTH, HEIGHT)
13
+
14
+
15
+ def lulc_mrb_floodplain():
16
+
17
+ Map = geemap.Map()
18
+
19
+ State_boundaries = ee.FeatureCollection('users/giswqs/MRB/State_Boundaries')
20
+ State_style = State_boundaries.style(
21
+ **{'color': '808080', 'width': 1, 'fillColor': '00000000'}
22
+ )
23
+
24
+ MRB_boundary = ee.FeatureCollection('users/giswqs/MRB/MRB_Boundary')
25
+ MRB_style = MRB_boundary.style(
26
+ **{'color': '000000', 'width': 2, 'fillColor': '00000000'}
27
+ )
28
+
29
+ floodplain = ee.Image('users/giswqs/MRB/USGS_Floodplain')
30
+
31
+ class_values = [34, 38, 46, 50, 62]
32
+ class_palette = ['c500ff', '00ffc5', '00a9e6', '73004d', '004d73']
33
+
34
+ img_1950 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_1950')
35
+ img_1950 = img_1950.set('b1_class_values', class_values)
36
+ img_1950 = img_1950.set('b1_class_palette', class_palette)
37
+
38
+ img_1960 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_1960')
39
+ img_1960 = img_1960.set('b1_class_values', class_values)
40
+ img_1960 = img_1960.set('b1_class_palette', class_palette)
41
+
42
+ img_1970 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_1970')
43
+ img_1970 = img_1970.set('b1_class_values', class_values)
44
+ img_1970 = img_1970.set('b1_class_palette', class_palette)
45
+
46
+ img_1980 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_1980')
47
+ img_1980 = img_1980.set('b1_class_values', class_values)
48
+ img_1980 = img_1980.set('b1_class_palette', class_palette)
49
+
50
+ img_1990 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_1990')
51
+ img_1990 = img_1990.set('b1_class_values', class_values)
52
+ img_1990 = img_1990.set('b1_class_palette', class_palette)
53
+
54
+ img_2000 = ee.Image('users/giswqs/MRB/Major_Transitions_1941_2000')
55
+ img_2000 = img_2000.set('b1_class_values', class_values)
56
+ img_2000 = img_2000.set('b1_class_palette', class_palette)
57
+
58
+ Map.addLayer(floodplain, {'palette': ['cccccc']}, 'Floodplain', True, 0.5)
59
+ Map.addLayer(img_2000, {}, 'Major Transitions 1941-2000')
60
+ Map.addLayer(img_1990, {}, 'Major Transitions 1941-1990')
61
+ Map.addLayer(img_1980, {}, 'Major Transitions 1941-1980')
62
+ Map.addLayer(img_1970, {}, 'Major Transitions 1941-1970')
63
+ Map.addLayer(img_1960, {}, 'Major Transitions 1941-1960')
64
+ Map.addLayer(img_1950, {}, 'Major Transitions 1941-1950')
65
+
66
+ Map.addLayer(State_style, {}, 'State Boundaries')
67
+ Map.addLayer(MRB_style, {}, 'MRB Boundary')
68
+
69
+ Map.to_streamlit(WIDTH, HEIGHT)
70
+
71
+
72
+ def global_mangrove_watch():
73
+ """https://samapriya.github.io/awesome-gee-community-datasets/projects/mangrove/"""
74
+ Map = geemap.Map()
75
+ gmw2007 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2007_v2")
76
+ gmw2008 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2008_v2")
77
+ gmw2009 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2009_v2")
78
+ gmw2010 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2010_v2")
79
+ gmw2015 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2015_v2")
80
+ gmw2016 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_2016_v2")
81
+ gmw1996 = ee.FeatureCollection("projects/sat-io/open-datasets/GMW/GMW_1996_v2")
82
+
83
+ Map.addLayer(
84
+ ee.Image().paint(gmw1996, 0, 3),
85
+ {"palette": ["228B22"]},
86
+ 'Global Mangrove Watch 1996',
87
+ )
88
+ Map.addLayer(
89
+ ee.Image().paint(gmw2007, 0, 3),
90
+ {"palette": ["228B22"]},
91
+ 'Global Mangrove Watch 2007',
92
+ )
93
+ Map.addLayer(
94
+ ee.Image().paint(gmw2008, 0, 3),
95
+ {"palette": ["228B22"]},
96
+ 'Global Mangrove Watch 2008',
97
+ )
98
+ Map.addLayer(
99
+ ee.Image().paint(gmw2009, 0, 3),
100
+ {"palette": ["228B22"]},
101
+ 'Global Mangrove Watch 2009',
102
+ )
103
+ Map.addLayer(
104
+ ee.Image().paint(gmw2010, 0, 3),
105
+ {"palette": ["228B22"]},
106
+ 'Global Mangrove Watch 2010',
107
+ )
108
+ Map.addLayer(
109
+ ee.Image().paint(gmw2015, 0, 3),
110
+ {"palette": ["228B22"]},
111
+ 'Global Mangrove Watch 2015',
112
+ )
113
+ Map.addLayer(
114
+ ee.Image().paint(gmw2016, 0, 3),
115
+ {"palette": ["228B22"]},
116
+ 'Global Mangrove Watch 2015',
117
+ )
118
+
119
+ Map.to_streamlit(WIDTH, HEIGHT)
120
+
121
+
122
+ def app():
123
+
124
+ st.title("Awesome GEE Community Datasets")
125
+
126
+ st.markdown(
127
+ """
128
+
129
+ This app is for exploring the [Awesome GEE Community Datasets](https://samapriya.github.io/awesome-gee-community-datasets). Work in progress.
130
+
131
+ """
132
+ )
133
+
134
+ datasets = {
135
+ "Population & Socioeconomic": {
136
+ "High Resolution Settlement Layer": "function()",
137
+ "World Settlement Footprint (2015)": "function()",
138
+ "Gridded Population of the World": "function()",
139
+ "geoBoundaries Global Database": "function()",
140
+ "West Africa Coastal Vulnerability Mapping": "function()",
141
+ "Relative Wealth Index (RWI)": "function()",
142
+ "Social Connectedness Index (SCI)": "function()",
143
+ "Native Land (Indigenous Land Maps)": "function()",
144
+ },
145
+ "Geophysical, Biological & Biogeochemical": {
146
+ "Geomorpho90m Geomorphometric Layers": "function()",
147
+ },
148
+ "Land Use and Land Cover": {
149
+ "Global Mangrove Watch": "global_mangrove_watch()",
150
+ "Mississippi River Basin Floodplain Land Use Change (1941-2000)": "lulc_mrb_floodplain()",
151
+ },
152
+ "Hydrology": {
153
+ "Global Shoreline Dataset": "function()",
154
+ },
155
+ "Agriculture, Vegetation and Forestry": {
156
+ "Landfire Mosaics LF v2.0.0": "function()",
157
+ },
158
+ "Global Utilities, Assets and Amenities Layers": {
159
+ "Global Power": "function()",
160
+ },
161
+ "EarthEnv Biodiversity ecosystems & climate Layers": {
162
+ "Global Consensus Landcover": "function()",
163
+ },
164
+ "Weather and Climate Layers": {
165
+ "Global Reference Evapotranspiration Layers": "function()",
166
+ },
167
+ "Global Events Layers": {
168
+ "Global Fire Atlas (2003-2016)": "function()",
169
+ },
170
+ }
171
+
172
+ row1_col1, row1_col2, _ = st.columns([1.2, 1.8, 1])
173
+
174
+ with row1_col1:
175
+ category = st.selectbox("Select a category", datasets.keys(), index=2)
176
+ with row1_col2:
177
+ dataset = st.selectbox("Select a dataset", datasets[category].keys())
178
+
179
+ Map = geemap.Map()
180
+
181
+ if dataset:
182
+ eval(datasets[category][dataset])
183
+
184
+ else:
185
+ Map = geemap.Map()
186
+ Map.to_streamlit(WIDTH, HEIGHT)
apps/heatmap.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+
5
+ def app():
6
+
7
+ st.title('Heatmaps')
8
+
9
+ filepath = "https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_cities.csv"
10
+ m = leafmap.Map(tiles="stamentoner")
11
+ m.add_heatmap(
12
+ filepath,
13
+ latitude="latitude",
14
+ longitude="longitude",
15
+ value="pop_max",
16
+ name="Heat map",
17
+ radius=20,
18
+ )
19
+ m.to_streamlit(width=700, height=500)
apps/home.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+
5
+ def app():
6
+ st.title("Streamlit for Geospatial Applications")
7
+
8
+ st.markdown(
9
+ """
10
+ This multi-page web app demonstrates various interactive web apps created using [streamlit](https://streamlit.io) and open-source mapping libraries,
11
+ such as [leafmap](https://leafmap.org), [geemap](https://geemap.org), [pydeck](https://deckgl.readthedocs.io), and [kepler.gl](https://docs.kepler.gl/docs/keplergl-jupyter).
12
+ This is an open-source project and you are very welcome to contribute your comments, questions, resources, and apps as [issues](https://github.com/giswqs/streamlit-geospatial/issues) or
13
+ [pull requests](https://github.com/giswqs/streamlit-geospatial/pulls) to the [GitHub repository](https://github.com/giswqs/streamlit-geospatial).
14
+
15
+ """
16
+ )
17
+
18
+ st.info("Click on the left sidebar menu to navigate to the different apps.")
19
+
20
+ st.subheader("Timelapse of Satellite Imagery")
21
+ st.markdown(
22
+ """
23
+ The following timelapse animations were created using the Timelapse web app. Click `Create Timelapse` on the left sidebar menu to create your own timelapse for any location around the globe.
24
+ """
25
+ )
26
+
27
+ row1_col1, row1_col2 = st.columns(2)
28
+ with row1_col1:
29
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/spain.gif")
30
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/las_vegas.gif")
31
+
32
+ with row1_col2:
33
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/goes.gif")
34
+ st.image("https://github.com/giswqs/data/raw/main/timelapse/fire.gif")
apps/housing.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import pathlib
4
+ import requests
5
+ import zipfile
6
+ import pandas as pd
7
+ import pydeck as pdk
8
+ import geopandas as gpd
9
+ import streamlit as st
10
+ import leafmap.colormaps as cm
11
+ from leafmap.common import hex_to_rgb
12
+
13
+
14
+ STREAMLIT_STATIC_PATH = pathlib.Path(st.__path__[0]) / "static"
15
+ # We create a downloads directory within the streamlit static asset directory
16
+ # and we write output files to it
17
+ DOWNLOADS_PATH = STREAMLIT_STATIC_PATH / "downloads"
18
+ if not DOWNLOADS_PATH.is_dir():
19
+ DOWNLOADS_PATH.mkdir()
20
+
21
+ # Data source: https://www.realtor.com/research/data/
22
+ # link_prefix = "https://econdata.s3-us-west-2.amazonaws.com/Reports/"
23
+ link_prefix = "https://raw.githubusercontent.com/giswqs/data/main/housing/"
24
+
25
+ data_links = {
26
+ "weekly": {
27
+ "national": link_prefix + "Core/listing_weekly_core_aggregate_by_country.csv",
28
+ "metro": link_prefix + "Core/listing_weekly_core_aggregate_by_metro.csv",
29
+ },
30
+ "monthly_current": {
31
+ "national": link_prefix + "Core/RDC_Inventory_Core_Metrics_Country.csv",
32
+ "state": link_prefix + "Core/RDC_Inventory_Core_Metrics_State.csv",
33
+ "metro": link_prefix + "Core/RDC_Inventory_Core_Metrics_Metro.csv",
34
+ "county": link_prefix + "Core/RDC_Inventory_Core_Metrics_County.csv",
35
+ "zip": link_prefix + "Core/RDC_Inventory_Core_Metrics_Zip.csv",
36
+ },
37
+ "monthly_historical": {
38
+ "national": link_prefix + "Core/RDC_Inventory_Core_Metrics_Country_History.csv",
39
+ "state": link_prefix + "Core/RDC_Inventory_Core_Metrics_State_History.csv",
40
+ "metro": link_prefix + "Core/RDC_Inventory_Core_Metrics_Metro_History.csv",
41
+ "county": link_prefix + "Core/RDC_Inventory_Core_Metrics_County_History.csv",
42
+ "zip": link_prefix + "Core/RDC_Inventory_Core_Metrics_Zip_History.csv",
43
+ },
44
+ "hotness": {
45
+ "metro": link_prefix
46
+ + "Hotness/RDC_Inventory_Hotness_Metrics_Metro_History.csv",
47
+ "county": link_prefix
48
+ + "Hotness/RDC_Inventory_Hotness_Metrics_County_History.csv",
49
+ "zip": link_prefix + "Hotness/RDC_Inventory_Hotness_Metrics_Zip_History.csv",
50
+ },
51
+ }
52
+
53
+
54
+ def get_data_columns(df, category, frequency="monthly"):
55
+ if frequency == "monthly":
56
+ if category.lower() == "county":
57
+ del_cols = ["month_date_yyyymm", "county_fips", "county_name"]
58
+ elif category.lower() == "state":
59
+ del_cols = ["month_date_yyyymm", "state", "state_id"]
60
+ elif category.lower() == "national":
61
+ del_cols = ["month_date_yyyymm", "country"]
62
+ elif category.lower() == "metro":
63
+ del_cols = ["month_date_yyyymm", "cbsa_code", "cbsa_title", "HouseholdRank"]
64
+ elif category.lower() == "zip":
65
+ del_cols = ["month_date_yyyymm", "postal_code", "zip_name", "flag"]
66
+ elif frequency == "weekly":
67
+ if category.lower() == "national":
68
+ del_cols = ["week_end_date", "geo_country"]
69
+ elif category.lower() == "metro":
70
+ del_cols = ["week_end_date", "cbsa_code", "cbsa_title", "hh_rank"]
71
+
72
+ cols = df.columns.values.tolist()
73
+
74
+ for col in cols:
75
+ if col.strip() in del_cols:
76
+ cols.remove(col)
77
+ if category.lower() == "metro":
78
+ return cols[2:]
79
+ else:
80
+ return cols[1:]
81
+
82
+
83
+ @st.cache
84
+ def get_inventory_data(url):
85
+ df = pd.read_csv(url)
86
+ url = url.lower()
87
+ if "county" in url:
88
+ df["county_fips"] = df["county_fips"].map(str)
89
+ df["county_fips"] = df["county_fips"].str.zfill(5)
90
+ elif "state" in url:
91
+ df["STUSPS"] = df["state_id"].str.upper()
92
+ elif "metro" in url:
93
+ df["cbsa_code"] = df["cbsa_code"].map(str)
94
+ elif "zip" in url:
95
+ df["postal_code"] = df["postal_code"].map(str)
96
+ df["postal_code"] = df["postal_code"].str.zfill(5)
97
+
98
+ if "listing_weekly_core_aggregate_by_country" in url:
99
+ columns = get_data_columns(df, "national", "weekly")
100
+ for column in columns:
101
+ if column != "median_days_on_market_by_day_yy":
102
+ df[column] = df[column].str.rstrip("%").astype(float) / 100
103
+ if "listing_weekly_core_aggregate_by_metro" in url:
104
+ columns = get_data_columns(df, "metro", "weekly")
105
+ for column in columns:
106
+ if column != "median_days_on_market_by_day_yy":
107
+ df[column] = df[column].str.rstrip("%").astype(float) / 100
108
+ df["cbsa_code"] = df["cbsa_code"].str[:5]
109
+ return df
110
+
111
+
112
+ def filter_weekly_inventory(df, week):
113
+ df = df[df["week_end_date"] == week]
114
+ return df
115
+
116
+
117
+ def get_start_end_year(df):
118
+ start_year = int(str(df["month_date_yyyymm"].min())[:4])
119
+ end_year = int(str(df["month_date_yyyymm"].max())[:4])
120
+ return start_year, end_year
121
+
122
+
123
+ def get_periods(df):
124
+ return [str(d) for d in list(set(df["month_date_yyyymm"].tolist()))]
125
+
126
+
127
+ @st.cache
128
+ def get_geom_data(category):
129
+
130
+ prefix = (
131
+ "https://raw.githubusercontent.com/giswqs/streamlit-geospatial/master/data/"
132
+ )
133
+ links = {
134
+ "national": prefix + "us_nation.geojson",
135
+ "state": prefix + "us_states.geojson",
136
+ "county": prefix + "us_counties.geojson",
137
+ "metro": prefix + "us_metro_areas.geojson",
138
+ "zip": "https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_zcta510_500k.zip",
139
+ }
140
+
141
+ if category.lower() == "zip":
142
+ r = requests.get(links[category])
143
+ out_zip = os.path.join(DOWNLOADS_PATH, "cb_2018_us_zcta510_500k.zip")
144
+ with open(out_zip, "wb") as code:
145
+ code.write(r.content)
146
+ zip_ref = zipfile.ZipFile(out_zip, "r")
147
+ zip_ref.extractall(DOWNLOADS_PATH)
148
+ gdf = gpd.read_file(out_zip.replace("zip", "shp"))
149
+ else:
150
+ gdf = gpd.read_file(links[category])
151
+ return gdf
152
+
153
+
154
+ def join_attributes(gdf, df, category):
155
+
156
+ new_gdf = None
157
+ if category == "county":
158
+ new_gdf = gdf.merge(df, left_on="GEOID", right_on="county_fips", how="outer")
159
+ elif category == "state":
160
+ new_gdf = gdf.merge(df, left_on="STUSPS", right_on="STUSPS", how="outer")
161
+ elif category == "national":
162
+ if "geo_country" in df.columns.values.tolist():
163
+ df["country"] = None
164
+ df.loc[0, "country"] = "United States"
165
+ new_gdf = gdf.merge(df, left_on="NAME", right_on="country", how="outer")
166
+ elif category == "metro":
167
+ new_gdf = gdf.merge(df, left_on="CBSAFP", right_on="cbsa_code", how="outer")
168
+ elif category == "zip":
169
+ new_gdf = gdf.merge(df, left_on="GEOID10", right_on="postal_code", how="outer")
170
+ return new_gdf
171
+
172
+
173
+ def select_non_null(gdf, col_name):
174
+ new_gdf = gdf[~gdf[col_name].isna()]
175
+ return new_gdf
176
+
177
+
178
+ def select_null(gdf, col_name):
179
+ new_gdf = gdf[gdf[col_name].isna()]
180
+ return new_gdf
181
+
182
+
183
+ def get_data_dict(name):
184
+ in_csv = os.path.join(os.getcwd(), "data/realtor_data_dict.csv")
185
+ df = pd.read_csv(in_csv)
186
+ label = list(df[df["Name"] == name]["Label"])[0]
187
+ desc = list(df[df["Name"] == name]["Description"])[0]
188
+ return label, desc
189
+
190
+
191
+ def get_weeks(df):
192
+ seq = list(set(df[~df["week_end_date"].isnull()]["week_end_date"].tolist()))
193
+ weeks = [
194
+ datetime.date(int(d.split("/")[2]), int(d.split("/")[0]), int(d.split("/")[1]))
195
+ for d in seq
196
+ ]
197
+ weeks.sort()
198
+ return weeks
199
+
200
+
201
+ def get_saturday(in_date):
202
+ idx = (in_date.weekday() + 1) % 7
203
+ sat = in_date + datetime.timedelta(6 - idx)
204
+ return sat
205
+
206
+
207
+ def app():
208
+
209
+ st.title("U.S. Real Estate Data and Market Trends")
210
+ st.markdown(
211
+ """**Introduction:** This interactive dashboard is designed for visualizing U.S. real estate data and market trends at multiple levels (i.e., national,
212
+ state, county, and metro). The data sources include [Real Estate Data](https://www.realtor.com/research/data) from realtor.com and
213
+ [Cartographic Boundary Files](https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html) from U.S. Census Bureau.
214
+ Several open-source packages are used to process the data and generate the visualizations, e.g., [streamlit](https://streamlit.io),
215
+ [geopandas](https://geopandas.org), [leafmap](https://leafmap.org), and [pydeck](https://deckgl.readthedocs.io).
216
+ """
217
+ )
218
+
219
+ with st.expander("See a demo"):
220
+ st.image("https://i.imgur.com/Z3dk6Tr.gif")
221
+
222
+ row1_col1, row1_col2, row1_col3, row1_col4, row1_col5 = st.columns(
223
+ [0.6, 0.8, 0.6, 1.4, 2]
224
+ )
225
+ with row1_col1:
226
+ frequency = st.selectbox("Monthly/weekly data", ["Monthly", "Weekly"])
227
+ with row1_col2:
228
+ types = ["Current month data", "Historical data"]
229
+ if frequency == "Weekly":
230
+ types.remove("Current month data")
231
+ cur_hist = st.selectbox(
232
+ "Current/historical data",
233
+ types,
234
+ )
235
+ with row1_col3:
236
+ if frequency == "Monthly":
237
+ scale = st.selectbox(
238
+ "Scale", ["National", "State", "Metro", "County"], index=3
239
+ )
240
+ else:
241
+ scale = st.selectbox("Scale", ["National", "Metro"], index=1)
242
+
243
+ gdf = get_geom_data(scale.lower())
244
+
245
+ if frequency == "Weekly":
246
+ inventory_df = get_inventory_data(data_links["weekly"][scale.lower()])
247
+ weeks = get_weeks(inventory_df)
248
+ with row1_col1:
249
+ selected_date = st.date_input("Select a date", value=weeks[-1])
250
+ saturday = get_saturday(selected_date)
251
+ selected_period = saturday.strftime("%-m/%-d/%Y")
252
+ if saturday not in weeks:
253
+ st.error(
254
+ "The selected date is not available in the data. Please select a date between {} and {}".format(
255
+ weeks[0], weeks[-1]
256
+ )
257
+ )
258
+ selected_period = weeks[-1].strftime("%-m/%-d/%Y")
259
+ inventory_df = get_inventory_data(data_links["weekly"][scale.lower()])
260
+ inventory_df = filter_weekly_inventory(inventory_df, selected_period)
261
+
262
+ if frequency == "Monthly":
263
+ if cur_hist == "Current month data":
264
+ inventory_df = get_inventory_data(
265
+ data_links["monthly_current"][scale.lower()]
266
+ )
267
+ selected_period = get_periods(inventory_df)[0]
268
+ else:
269
+ with row1_col2:
270
+ inventory_df = get_inventory_data(
271
+ data_links["monthly_historical"][scale.lower()]
272
+ )
273
+ start_year, end_year = get_start_end_year(inventory_df)
274
+ periods = get_periods(inventory_df)
275
+ with st.expander("Select year and month", True):
276
+ selected_year = st.slider(
277
+ "Year",
278
+ start_year,
279
+ end_year,
280
+ value=start_year,
281
+ step=1,
282
+ )
283
+ selected_month = st.slider(
284
+ "Month",
285
+ min_value=1,
286
+ max_value=12,
287
+ value=int(periods[0][-2:]),
288
+ step=1,
289
+ )
290
+ selected_period = str(selected_year) + str(selected_month).zfill(2)
291
+ if selected_period not in periods:
292
+ st.error("Data not available for selected year and month")
293
+ selected_period = periods[0]
294
+ inventory_df = inventory_df[
295
+ inventory_df["month_date_yyyymm"] == int(selected_period)
296
+ ]
297
+
298
+ data_cols = get_data_columns(inventory_df, scale.lower(), frequency.lower())
299
+
300
+ with row1_col4:
301
+ selected_col = st.selectbox("Attribute", data_cols)
302
+ with row1_col5:
303
+ show_desc = st.checkbox("Show attribute description")
304
+ if show_desc:
305
+ try:
306
+ label, desc = get_data_dict(selected_col.strip())
307
+ markdown = f"""
308
+ **{label}**: {desc}
309
+ """
310
+ st.markdown(markdown)
311
+ except:
312
+ st.warning("No description available for selected attribute")
313
+
314
+ row2_col1, row2_col2, row2_col3, row2_col4, row2_col5, row2_col6 = st.columns(
315
+ [0.6, 0.68, 0.7, 0.7, 1.5, 0.8]
316
+ )
317
+
318
+ palettes = cm.list_colormaps()
319
+ with row2_col1:
320
+ palette = st.selectbox("Color palette", palettes, index=palettes.index("Blues"))
321
+ with row2_col2:
322
+ n_colors = st.slider("Number of colors", min_value=2, max_value=20, value=8)
323
+ with row2_col3:
324
+ show_nodata = st.checkbox("Show nodata areas", value=True)
325
+ with row2_col4:
326
+ show_3d = st.checkbox("Show 3D view", value=False)
327
+ with row2_col5:
328
+ if show_3d:
329
+ elev_scale = st.slider(
330
+ "Elevation scale", min_value=1, max_value=1000000, value=1, step=10
331
+ )
332
+ with row2_col6:
333
+ st.info("Press Ctrl and move the left mouse button.")
334
+ else:
335
+ elev_scale = 1
336
+
337
+ gdf = join_attributes(gdf, inventory_df, scale.lower())
338
+ gdf_null = select_null(gdf, selected_col)
339
+ gdf = select_non_null(gdf, selected_col)
340
+ gdf = gdf.sort_values(by=selected_col, ascending=True)
341
+
342
+ colors = cm.get_palette(palette, n_colors)
343
+ colors = [hex_to_rgb(c) for c in colors]
344
+
345
+ for i, ind in enumerate(gdf.index):
346
+ index = int(i / (len(gdf) / len(colors)))
347
+ if index >= len(colors):
348
+ index = len(colors) - 1
349
+ gdf.loc[ind, "R"] = colors[index][0]
350
+ gdf.loc[ind, "G"] = colors[index][1]
351
+ gdf.loc[ind, "B"] = colors[index][2]
352
+
353
+ initial_view_state = pdk.ViewState(
354
+ latitude=40, longitude=-100, zoom=3, max_zoom=16, pitch=0, bearing=0
355
+ )
356
+
357
+ min_value = gdf[selected_col].min()
358
+ max_value = gdf[selected_col].max()
359
+ color = "color"
360
+ # color_exp = f"[({selected_col}-{min_value})/({max_value}-{min_value})*255, 0, 0]"
361
+ color_exp = f"[R, G, B]"
362
+
363
+ geojson = pdk.Layer(
364
+ "GeoJsonLayer",
365
+ gdf,
366
+ pickable=True,
367
+ opacity=0.5,
368
+ stroked=True,
369
+ filled=True,
370
+ extruded=show_3d,
371
+ wireframe=True,
372
+ get_elevation=f"{selected_col}",
373
+ elevation_scale=elev_scale,
374
+ # get_fill_color="color",
375
+ get_fill_color=color_exp,
376
+ get_line_color=[0, 0, 0],
377
+ get_line_width=2,
378
+ line_width_min_pixels=1,
379
+ )
380
+
381
+ geojson_null = pdk.Layer(
382
+ "GeoJsonLayer",
383
+ gdf_null,
384
+ pickable=True,
385
+ opacity=0.2,
386
+ stroked=True,
387
+ filled=True,
388
+ extruded=False,
389
+ wireframe=True,
390
+ # get_elevation="properties.ALAND/100000",
391
+ # get_fill_color="color",
392
+ get_fill_color=[200, 200, 200],
393
+ get_line_color=[0, 0, 0],
394
+ get_line_width=2,
395
+ line_width_min_pixels=1,
396
+ )
397
+
398
+ # tooltip = {"text": "Name: {NAME}"}
399
+
400
+ # tooltip_value = f"<b>Value:</b> {median_listing_price}""
401
+ tooltip = {
402
+ "html": "<b>Name:</b> {NAME}<br><b>Value:</b> {"
403
+ + selected_col
404
+ + "}<br><b>Date:</b> "
405
+ + selected_period
406
+ + "",
407
+ "style": {"backgroundColor": "steelblue", "color": "white"},
408
+ }
409
+
410
+ layers = [geojson]
411
+ if show_nodata:
412
+ layers.append(geojson_null)
413
+
414
+ r = pdk.Deck(
415
+ layers=layers,
416
+ initial_view_state=initial_view_state,
417
+ map_style="light",
418
+ tooltip=tooltip,
419
+ )
420
+
421
+ row3_col1, row3_col2 = st.columns([6, 1])
422
+
423
+ with row3_col1:
424
+ st.pydeck_chart(r)
425
+ with row3_col2:
426
+ st.write(
427
+ cm.create_colormap(
428
+ palette,
429
+ label=selected_col.replace("_", " ").title(),
430
+ width=0.2,
431
+ height=3,
432
+ orientation="vertical",
433
+ vmin=min_value,
434
+ vmax=max_value,
435
+ font_size=10,
436
+ )
437
+ )
438
+ row4_col1, row4_col2, row4_col3 = st.columns([1, 2, 3])
439
+ with row4_col1:
440
+ show_data = st.checkbox("Show raw data")
441
+ with row4_col2:
442
+ show_cols = st.multiselect("Select columns", data_cols)
443
+ with row4_col3:
444
+ show_colormaps = st.checkbox("Preview all color palettes")
445
+ if show_colormaps:
446
+ st.write(cm.plot_colormaps(return_fig=True))
447
+ if show_data:
448
+ if scale == "National":
449
+ st.dataframe(gdf[["NAME", "GEOID"] + show_cols])
450
+ elif scale == "State":
451
+ st.dataframe(gdf[["NAME", "STUSPS"] + show_cols])
452
+ elif scale == "County":
453
+ st.dataframe(gdf[["NAME", "STATEFP", "COUNTYFP"] + show_cols])
454
+ elif scale == "Metro":
455
+ st.dataframe(gdf[["NAME", "CBSAFP"] + show_cols])
456
+ elif scale == "Zip":
457
+ st.dataframe(gdf[["GEOID10"] + show_cols])
apps/hurricane.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import tropycal.tracks as tracks
3
+
4
+
5
+ @st.cache
6
+ def read_data(basin='north_atlantic', source='hurdat', include_btk=False):
7
+ return tracks.TrackDataset(basin=basin, source=source, include_btk=include_btk)
8
+
9
+
10
+ def app():
11
+
12
+ st.title("Hurricane Mapping")
13
+
14
+ row1_col1, row1_col2 = st.columns([3, 1])
15
+
16
+ with row1_col1:
17
+ empty = st.empty()
18
+ empty.image("https://i.imgur.com/Ec7qsR0.png")
19
+
20
+ with row1_col2:
21
+
22
+ checkbox = st.checkbox("Select from a list of hurricanes", value=False)
23
+ if checkbox:
24
+ if st.session_state.get('hurricane') is None:
25
+ st.session_state['hurricane'] = read_data()
26
+
27
+ years = st.slider(
28
+ 'Select a year', min_value=1950, max_value=2022, value=(2000, 2010)
29
+ )
30
+ storms = st.session_state['hurricane'].filter_storms(year_range=years)
31
+ selected = st.selectbox('Select a storm', storms)
32
+ storm = st.session_state['hurricane'].get_storm(selected)
33
+ ax = storm.plot()
34
+ fig = ax.get_figure()
35
+ empty.pyplot(fig)
36
+ else:
37
+
38
+ name = st.text_input("Or enter a storm Name", "michael")
39
+ if name:
40
+ if st.session_state.get('hurricane') is None:
41
+ st.session_state['hurricane'] = read_data()
42
+ basin = st.session_state['hurricane']
43
+ years = basin.search_name(name)
44
+ if len(years) > 0:
45
+ year = st.selectbox("Select a year", years)
46
+ storm = basin.get_storm((name, year))
47
+ ax = storm.plot()
48
+ fig = ax.get_figure()
49
+ empty.pyplot(fig)
50
+ else:
51
+ empty.text("No storms found")
52
+ st.write("No storms found")
apps/plotly_maps.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.plotlymap as leafmap
3
+
4
+
5
+ def app():
6
+
7
+ st.title("Plotly Maps")
8
+ m = leafmap.Map(basemap="street", height=650)
9
+ m.add_mapbox_layer(style="streets")
10
+
11
+ basemaps = list(leafmap.basemaps.keys())
12
+ basemap = st.selectbox(
13
+ "Select a basemap", basemaps, basemaps.index("Stamen.Terrain")
14
+ )
15
+ m.add_basemap(basemap)
16
+
17
+ st.plotly_chart(m, use_container_width=True)
apps/raster.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import leafmap.foliumap as leafmap
3
+ import streamlit as st
4
+ import palettable
5
+
6
+
7
+ @st.cache
8
+ def load_cog_list():
9
+ print(os.getcwd())
10
+ in_txt = os.path.join(os.getcwd(), "data/cog_files.txt")
11
+ with open(in_txt) as f:
12
+ return [line.strip() for line in f.readlines()[1:]]
13
+
14
+
15
+ @st.cache
16
+ def get_palettes():
17
+ palettes = dir(palettable.matplotlib)[:-16]
18
+ return ["matplotlib." + p for p in palettes]
19
+
20
+
21
+ def app():
22
+
23
+ st.title("Visualize Raster Datasets")
24
+ st.markdown(
25
+ """
26
+ An interactive web app for visualizing local raster datasets and Cloud Optimized GeoTIFF ([COG](https://www.cogeo.org)). The app was built using [streamlit](https://streamlit.io), [leafmap](https://leafmap.org), and [localtileserver](https://github.com/banesullivan/localtileserver).
27
+
28
+
29
+ """
30
+ )
31
+
32
+ row1_col1, row1_col2 = st.columns([2, 1])
33
+
34
+ with row1_col1:
35
+ cog_list = load_cog_list()
36
+ cog = st.selectbox("Select a sample Cloud Opitmized GeoTIFF (COG)", cog_list)
37
+
38
+ with row1_col2:
39
+ empty = st.empty()
40
+
41
+ url = empty.text_input(
42
+ "Enter a HTTP URL to a Cloud Optimized GeoTIFF (COG)",
43
+ cog,
44
+ )
45
+
46
+ data = st.file_uploader("Upload a raster dataset", type=["tif", "img"])
47
+
48
+ if data:
49
+ url = empty.text_input(
50
+ "Enter a URL to a Cloud Optimized GeoTIFF (COG)",
51
+ "",
52
+ )
53
+
54
+ add_palette = st.checkbox("Add a color palette")
55
+ if add_palette:
56
+ palette = st.selectbox("Select a color palette", get_palettes())
57
+ else:
58
+ palette = None
59
+
60
+ submit = st.button("Submit")
61
+
62
+ m = leafmap.Map(latlon_control=False)
63
+
64
+ if submit:
65
+ if data or url:
66
+ try:
67
+ if data:
68
+ file_path = leafmap.save_data(data)
69
+ m.add_local_tile(file_path, palette=palette, debug=True)
70
+ elif url:
71
+ m.add_remote_tile(url, palette=palette, debug=True)
72
+ except Exception as e:
73
+ with row1_col2:
74
+ st.error("Work in progress. Try it again later.")
75
+
76
+ with row1_col1:
77
+ m.to_streamlit()
apps/rois.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ A module for storing some sample ROIs for creating Landsat/GOES timelapse.
2
+ """
3
+
4
+ from shapely.geometry import Polygon
5
+
6
+ goes_rois = {
7
+ "Creek Fire, CA (2020-09-05)": {
8
+ "region": Polygon(
9
+ [
10
+ [-121.003418, 36.848857],
11
+ [-121.003418, 39.049052],
12
+ [-117.905273, 39.049052],
13
+ [-117.905273, 36.848857],
14
+ [-121.003418, 36.848857],
15
+ ]
16
+ ),
17
+ "start_time": "2020-09-05T15:00:00",
18
+ "end_time": "2020-09-06T02:00:00",
19
+ },
20
+ "Bomb Cyclone (2021-10-24)": {
21
+ "region": Polygon(
22
+ [
23
+ [-159.5954, 60.4088],
24
+ [-159.5954, 24.5178],
25
+ [-114.2438, 24.5178],
26
+ [-114.2438, 60.4088],
27
+ ]
28
+ ),
29
+ "start_time": "2021-10-24T14:00:00",
30
+ "end_time": "2021-10-25T01:00:00",
31
+ },
32
+ "Hunga Tonga Volcanic Eruption (2022-01-15)": {
33
+ "region": Polygon(
34
+ [
35
+ [-192.480469, -32.546813],
36
+ [-192.480469, -8.754795],
37
+ [-157.587891, -8.754795],
38
+ [-157.587891, -32.546813],
39
+ [-192.480469, -32.546813],
40
+ ]
41
+ ),
42
+ "start_time": "2022-01-15T03:00:00",
43
+ "end_time": "2022-01-15T07:00:00",
44
+ },
45
+ "Hunga Tonga Volcanic Eruption Closer Look (2022-01-15)": {
46
+ "region": Polygon(
47
+ [
48
+ [-178.901367, -22.958393],
49
+ [-178.901367, -17.85329],
50
+ [-171.452637, -17.85329],
51
+ [-171.452637, -22.958393],
52
+ [-178.901367, -22.958393],
53
+ ]
54
+ ),
55
+ "start_time": "2022-01-15T03:00:00",
56
+ "end_time": "2022-01-15T07:00:00",
57
+ },
58
+ }
59
+
60
+
61
+ landsat_rois = {
62
+ "Aral Sea": Polygon(
63
+ [
64
+ [57.667236, 43.834527],
65
+ [57.667236, 45.996962],
66
+ [61.12793, 45.996962],
67
+ [61.12793, 43.834527],
68
+ [57.667236, 43.834527],
69
+ ]
70
+ ),
71
+ "Dubai": Polygon(
72
+ [
73
+ [54.541626, 24.763044],
74
+ [54.541626, 25.427152],
75
+ [55.632019, 25.427152],
76
+ [55.632019, 24.763044],
77
+ [54.541626, 24.763044],
78
+ ]
79
+ ),
80
+ "Hong Kong International Airport": Polygon(
81
+ [
82
+ [113.825226, 22.198849],
83
+ [113.825226, 22.349758],
84
+ [114.085121, 22.349758],
85
+ [114.085121, 22.198849],
86
+ [113.825226, 22.198849],
87
+ ]
88
+ ),
89
+ "Las Vegas, NV": Polygon(
90
+ [
91
+ [-115.554199, 35.804449],
92
+ [-115.554199, 36.558188],
93
+ [-113.903503, 36.558188],
94
+ [-113.903503, 35.804449],
95
+ [-115.554199, 35.804449],
96
+ ]
97
+ ),
98
+ "Pucallpa, Peru": Polygon(
99
+ [
100
+ [-74.672699, -8.600032],
101
+ [-74.672699, -8.254983],
102
+ [-74.279938, -8.254983],
103
+ [-74.279938, -8.600032],
104
+ ]
105
+ ),
106
+ "Sierra Gorda, Chile": Polygon(
107
+ [
108
+ [-69.315491, -22.837104],
109
+ [-69.315491, -22.751488],
110
+ [-69.190006, -22.751488],
111
+ [-69.190006, -22.837104],
112
+ [-69.315491, -22.837104],
113
+ ]
114
+ ),
115
+ }
116
+
117
+ modis_rois = {
118
+ "World": Polygon(
119
+ [
120
+ [-171.210938, -57.136239],
121
+ [-171.210938, 79.997168],
122
+ [177.539063, 79.997168],
123
+ [177.539063, -57.136239],
124
+ [-171.210938, -57.136239],
125
+ ]
126
+ ),
127
+ "Africa": Polygon(
128
+ [
129
+ [-18.6983, 38.1446],
130
+ [-18.6983, -36.1630],
131
+ [52.2293, -36.1630],
132
+ [52.2293, 38.1446],
133
+ ]
134
+ ),
135
+ "USA": Polygon(
136
+ [
137
+ [-127.177734, 23.725012],
138
+ [-127.177734, 50.792047],
139
+ [-66.269531, 50.792047],
140
+ [-66.269531, 23.725012],
141
+ [-127.177734, 23.725012],
142
+ ]
143
+ ),
144
+ }
145
+
146
+ ocean_rois = {
147
+ "Gulf of Mexico": Polygon(
148
+ [
149
+ [-101.206055, 15.496032],
150
+ [-101.206055, 32.361403],
151
+ [-75.673828, 32.361403],
152
+ [-75.673828, 15.496032],
153
+ [-101.206055, 15.496032],
154
+ ]
155
+ ),
156
+ "North Atlantic Ocean": Polygon(
157
+ [
158
+ [-85.341797, 24.046464],
159
+ [-85.341797, 45.02695],
160
+ [-55.810547, 45.02695],
161
+ [-55.810547, 24.046464],
162
+ [-85.341797, 24.046464],
163
+ ]
164
+ ),
165
+ "World": Polygon(
166
+ [
167
+ [-171.210938, -57.136239],
168
+ [-171.210938, 79.997168],
169
+ [177.539063, 79.997168],
170
+ [177.539063, -57.136239],
171
+ [-171.210938, -57.136239],
172
+ ]
173
+ ),
174
+ }
apps/timelapse.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import os
3
+ import datetime
4
+ import fiona
5
+ import geopandas as gpd
6
+ import folium
7
+ import streamlit as st
8
+ import geemap.colormaps as cm
9
+ import geemap.foliumap as geemap
10
+ from datetime import date
11
+ from .rois import *
12
+
13
+
14
+ @st.cache
15
+ def uploaded_file_to_gdf(data):
16
+ import tempfile
17
+ import os
18
+ import uuid
19
+
20
+ _, file_extension = os.path.splitext(data.name)
21
+ file_id = str(uuid.uuid4())
22
+ file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_extension}")
23
+
24
+ with open(file_path, "wb") as file:
25
+ file.write(data.getbuffer())
26
+
27
+ if file_path.lower().endswith(".kml"):
28
+ fiona.drvsupport.supported_drivers["KML"] = "rw"
29
+ gdf = gpd.read_file(file_path, driver="KML")
30
+ else:
31
+ gdf = gpd.read_file(file_path)
32
+
33
+ return gdf
34
+
35
+
36
+ def app():
37
+
38
+ today = date.today()
39
+
40
+ st.title("Create Timelapse")
41
+
42
+ st.markdown(
43
+ """
44
+ An interactive web app for creating [Landsat](https://developers.google.com/earth-engine/datasets/catalog/landsat)/[GOES](https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16) timelapse for any location around the globe.
45
+ The app was built using [streamlit](https://streamlit.io), [geemap](https://geemap.org), and [Google Earth Engine](https://earthengine.google.com). For more info, check out my streamlit [blog post](https://blog.streamlit.io/creating-satellite-timelapse-with-streamlit-and-earth-engine).
46
+ """
47
+ )
48
+
49
+ row1_col1, row1_col2 = st.columns([2, 1])
50
+
51
+ if st.session_state.get("zoom_level") is None:
52
+ st.session_state["zoom_level"] = 4
53
+
54
+ st.session_state["ee_asset_id"] = None
55
+ st.session_state["bands"] = None
56
+ st.session_state["palette"] = None
57
+ st.session_state["vis_params"] = None
58
+
59
+ with row1_col1:
60
+ m = geemap.Map(
61
+ basemap="HYBRID",
62
+ plugin_Draw=True,
63
+ Draw_export=True,
64
+ locate_control=True,
65
+ plugin_LatLngPopup=False,
66
+ )
67
+ m.add_basemap("ROADMAP")
68
+
69
+ with row1_col2:
70
+
71
+ keyword = st.text_input("Search for a location:", "")
72
+ if keyword:
73
+ locations = geemap.geocode(keyword)
74
+ if locations is not None and len(locations) > 0:
75
+ str_locations = [str(g)[1:-1] for g in locations]
76
+ location = st.selectbox("Select a location:", str_locations)
77
+ loc_index = str_locations.index(location)
78
+ selected_loc = locations[loc_index]
79
+ lat, lng = selected_loc.lat, selected_loc.lng
80
+ folium.Marker(location=[lat, lng], popup=location).add_to(m)
81
+ m.set_center(lng, lat, 12)
82
+ st.session_state["zoom_level"] = 12
83
+
84
+ collection = st.selectbox(
85
+ "Select a satellite image collection: ",
86
+ [
87
+ "Any Earth Engine ImageCollection",
88
+ "Landsat TM-ETM-OLI Surface Reflectance",
89
+ "Sentinel-2 MSI Surface Reflectance",
90
+ "Geostationary Operational Environmental Satellites (GOES)",
91
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
92
+ "MODIS Gap filled Land Surface Temperature Daily",
93
+ "MODIS Ocean Color SMI",
94
+ "USDA National Agriculture Imagery Program (NAIP)",
95
+ ],
96
+ index=1,
97
+ )
98
+
99
+ if collection in [
100
+ "Landsat TM-ETM-OLI Surface Reflectance",
101
+ "Sentinel-2 MSI Surface Reflectance",
102
+ ]:
103
+ roi_options = ["Uploaded GeoJSON"] + list(landsat_rois.keys())
104
+
105
+ elif collection == "Geostationary Operational Environmental Satellites (GOES)":
106
+ roi_options = ["Uploaded GeoJSON"] + list(goes_rois.keys())
107
+
108
+ elif collection in [
109
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
110
+ "MODIS Gap filled Land Surface Temperature Daily",
111
+ ]:
112
+ roi_options = ["Uploaded GeoJSON"] + list(modis_rois.keys())
113
+ elif collection == "MODIS Ocean Color SMI":
114
+ roi_options = ["Uploaded GeoJSON"] + list(ocean_rois.keys())
115
+ else:
116
+ roi_options = ["Uploaded GeoJSON"]
117
+
118
+ if collection == "Any Earth Engine ImageCollection":
119
+ keyword = st.text_input("Enter a keyword to search (e.g., MODIS):", "")
120
+ if keyword:
121
+
122
+ assets = geemap.search_ee_data(keyword)
123
+ ee_assets = []
124
+ for asset in assets:
125
+ if asset["ee_id_snippet"].startswith("ee.ImageCollection"):
126
+ ee_assets.append(asset)
127
+
128
+ asset_titles = [x["title"] for x in ee_assets]
129
+ dataset = st.selectbox("Select a dataset:", asset_titles)
130
+ if len(ee_assets) > 0:
131
+ st.session_state["ee_assets"] = ee_assets
132
+ st.session_state["asset_titles"] = asset_titles
133
+ index = asset_titles.index(dataset)
134
+ ee_id = ee_assets[index]["id"]
135
+ else:
136
+ ee_id = ""
137
+
138
+ if dataset is not None:
139
+ with st.expander("Show dataset details", False):
140
+ index = asset_titles.index(dataset)
141
+ html = geemap.ee_data_html(st.session_state["ee_assets"][index])
142
+ st.markdown(html, True)
143
+ # elif collection == "MODIS Gap filled Land Surface Temperature Daily":
144
+ # ee_id = ""
145
+ else:
146
+ ee_id = ""
147
+
148
+ asset_id = st.text_input("Enter an ee.ImageCollection asset ID:", ee_id)
149
+
150
+ if asset_id:
151
+ with st.expander("Customize band combination and color palette", True):
152
+ try:
153
+ col = ee.ImageCollection.load(asset_id)
154
+ st.session_state["ee_asset_id"] = asset_id
155
+ except:
156
+ st.error("Invalid Earth Engine asset ID.")
157
+ st.session_state["ee_asset_id"] = None
158
+ return
159
+
160
+ img_bands = col.first().bandNames().getInfo()
161
+ if len(img_bands) >= 3:
162
+ default_bands = img_bands[:3][::-1]
163
+ else:
164
+ default_bands = img_bands[:]
165
+ bands = st.multiselect(
166
+ "Select one or three bands (RGB):", img_bands, default_bands
167
+ )
168
+ st.session_state["bands"] = bands
169
+
170
+ if len(bands) == 1:
171
+ palette_options = st.selectbox(
172
+ "Color palette",
173
+ cm.list_colormaps(),
174
+ index=2,
175
+ )
176
+ palette_values = cm.get_palette(palette_options, 15)
177
+ palette = st.text_area(
178
+ "Enter a custom palette:",
179
+ palette_values,
180
+ )
181
+ st.write(
182
+ cm.plot_colormap(cmap=palette_options, return_fig=True)
183
+ )
184
+ st.session_state["palette"] = eval(palette)
185
+
186
+ if bands:
187
+ vis_params = st.text_area(
188
+ "Enter visualization parameters",
189
+ "{'bands': ["
190
+ + ", ".join([f"'{band}'" for band in bands])
191
+ + "]}",
192
+ )
193
+ else:
194
+ vis_params = st.text_area(
195
+ "Enter visualization parameters",
196
+ "{}",
197
+ )
198
+ try:
199
+ st.session_state["vis_params"] = eval(vis_params)
200
+ st.session_state["vis_params"]["palette"] = st.session_state[
201
+ "palette"
202
+ ]
203
+ except Exception as e:
204
+ st.session_state["vis_params"] = None
205
+ st.error(
206
+ f"Invalid visualization parameters. It must be a dictionary."
207
+ )
208
+
209
+ elif collection == "MODIS Gap filled Land Surface Temperature Daily":
210
+ with st.expander("Show dataset details", False):
211
+ st.markdown(
212
+ """
213
+ See the [Awesome GEE Community Datasets](https://samapriya.github.io/awesome-gee-community-datasets/projects/daily_lst/).
214
+ """
215
+ )
216
+
217
+ MODIS_options = ["Daytime (1:30 pm)", "Nighttime (1:30 am)"]
218
+ MODIS_option = st.selectbox("Select a MODIS dataset:", MODIS_options)
219
+ if MODIS_option == "Daytime (1:30 pm)":
220
+ st.session_state[
221
+ "ee_asset_id"
222
+ ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
223
+ else:
224
+ st.session_state[
225
+ "ee_asset_id"
226
+ ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"
227
+
228
+ palette_options = st.selectbox(
229
+ "Color palette",
230
+ cm.list_colormaps(),
231
+ index=90,
232
+ )
233
+ palette_values = cm.get_palette(palette_options, 15)
234
+ palette = st.text_area(
235
+ "Enter a custom palette:",
236
+ palette_values,
237
+ )
238
+ st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
239
+ st.session_state["palette"] = eval(palette)
240
+ elif collection == "MODIS Ocean Color SMI":
241
+ with st.expander("Show dataset details", False):
242
+ st.markdown(
243
+ """
244
+ See the [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI).
245
+ """
246
+ )
247
+
248
+ MODIS_options = ["Aqua", "Terra"]
249
+ MODIS_option = st.selectbox("Select a satellite:", MODIS_options)
250
+ st.session_state["ee_asset_id"] = MODIS_option
251
+ # if MODIS_option == "Daytime (1:30 pm)":
252
+ # st.session_state[
253
+ # "ee_asset_id"
254
+ # ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
255
+ # else:
256
+ # st.session_state[
257
+ # "ee_asset_id"
258
+ # ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"
259
+
260
+ band_dict = {
261
+ "Chlorophyll a concentration": "chlor_a",
262
+ "Normalized fluorescence line height": "nflh",
263
+ "Particulate organic carbon": "poc",
264
+ "Sea surface temperature": "sst",
265
+ "Remote sensing reflectance at band 412nm": "Rrs_412",
266
+ "Remote sensing reflectance at band 443nm": "Rrs_443",
267
+ "Remote sensing reflectance at band 469nm": "Rrs_469",
268
+ "Remote sensing reflectance at band 488nm": "Rrs_488",
269
+ "Remote sensing reflectance at band 531nm": "Rrs_531",
270
+ "Remote sensing reflectance at band 547nm": "Rrs_547",
271
+ "Remote sensing reflectance at band 555nm": "Rrs_555",
272
+ "Remote sensing reflectance at band 645nm": "Rrs_645",
273
+ "Remote sensing reflectance at band 667nm": "Rrs_667",
274
+ "Remote sensing reflectance at band 678nm": "Rrs_678",
275
+ }
276
+
277
+ band_options = list(band_dict.keys())
278
+ band = st.selectbox(
279
+ "Select a band",
280
+ band_options,
281
+ band_options.index("Sea surface temperature"),
282
+ )
283
+ st.session_state["band"] = band_dict[band]
284
+
285
+ colors = cm.list_colormaps()
286
+ palette_options = st.selectbox(
287
+ "Color palette",
288
+ colors,
289
+ index=colors.index("coolwarm"),
290
+ )
291
+ palette_values = cm.get_palette(palette_options, 15)
292
+ palette = st.text_area(
293
+ "Enter a custom palette:",
294
+ palette_values,
295
+ )
296
+ st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
297
+ st.session_state["palette"] = eval(palette)
298
+
299
+ sample_roi = st.selectbox(
300
+ "Select a sample ROI or upload a GeoJSON file:",
301
+ roi_options,
302
+ index=0,
303
+ )
304
+
305
+ add_outline = st.checkbox(
306
+ "Overlay an administrative boundary on timelapse", False
307
+ )
308
+
309
+ if add_outline:
310
+
311
+ with st.expander("Customize administrative boundary", True):
312
+
313
+ overlay_options = {
314
+ "User-defined": None,
315
+ "Continents": "continents",
316
+ "Countries": "countries",
317
+ "US States": "us_states",
318
+ "China": "china",
319
+ }
320
+
321
+ overlay = st.selectbox(
322
+ "Select an administrative boundary:",
323
+ list(overlay_options.keys()),
324
+ index=2,
325
+ )
326
+
327
+ overlay_data = overlay_options[overlay]
328
+
329
+ if overlay_data is None:
330
+ overlay_data = st.text_input(
331
+ "Enter an HTTP URL to a GeoJSON file or an ee.FeatureCollection asset id:",
332
+ "https://raw.githubusercontent.com/giswqs/geemap/master/examples/data/countries.geojson",
333
+ )
334
+
335
+ overlay_color = st.color_picker(
336
+ "Select a color for the administrative boundary:", "#000000"
337
+ )
338
+ overlay_width = st.slider(
339
+ "Select a line width for the administrative boundary:", 1, 20, 1
340
+ )
341
+ overlay_opacity = st.slider(
342
+ "Select an opacity for the administrative boundary:",
343
+ 0.0,
344
+ 1.0,
345
+ 1.0,
346
+ 0.05,
347
+ )
348
+ else:
349
+ overlay_data = None
350
+ overlay_color = "black"
351
+ overlay_width = 1
352
+ overlay_opacity = 1
353
+
354
+ with row1_col1:
355
+
356
+ with st.expander(
357
+ "Steps: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Expand this tab to see a demo πŸ‘‰"
358
+ ):
359
+ video_empty = st.empty()
360
+
361
+ data = st.file_uploader(
362
+ "Upload a GeoJSON file to use as an ROI. Customize timelapse parameters and then click the Submit button πŸ˜‡πŸ‘‡",
363
+ type=["geojson", "kml", "zip"],
364
+ )
365
+
366
+ crs = "epsg:4326"
367
+ if sample_roi == "Uploaded GeoJSON":
368
+ if data is None:
369
+ # st.info(
370
+ # "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click Submit button"
371
+ # )
372
+ if collection in [
373
+ "Geostationary Operational Environmental Satellites (GOES)",
374
+ "USDA National Agriculture Imagery Program (NAIP)",
375
+ ] and (not keyword):
376
+ m.set_center(-100, 40, 3)
377
+ # else:
378
+ # m.set_center(4.20, 18.63, zoom=2)
379
+ else:
380
+ if collection in [
381
+ "Landsat TM-ETM-OLI Surface Reflectance",
382
+ "Sentinel-2 MSI Surface Reflectance",
383
+ ]:
384
+ gdf = gpd.GeoDataFrame(
385
+ index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
386
+ )
387
+ elif (
388
+ collection
389
+ == "Geostationary Operational Environmental Satellites (GOES)"
390
+ ):
391
+ gdf = gpd.GeoDataFrame(
392
+ index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
393
+ )
394
+ elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":
395
+ gdf = gpd.GeoDataFrame(
396
+ index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
397
+ )
398
+
399
+ if sample_roi != "Uploaded GeoJSON":
400
+
401
+ if collection in [
402
+ "Landsat TM-ETM-OLI Surface Reflectance",
403
+ "Sentinel-2 MSI Surface Reflectance",
404
+ ]:
405
+ gdf = gpd.GeoDataFrame(
406
+ index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
407
+ )
408
+ elif (
409
+ collection
410
+ == "Geostationary Operational Environmental Satellites (GOES)"
411
+ ):
412
+ gdf = gpd.GeoDataFrame(
413
+ index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
414
+ )
415
+ elif collection in [
416
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
417
+ "MODIS Gap filled Land Surface Temperature Daily",
418
+ ]:
419
+ gdf = gpd.GeoDataFrame(
420
+ index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
421
+ )
422
+ elif collection == "MODIS Ocean Color SMI":
423
+ gdf = gpd.GeoDataFrame(
424
+ index=[0], crs=crs, geometry=[ocean_rois[sample_roi]]
425
+ )
426
+ st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
427
+ m.add_gdf(gdf, "ROI")
428
+
429
+ elif data:
430
+ gdf = uploaded_file_to_gdf(data)
431
+ st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
432
+ m.add_gdf(gdf, "ROI")
433
+
434
+ m.to_streamlit(height=600)
435
+
436
+ with row1_col2:
437
+
438
+ if collection in [
439
+ "Landsat TM-ETM-OLI Surface Reflectance",
440
+ "Sentinel-2 MSI Surface Reflectance",
441
+ ]:
442
+
443
+ if collection == "Landsat TM-ETM-OLI Surface Reflectance":
444
+ sensor_start_year = 1984
445
+ timelapse_title = "Landsat Timelapse"
446
+ timelapse_speed = 5
447
+ elif collection == "Sentinel-2 MSI Surface Reflectance":
448
+ sensor_start_year = 2015
449
+ timelapse_title = "Sentinel-2 Timelapse"
450
+ timelapse_speed = 5
451
+ video_empty.video("https://youtu.be/VVRK_-dEjR4")
452
+
453
+ with st.form("submit_landsat_form"):
454
+
455
+ roi = None
456
+ if st.session_state.get("roi") is not None:
457
+ roi = st.session_state.get("roi")
458
+ out_gif = geemap.temp_file_path(".gif")
459
+
460
+ title = st.text_input(
461
+ "Enter a title to show on the timelapse: ", timelapse_title
462
+ )
463
+ RGB = st.selectbox(
464
+ "Select an RGB band combination:",
465
+ [
466
+ "Red/Green/Blue",
467
+ "NIR/Red/Green",
468
+ "SWIR2/SWIR1/NIR",
469
+ "NIR/SWIR1/Red",
470
+ "SWIR2/NIR/Red",
471
+ "SWIR2/SWIR1/Red",
472
+ "SWIR1/NIR/Blue",
473
+ "NIR/SWIR1/Blue",
474
+ "SWIR2/NIR/Green",
475
+ "SWIR1/NIR/Red",
476
+ "SWIR2/NIR/SWIR1",
477
+ "SWIR1/NIR/SWIR2",
478
+ ],
479
+ index=9,
480
+ )
481
+
482
+ frequency = st.selectbox(
483
+ "Select a temporal frequency:",
484
+ ["year", "quarter", "month"],
485
+ index=0,
486
+ )
487
+
488
+ with st.expander("Customize timelapse"):
489
+
490
+ speed = st.slider("Frames per second:", 1, 30, timelapse_speed)
491
+ dimensions = st.slider(
492
+ "Maximum dimensions (Width*Height) in pixels", 768, 2000, 768
493
+ )
494
+ progress_bar_color = st.color_picker(
495
+ "Progress bar color:", "#0000ff"
496
+ )
497
+ years = st.slider(
498
+ "Start and end year:",
499
+ sensor_start_year,
500
+ today.year,
501
+ (sensor_start_year, today.year),
502
+ )
503
+ months = st.slider("Start and end month:", 1, 12, (1, 12))
504
+ font_size = st.slider("Font size:", 10, 50, 30)
505
+ font_color = st.color_picker("Font color:", "#ffffff")
506
+ apply_fmask = st.checkbox(
507
+ "Apply fmask (remove clouds, shadows, snow)", True
508
+ )
509
+ font_type = st.selectbox(
510
+ "Select the font type for the title:",
511
+ ["arial.ttf", "alibaba.otf"],
512
+ index=0,
513
+ )
514
+ fading = st.slider(
515
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
516
+ )
517
+ mp4 = st.checkbox("Save timelapse as MP4", True)
518
+
519
+ empty_text = st.empty()
520
+ empty_image = st.empty()
521
+ empty_fire_image = st.empty()
522
+ empty_video = st.container()
523
+ submitted = st.form_submit_button("Submit")
524
+ if submitted:
525
+
526
+ if sample_roi == "Uploaded GeoJSON" and data is None:
527
+ empty_text.warning(
528
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
529
+ )
530
+ else:
531
+
532
+ empty_text.text("Computing... Please wait...")
533
+
534
+ start_year = years[0]
535
+ end_year = years[1]
536
+ start_date = str(months[0]).zfill(2) + "-01"
537
+ end_date = str(months[1]).zfill(2) + "-30"
538
+ bands = RGB.split("/")
539
+
540
+ try:
541
+ if collection == "Landsat TM-ETM-OLI Surface Reflectance":
542
+ out_gif = geemap.landsat_timelapse(
543
+ roi=roi,
544
+ out_gif=out_gif,
545
+ start_year=start_year,
546
+ end_year=end_year,
547
+ start_date=start_date,
548
+ end_date=end_date,
549
+ bands=bands,
550
+ apply_fmask=apply_fmask,
551
+ frames_per_second=speed,
552
+ dimensions=dimensions,
553
+ overlay_data=overlay_data,
554
+ overlay_color=overlay_color,
555
+ overlay_width=overlay_width,
556
+ overlay_opacity=overlay_opacity,
557
+ frequency=frequency,
558
+ date_format=None,
559
+ title=title,
560
+ title_xy=("2%", "90%"),
561
+ add_text=True,
562
+ text_xy=("2%", "2%"),
563
+ text_sequence=None,
564
+ font_type=font_type,
565
+ font_size=font_size,
566
+ font_color=font_color,
567
+ add_progress_bar=True,
568
+ progress_bar_color=progress_bar_color,
569
+ progress_bar_height=5,
570
+ loop=0,
571
+ mp4=mp4,
572
+ fading=fading,
573
+ )
574
+ elif collection == "Sentinel-2 MSI Surface Reflectance":
575
+ out_gif = geemap.sentinel2_timelapse(
576
+ roi=roi,
577
+ out_gif=out_gif,
578
+ start_year=start_year,
579
+ end_year=end_year,
580
+ start_date=start_date,
581
+ end_date=end_date,
582
+ bands=bands,
583
+ apply_fmask=apply_fmask,
584
+ frames_per_second=speed,
585
+ dimensions=dimensions,
586
+ overlay_data=overlay_data,
587
+ overlay_color=overlay_color,
588
+ overlay_width=overlay_width,
589
+ overlay_opacity=overlay_opacity,
590
+ frequency=frequency,
591
+ date_format=None,
592
+ title=title,
593
+ title_xy=("2%", "90%"),
594
+ add_text=True,
595
+ text_xy=("2%", "2%"),
596
+ text_sequence=None,
597
+ font_type=font_type,
598
+ font_size=font_size,
599
+ font_color=font_color,
600
+ add_progress_bar=True,
601
+ progress_bar_color=progress_bar_color,
602
+ progress_bar_height=5,
603
+ loop=0,
604
+ mp4=mp4,
605
+ fading=fading,
606
+ )
607
+ except:
608
+ empty_text.error(
609
+ "An error occurred while computing the timelapse. Your probably requested too much data. Try reducing the ROI or timespan."
610
+ )
611
+ st.stop()
612
+
613
+ if out_gif is not None and os.path.exists(out_gif):
614
+
615
+ empty_text.text(
616
+ "Right click the GIF to save it to your computerπŸ‘‡"
617
+ )
618
+ empty_image.image(out_gif)
619
+
620
+ out_mp4 = out_gif.replace(".gif", ".mp4")
621
+ if mp4 and os.path.exists(out_mp4):
622
+ with empty_video:
623
+ st.text(
624
+ "Right click the MP4 to save it to your computerπŸ‘‡"
625
+ )
626
+ st.video(out_gif.replace(".gif", ".mp4"))
627
+
628
+ else:
629
+ empty_text.error(
630
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
631
+ )
632
+
633
+ elif collection == "Geostationary Operational Environmental Satellites (GOES)":
634
+
635
+ video_empty.video("https://youtu.be/16fA2QORG4A")
636
+
637
+ with st.form("submit_goes_form"):
638
+
639
+ roi = None
640
+ if st.session_state.get("roi") is not None:
641
+ roi = st.session_state.get("roi")
642
+ out_gif = geemap.temp_file_path(".gif")
643
+
644
+ satellite = st.selectbox("Select a satellite:", ["GOES-17", "GOES-16"])
645
+ earliest_date = datetime.date(2017, 7, 10)
646
+ latest_date = datetime.date.today()
647
+
648
+ if sample_roi == "Uploaded GeoJSON":
649
+ roi_start_date = today - datetime.timedelta(days=2)
650
+ roi_end_date = today - datetime.timedelta(days=1)
651
+ roi_start_time = datetime.time(14, 00)
652
+ roi_end_time = datetime.time(1, 00)
653
+ else:
654
+ roi_start = goes_rois[sample_roi]["start_time"]
655
+ roi_end = goes_rois[sample_roi]["end_time"]
656
+ roi_start_date = datetime.datetime.strptime(
657
+ roi_start[:10], "%Y-%m-%d"
658
+ )
659
+ roi_end_date = datetime.datetime.strptime(roi_end[:10], "%Y-%m-%d")
660
+ roi_start_time = datetime.time(
661
+ int(roi_start[11:13]), int(roi_start[14:16])
662
+ )
663
+ roi_end_time = datetime.time(
664
+ int(roi_end[11:13]), int(roi_end[14:16])
665
+ )
666
+
667
+ start_date = st.date_input("Select the start date:", roi_start_date)
668
+ end_date = st.date_input("Select the end date:", roi_end_date)
669
+
670
+ with st.expander("Customize timelapse"):
671
+
672
+ add_fire = st.checkbox("Add Fire/Hotspot Characterization", False)
673
+
674
+ scan_type = st.selectbox(
675
+ "Select a scan type:", ["Full Disk", "CONUS", "Mesoscale"]
676
+ )
677
+
678
+ start_time = st.time_input(
679
+ "Select the start time of the start date:", roi_start_time
680
+ )
681
+
682
+ end_time = st.time_input(
683
+ "Select the end time of the end date:", roi_end_time
684
+ )
685
+
686
+ start = (
687
+ start_date.strftime("%Y-%m-%d")
688
+ + "T"
689
+ + start_time.strftime("%H:%M:%S")
690
+ )
691
+ end = (
692
+ end_date.strftime("%Y-%m-%d")
693
+ + "T"
694
+ + end_time.strftime("%H:%M:%S")
695
+ )
696
+
697
+ speed = st.slider("Frames per second:", 1, 30, 5)
698
+ add_progress_bar = st.checkbox("Add a progress bar", True)
699
+ progress_bar_color = st.color_picker(
700
+ "Progress bar color:", "#0000ff"
701
+ )
702
+ font_size = st.slider("Font size:", 10, 50, 20)
703
+ font_color = st.color_picker("Font color:", "#ffffff")
704
+ fading = st.slider(
705
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
706
+ )
707
+ mp4 = st.checkbox("Save timelapse as MP4", True)
708
+
709
+ empty_text = st.empty()
710
+ empty_image = st.empty()
711
+ empty_video = st.container()
712
+ empty_fire_text = st.empty()
713
+ empty_fire_image = st.empty()
714
+
715
+ submitted = st.form_submit_button("Submit")
716
+ if submitted:
717
+ if sample_roi == "Uploaded GeoJSON" and data is None:
718
+ empty_text.warning(
719
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
720
+ )
721
+ else:
722
+ empty_text.text("Computing... Please wait...")
723
+
724
+ geemap.goes_timelapse(
725
+ out_gif,
726
+ start_date=start,
727
+ end_date=end,
728
+ data=satellite,
729
+ scan=scan_type.replace(" ", "_").lower(),
730
+ region=roi,
731
+ dimensions=768,
732
+ framesPerSecond=speed,
733
+ date_format="YYYY-MM-dd HH:mm",
734
+ xy=("3%", "3%"),
735
+ text_sequence=None,
736
+ font_type="arial.ttf",
737
+ font_size=font_size,
738
+ font_color=font_color,
739
+ add_progress_bar=add_progress_bar,
740
+ progress_bar_color=progress_bar_color,
741
+ progress_bar_height=5,
742
+ loop=0,
743
+ overlay_data=overlay_data,
744
+ overlay_color=overlay_color,
745
+ overlay_width=overlay_width,
746
+ overlay_opacity=overlay_opacity,
747
+ mp4=mp4,
748
+ fading=fading,
749
+ )
750
+
751
+ if out_gif is not None and os.path.exists(out_gif):
752
+ empty_text.text(
753
+ "Right click the GIF to save it to your computerπŸ‘‡"
754
+ )
755
+ empty_image.image(out_gif)
756
+
757
+ out_mp4 = out_gif.replace(".gif", ".mp4")
758
+ if mp4 and os.path.exists(out_mp4):
759
+ with empty_video:
760
+ st.text(
761
+ "Right click the MP4 to save it to your computerπŸ‘‡"
762
+ )
763
+ st.video(out_gif.replace(".gif", ".mp4"))
764
+
765
+ if add_fire:
766
+ out_fire_gif = geemap.temp_file_path(".gif")
767
+ empty_fire_text.text(
768
+ "Delineating Fire Hotspot... Please wait..."
769
+ )
770
+ geemap.goes_fire_timelapse(
771
+ out_fire_gif,
772
+ start_date=start,
773
+ end_date=end,
774
+ data=satellite,
775
+ scan=scan_type.replace(" ", "_").lower(),
776
+ region=roi,
777
+ dimensions=768,
778
+ framesPerSecond=speed,
779
+ date_format="YYYY-MM-dd HH:mm",
780
+ xy=("3%", "3%"),
781
+ text_sequence=None,
782
+ font_type="arial.ttf",
783
+ font_size=font_size,
784
+ font_color=font_color,
785
+ add_progress_bar=add_progress_bar,
786
+ progress_bar_color=progress_bar_color,
787
+ progress_bar_height=5,
788
+ loop=0,
789
+ )
790
+ if os.path.exists(out_fire_gif):
791
+ empty_fire_image.image(out_fire_gif)
792
+ else:
793
+ empty_text.text(
794
+ "Something went wrong, either the ROI is too big or there are no data available for the specified date range. Please try a smaller ROI or different date range."
795
+ )
796
+
797
+ elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":
798
+
799
+ video_empty.video("https://youtu.be/16fA2QORG4A")
800
+
801
+ satellite = st.selectbox("Select a satellite:", ["Terra", "Aqua"])
802
+ band = st.selectbox("Select a band:", ["NDVI", "EVI"])
803
+
804
+ with st.form("submit_modis_form"):
805
+
806
+ roi = None
807
+ if st.session_state.get("roi") is not None:
808
+ roi = st.session_state.get("roi")
809
+ out_gif = geemap.temp_file_path(".gif")
810
+
811
+ with st.expander("Customize timelapse"):
812
+
813
+ start = st.date_input(
814
+ "Select a start date:", datetime.date(2000, 2, 8)
815
+ )
816
+ end = st.date_input("Select an end date:", datetime.date.today())
817
+
818
+ start_date = start.strftime("%Y-%m-%d")
819
+ end_date = end.strftime("%Y-%m-%d")
820
+
821
+ speed = st.slider("Frames per second:", 1, 30, 5)
822
+ add_progress_bar = st.checkbox("Add a progress bar", True)
823
+ progress_bar_color = st.color_picker(
824
+ "Progress bar color:", "#0000ff"
825
+ )
826
+ font_size = st.slider("Font size:", 10, 50, 20)
827
+ font_color = st.color_picker("Font color:", "#ffffff")
828
+
829
+ font_type = st.selectbox(
830
+ "Select the font type for the title:",
831
+ ["arial.ttf", "alibaba.otf"],
832
+ index=0,
833
+ )
834
+ fading = st.slider(
835
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
836
+ )
837
+ mp4 = st.checkbox("Save timelapse as MP4", True)
838
+
839
+ empty_text = st.empty()
840
+ empty_image = st.empty()
841
+ empty_video = st.container()
842
+
843
+ submitted = st.form_submit_button("Submit")
844
+ if submitted:
845
+ if sample_roi == "Uploaded GeoJSON" and data is None:
846
+ empty_text.warning(
847
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
848
+ )
849
+ else:
850
+
851
+ empty_text.text("Computing... Please wait...")
852
+
853
+ geemap.modis_ndvi_timelapse(
854
+ out_gif,
855
+ satellite,
856
+ band,
857
+ start_date,
858
+ end_date,
859
+ roi,
860
+ 768,
861
+ speed,
862
+ overlay_data=overlay_data,
863
+ overlay_color=overlay_color,
864
+ overlay_width=overlay_width,
865
+ overlay_opacity=overlay_opacity,
866
+ mp4=mp4,
867
+ fading=fading,
868
+ )
869
+
870
+ geemap.reduce_gif_size(out_gif)
871
+
872
+ empty_text.text(
873
+ "Right click the GIF to save it to your computerπŸ‘‡"
874
+ )
875
+ empty_image.image(out_gif)
876
+
877
+ out_mp4 = out_gif.replace(".gif", ".mp4")
878
+ if mp4 and os.path.exists(out_mp4):
879
+ with empty_video:
880
+ st.text(
881
+ "Right click the MP4 to save it to your computerπŸ‘‡"
882
+ )
883
+ st.video(out_gif.replace(".gif", ".mp4"))
884
+
885
+ elif collection == "Any Earth Engine ImageCollection":
886
+
887
+ with st.form("submit_ts_form"):
888
+ with st.expander("Customize timelapse"):
889
+
890
+ title = st.text_input(
891
+ "Enter a title to show on the timelapse: ", "Timelapse"
892
+ )
893
+ start_date = st.date_input(
894
+ "Select the start date:", datetime.date(2020, 1, 1)
895
+ )
896
+ end_date = st.date_input(
897
+ "Select the end date:", datetime.date.today()
898
+ )
899
+ frequency = st.selectbox(
900
+ "Select a temporal frequency:",
901
+ ["year", "quarter", "month", "day", "hour", "minute", "second"],
902
+ index=0,
903
+ )
904
+ reducer = st.selectbox(
905
+ "Select a reducer for aggregating data:",
906
+ ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
907
+ index=0,
908
+ )
909
+ data_format = st.selectbox(
910
+ "Select a date format to show on the timelapse:",
911
+ [
912
+ "YYYY-MM-dd",
913
+ "YYYY",
914
+ "YYMM-MM",
915
+ "YYYY-MM-dd HH:mm",
916
+ "YYYY-MM-dd HH:mm:ss",
917
+ "HH:mm",
918
+ "HH:mm:ss",
919
+ "w",
920
+ "M",
921
+ "d",
922
+ "D",
923
+ ],
924
+ index=0,
925
+ )
926
+
927
+ speed = st.slider("Frames per second:", 1, 30, 5)
928
+ add_progress_bar = st.checkbox("Add a progress bar", True)
929
+ progress_bar_color = st.color_picker(
930
+ "Progress bar color:", "#0000ff"
931
+ )
932
+ font_size = st.slider("Font size:", 10, 50, 30)
933
+ font_color = st.color_picker("Font color:", "#ffffff")
934
+ font_type = st.selectbox(
935
+ "Select the font type for the title:",
936
+ ["arial.ttf", "alibaba.otf"],
937
+ index=0,
938
+ )
939
+ fading = st.slider(
940
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
941
+ )
942
+ mp4 = st.checkbox("Save timelapse as MP4", True)
943
+
944
+ empty_text = st.empty()
945
+ empty_image = st.empty()
946
+ empty_video = st.container()
947
+ empty_fire_image = st.empty()
948
+
949
+ roi = None
950
+ if st.session_state.get("roi") is not None:
951
+ roi = st.session_state.get("roi")
952
+ out_gif = geemap.temp_file_path(".gif")
953
+
954
+ submitted = st.form_submit_button("Submit")
955
+ if submitted:
956
+
957
+ if sample_roi == "Uploaded GeoJSON" and data is None:
958
+ empty_text.warning(
959
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
960
+ )
961
+ else:
962
+
963
+ empty_text.text("Computing... Please wait...")
964
+ try:
965
+ geemap.create_timelapse(
966
+ st.session_state.get("ee_asset_id"),
967
+ start_date=start_date.strftime("%Y-%m-%d"),
968
+ end_date=end_date.strftime("%Y-%m-%d"),
969
+ region=roi,
970
+ frequency=frequency,
971
+ reducer=reducer,
972
+ date_format=data_format,
973
+ out_gif=out_gif,
974
+ bands=st.session_state.get("bands"),
975
+ palette=st.session_state.get("palette"),
976
+ vis_params=st.session_state.get("vis_params"),
977
+ dimensions=768,
978
+ frames_per_second=speed,
979
+ crs="EPSG:3857",
980
+ overlay_data=overlay_data,
981
+ overlay_color=overlay_color,
982
+ overlay_width=overlay_width,
983
+ overlay_opacity=overlay_opacity,
984
+ title=title,
985
+ title_xy=("2%", "90%"),
986
+ add_text=True,
987
+ text_xy=("2%", "2%"),
988
+ text_sequence=None,
989
+ font_type=font_type,
990
+ font_size=font_size,
991
+ font_color=font_color,
992
+ add_progress_bar=add_progress_bar,
993
+ progress_bar_color=progress_bar_color,
994
+ progress_bar_height=5,
995
+ loop=0,
996
+ mp4=mp4,
997
+ fading=fading,
998
+ )
999
+ except:
1000
+ empty_text.error(
1001
+ "An error occurred while computing the timelapse. You probably requested too much data. Try reducing the ROI or timespan."
1002
+ )
1003
+
1004
+ empty_text.text(
1005
+ "Right click the GIF to save it to your computerπŸ‘‡"
1006
+ )
1007
+ empty_image.image(out_gif)
1008
+
1009
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1010
+ if mp4 and os.path.exists(out_mp4):
1011
+ with empty_video:
1012
+ st.text(
1013
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1014
+ )
1015
+ st.video(out_gif.replace(".gif", ".mp4"))
1016
+
1017
+ elif collection in [
1018
+ "MODIS Gap filled Land Surface Temperature Daily",
1019
+ "MODIS Ocean Color SMI",
1020
+ ]:
1021
+
1022
+ with st.form("submit_ts_form"):
1023
+ with st.expander("Customize timelapse"):
1024
+
1025
+ title = st.text_input(
1026
+ "Enter a title to show on the timelapse: ",
1027
+ "Surface Temperature",
1028
+ )
1029
+ start_date = st.date_input(
1030
+ "Select the start date:", datetime.date(2018, 1, 1)
1031
+ )
1032
+ end_date = st.date_input(
1033
+ "Select the end date:", datetime.date(2020, 12, 31)
1034
+ )
1035
+ frequency = st.selectbox(
1036
+ "Select a temporal frequency:",
1037
+ ["year", "quarter", "month", "week", "day"],
1038
+ index=2,
1039
+ )
1040
+ reducer = st.selectbox(
1041
+ "Select a reducer for aggregating data:",
1042
+ ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
1043
+ index=0,
1044
+ )
1045
+
1046
+ vis_params = st.text_area(
1047
+ "Enter visualization parameters",
1048
+ "",
1049
+ help="Enter a string in the format of a dictionary, such as '{'min': 23, 'max': 32}'",
1050
+ )
1051
+
1052
+ speed = st.slider("Frames per second:", 1, 30, 5)
1053
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1054
+ progress_bar_color = st.color_picker(
1055
+ "Progress bar color:", "#0000ff"
1056
+ )
1057
+ font_size = st.slider("Font size:", 10, 50, 30)
1058
+ font_color = st.color_picker("Font color:", "#ffffff")
1059
+ font_type = st.selectbox(
1060
+ "Select the font type for the title:",
1061
+ ["arial.ttf", "alibaba.otf"],
1062
+ index=0,
1063
+ )
1064
+ add_colorbar = st.checkbox("Add a colorbar", True)
1065
+ colorbar_label = st.text_input(
1066
+ "Enter the colorbar label:", "Surface Temperature (Β°C)"
1067
+ )
1068
+ fading = st.slider(
1069
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1070
+ )
1071
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1072
+
1073
+ empty_text = st.empty()
1074
+ empty_image = st.empty()
1075
+ empty_video = st.container()
1076
+
1077
+ roi = None
1078
+ if st.session_state.get("roi") is not None:
1079
+ roi = st.session_state.get("roi")
1080
+ out_gif = geemap.temp_file_path(".gif")
1081
+
1082
+ submitted = st.form_submit_button("Submit")
1083
+ if submitted:
1084
+
1085
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1086
+ empty_text.warning(
1087
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1088
+ )
1089
+ else:
1090
+
1091
+ empty_text.text("Computing... Please wait...")
1092
+ try:
1093
+ if (
1094
+ collection
1095
+ == "MODIS Gap filled Land Surface Temperature Daily"
1096
+ ):
1097
+ out_gif = geemap.create_timelapse(
1098
+ st.session_state.get("ee_asset_id"),
1099
+ start_date=start_date.strftime("%Y-%m-%d"),
1100
+ end_date=end_date.strftime("%Y-%m-%d"),
1101
+ region=roi,
1102
+ bands=None,
1103
+ frequency=frequency,
1104
+ reducer=reducer,
1105
+ date_format=None,
1106
+ out_gif=out_gif,
1107
+ palette=st.session_state.get("palette"),
1108
+ vis_params=None,
1109
+ dimensions=768,
1110
+ frames_per_second=speed,
1111
+ crs="EPSG:3857",
1112
+ overlay_data=overlay_data,
1113
+ overlay_color=overlay_color,
1114
+ overlay_width=overlay_width,
1115
+ overlay_opacity=overlay_opacity,
1116
+ title=title,
1117
+ title_xy=("2%", "90%"),
1118
+ add_text=True,
1119
+ text_xy=("2%", "2%"),
1120
+ text_sequence=None,
1121
+ font_type=font_type,
1122
+ font_size=font_size,
1123
+ font_color=font_color,
1124
+ add_progress_bar=add_progress_bar,
1125
+ progress_bar_color=progress_bar_color,
1126
+ progress_bar_height=5,
1127
+ add_colorbar=add_colorbar,
1128
+ colorbar_label=colorbar_label,
1129
+ loop=0,
1130
+ mp4=mp4,
1131
+ fading=fading,
1132
+ )
1133
+ elif collection == "MODIS Ocean Color SMI":
1134
+ if vis_params.startswith("{") and vis_params.endswith(
1135
+ "}"
1136
+ ):
1137
+ vis_params = eval(vis_params)
1138
+ else:
1139
+ vis_params = None
1140
+ out_gif = geemap.modis_ocean_color_timelapse(
1141
+ st.session_state.get("ee_asset_id"),
1142
+ start_date=start_date.strftime("%Y-%m-%d"),
1143
+ end_date=end_date.strftime("%Y-%m-%d"),
1144
+ region=roi,
1145
+ bands=st.session_state["band"],
1146
+ frequency=frequency,
1147
+ reducer=reducer,
1148
+ date_format=None,
1149
+ out_gif=out_gif,
1150
+ palette=st.session_state.get("palette"),
1151
+ vis_params=vis_params,
1152
+ dimensions=768,
1153
+ frames_per_second=speed,
1154
+ crs="EPSG:3857",
1155
+ overlay_data=overlay_data,
1156
+ overlay_color=overlay_color,
1157
+ overlay_width=overlay_width,
1158
+ overlay_opacity=overlay_opacity,
1159
+ title=title,
1160
+ title_xy=("2%", "90%"),
1161
+ add_text=True,
1162
+ text_xy=("2%", "2%"),
1163
+ text_sequence=None,
1164
+ font_type=font_type,
1165
+ font_size=font_size,
1166
+ font_color=font_color,
1167
+ add_progress_bar=add_progress_bar,
1168
+ progress_bar_color=progress_bar_color,
1169
+ progress_bar_height=5,
1170
+ add_colorbar=add_colorbar,
1171
+ colorbar_label=colorbar_label,
1172
+ loop=0,
1173
+ mp4=mp4,
1174
+ fading=fading,
1175
+ )
1176
+ except:
1177
+ empty_text.error(
1178
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
1179
+ )
1180
+
1181
+ if out_gif is not None and os.path.exists(out_gif):
1182
+
1183
+ geemap.reduce_gif_size(out_gif)
1184
+
1185
+ empty_text.text(
1186
+ "Right click the GIF to save it to your computerπŸ‘‡"
1187
+ )
1188
+ empty_image.image(out_gif)
1189
+
1190
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1191
+ if mp4 and os.path.exists(out_mp4):
1192
+ with empty_video:
1193
+ st.text(
1194
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1195
+ )
1196
+ st.video(out_gif.replace(".gif", ".mp4"))
1197
+
1198
+ else:
1199
+ st.error(
1200
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
1201
+ )
1202
+
1203
+ elif collection == "USDA National Agriculture Imagery Program (NAIP)":
1204
+
1205
+ with st.form("submit_naip_form"):
1206
+ with st.expander("Customize timelapse"):
1207
+
1208
+ title = st.text_input(
1209
+ "Enter a title to show on the timelapse: ", "NAIP Timelapse"
1210
+ )
1211
+
1212
+ years = st.slider(
1213
+ "Start and end year:",
1214
+ 2003,
1215
+ today.year,
1216
+ (2003, today.year),
1217
+ )
1218
+
1219
+ bands = st.selectbox(
1220
+ "Select a band combination:", ["N/R/G", "R/G/B"], index=0
1221
+ )
1222
+
1223
+ speed = st.slider("Frames per second:", 1, 30, 3)
1224
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1225
+ progress_bar_color = st.color_picker(
1226
+ "Progress bar color:", "#0000ff"
1227
+ )
1228
+ font_size = st.slider("Font size:", 10, 50, 30)
1229
+ font_color = st.color_picker("Font color:", "#ffffff")
1230
+ font_type = st.selectbox(
1231
+ "Select the font type for the title:",
1232
+ ["arial.ttf", "alibaba.otf"],
1233
+ index=0,
1234
+ )
1235
+ fading = st.slider(
1236
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1237
+ )
1238
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1239
+
1240
+ empty_text = st.empty()
1241
+ empty_image = st.empty()
1242
+ empty_video = st.container()
1243
+ empty_fire_image = st.empty()
1244
+
1245
+ roi = None
1246
+ if st.session_state.get("roi") is not None:
1247
+ roi = st.session_state.get("roi")
1248
+ out_gif = geemap.temp_file_path(".gif")
1249
+
1250
+ submitted = st.form_submit_button("Submit")
1251
+ if submitted:
1252
+
1253
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1254
+ empty_text.warning(
1255
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1256
+ )
1257
+ else:
1258
+
1259
+ empty_text.text("Computing... Please wait...")
1260
+ try:
1261
+ geemap.naip_timelapse(
1262
+ roi,
1263
+ years[0],
1264
+ years[1],
1265
+ out_gif,
1266
+ bands=bands.split("/"),
1267
+ palette=st.session_state.get("palette"),
1268
+ vis_params=None,
1269
+ dimensions=768,
1270
+ frames_per_second=speed,
1271
+ crs="EPSG:3857",
1272
+ overlay_data=overlay_data,
1273
+ overlay_color=overlay_color,
1274
+ overlay_width=overlay_width,
1275
+ overlay_opacity=overlay_opacity,
1276
+ title=title,
1277
+ title_xy=("2%", "90%"),
1278
+ add_text=True,
1279
+ text_xy=("2%", "2%"),
1280
+ text_sequence=None,
1281
+ font_type=font_type,
1282
+ font_size=font_size,
1283
+ font_color=font_color,
1284
+ add_progress_bar=add_progress_bar,
1285
+ progress_bar_color=progress_bar_color,
1286
+ progress_bar_height=5,
1287
+ loop=0,
1288
+ mp4=mp4,
1289
+ fading=fading,
1290
+ )
1291
+ except:
1292
+ empty_text.error(
1293
+ "Something went wrong. You either requested too much data or the ROI is outside the U.S."
1294
+ )
1295
+
1296
+ if out_gif is not None and os.path.exists(out_gif):
1297
+
1298
+ empty_text.text(
1299
+ "Right click the GIF to save it to your computerπŸ‘‡"
1300
+ )
1301
+ empty_image.image(out_gif)
1302
+
1303
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1304
+ if mp4 and os.path.exists(out_mp4):
1305
+ with empty_video:
1306
+ st.text(
1307
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1308
+ )
1309
+ st.video(out_gif.replace(".gif", ".mp4"))
1310
+
1311
+ else:
1312
+ st.error(
1313
+ "Something went wrong. You either requested too much data or the ROI is outside the U.S."
1314
+ )
apps/vector.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import fiona
3
+ import geopandas as gpd
4
+ import streamlit as st
5
+
6
+
7
+ def save_uploaded_file(file_content, file_name):
8
+ """
9
+ Save the uploaded file to a temporary directory
10
+ """
11
+ import tempfile
12
+ import os
13
+ import uuid
14
+
15
+ _, file_extension = os.path.splitext(file_name)
16
+ file_id = str(uuid.uuid4())
17
+ file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_extension}")
18
+
19
+ with open(file_path, "wb") as file:
20
+ file.write(file_content.getbuffer())
21
+
22
+ return file_path
23
+
24
+
25
+ def app():
26
+
27
+ st.title("Upload Vector Data")
28
+
29
+ row1_col1, row1_col2 = st.columns([2, 1])
30
+ width = 950
31
+ height = 600
32
+
33
+ with row1_col2:
34
+
35
+ backend = st.selectbox(
36
+ "Select a plotting backend", ["folium", "kepler.gl", "pydeck"], index=2
37
+ )
38
+
39
+ if backend == "folium":
40
+ import leafmap.foliumap as leafmap
41
+ elif backend == "kepler.gl":
42
+ import leafmap.kepler as leafmap
43
+ elif backend == "pydeck":
44
+ import leafmap.deck as leafmap
45
+
46
+ url = st.text_input(
47
+ "Enter a URL to a vector dataset",
48
+ "https://github.com/giswqs/streamlit-geospatial/raw/master/data/us_states.geojson",
49
+ )
50
+
51
+ data = st.file_uploader(
52
+ "Upload a vector dataset", type=["geojson", "kml", "zip", "tab"]
53
+ )
54
+
55
+ container = st.container()
56
+
57
+ if data or url:
58
+ if data:
59
+ file_path = save_uploaded_file(data, data.name)
60
+ layer_name = os.path.splitext(data.name)[0]
61
+ elif url:
62
+ file_path = url
63
+ layer_name = url.split("/")[-1].split(".")[0]
64
+
65
+ with row1_col1:
66
+ if file_path.lower().endswith(".kml"):
67
+ fiona.drvsupport.supported_drivers["KML"] = "rw"
68
+ gdf = gpd.read_file(file_path, driver="KML")
69
+ else:
70
+ gdf = gpd.read_file(file_path)
71
+ lon, lat = leafmap.gdf_centroid(gdf)
72
+ if backend == "pydeck":
73
+
74
+ column_names = gdf.columns.values.tolist()
75
+ random_column = None
76
+ with container:
77
+ random_color = st.checkbox("Apply random colors", True)
78
+ if random_color:
79
+ random_column = st.selectbox(
80
+ "Select a column to apply random colors", column_names
81
+ )
82
+
83
+ m = leafmap.Map(center=(lat, lon))
84
+ m.add_gdf(gdf, random_color_column=random_column)
85
+ st.pydeck_chart(m)
86
+
87
+ else:
88
+ m = leafmap.Map(center=(lat, lon), draw_export=True)
89
+ m.add_gdf(gdf, layer_name=layer_name)
90
+ # m.add_vector(file_path, layer_name=layer_name)
91
+ if backend == "folium":
92
+ m.zoom_to_gdf(gdf)
93
+ m.to_streamlit(width=width, height=height)
94
+
95
+ else:
96
+ with row1_col1:
97
+ m = leafmap.Map()
98
+ st.pydeck_chart(m)
apps/wms.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import streamlit as st
3
+ import leafmap.foliumap as leafmap
4
+
5
+
6
+ @st.cache
7
+ def get_layers(url):
8
+ options = leafmap.get_wms_layers(url)
9
+ return options
10
+
11
+
12
+ def app():
13
+ st.title("Add Web Map Service (WMS)")
14
+ st.markdown(
15
+ """
16
+ This app is a demonstration of loading Web Map Service (WMS) layers. Simply enter the URL of the WMS service
17
+ in the text box below and press Enter to retrieve the layers. Go to https://apps.nationalmap.gov/services to find
18
+ some WMS URLs if needed.
19
+ """
20
+ )
21
+
22
+ row1_col1, row1_col2 = st.columns([3, 1.3])
23
+ width = 800
24
+ height = 600
25
+ layers = None
26
+
27
+ with row1_col2:
28
+
29
+ esa_landcover = "https://services.terrascope.be/wms/v2"
30
+ url = st.text_input(
31
+ "Enter a WMS URL:", value="https://services.terrascope.be/wms/v2"
32
+ )
33
+ empty = st.empty()
34
+
35
+ if url:
36
+ options = get_layers(url)
37
+
38
+ default = None
39
+ if url == esa_landcover:
40
+ default = "WORLDCOVER_2020_MAP"
41
+ layers = empty.multiselect(
42
+ "Select WMS layers to add to the map:", options, default=default
43
+ )
44
+ add_legend = st.checkbox("Add a legend to the map", value=True)
45
+ if default == "WORLDCOVER_2020_MAP":
46
+ legend = str(leafmap.builtin_legends["ESA_WorldCover"])
47
+ else:
48
+ legend = ""
49
+ if add_legend:
50
+ legend_text = st.text_area(
51
+ "Enter a legend as a dictionary {label: color}",
52
+ value=legend,
53
+ height=200,
54
+ )
55
+
56
+ with row1_col1:
57
+ m = leafmap.Map(center=(36.3, 0), zoom=2)
58
+
59
+ if layers is not None:
60
+ for layer in layers:
61
+ m.add_wms_layer(
62
+ url, layers=layer, name=layer, attribution=" ", transparent=True
63
+ )
64
+ if add_legend and legend_text:
65
+ legend_dict = ast.literal_eval(legend_text)
66
+ m.add_legend(legend_dict=legend_dict)
67
+
68
+ m.to_streamlit(width, height)
apps/xy.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import leafmap.foliumap as leafmap
2
+ import pandas as pd
3
+ import streamlit as st
4
+
5
+
6
+ def app():
7
+
8
+ st.title("Add Points from XY")
9
+
10
+ sample_url = "https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/world_cities.csv"
11
+ url = st.text_input("Enter URL:", sample_url)
12
+ m = leafmap.Map(locate_control=True, plugin_LatLngPopup=False)
13
+
14
+ if url:
15
+
16
+ try:
17
+ df = pd.read_csv(url)
18
+
19
+ columns = df.columns.values.tolist()
20
+ row1_col1, row1_col2, row1_col3, row1_col4, row1_col5 = st.columns(
21
+ [1, 1, 3, 1, 1]
22
+ )
23
+
24
+ lon_index = 0
25
+ lat_index = 0
26
+
27
+ for col in columns:
28
+ if col.lower() in ["lon", "longitude", "long", "lng"]:
29
+ lon_index = columns.index(col)
30
+ elif col.lower() in ["lat", "latitude"]:
31
+ lat_index = columns.index(col)
32
+
33
+ with row1_col1:
34
+ x = st.selectbox("Select longitude column", columns, lon_index)
35
+
36
+ with row1_col2:
37
+ y = st.selectbox("Select latitude column", columns, lat_index)
38
+
39
+ with row1_col3:
40
+ popups = st.multiselect("Select popup columns", columns, columns)
41
+
42
+ with row1_col4:
43
+ heatmap = st.checkbox("Add heatmap")
44
+
45
+ if heatmap:
46
+ with row1_col5:
47
+ if "pop_max" in columns:
48
+ index = columns.index("pop_max")
49
+ else:
50
+ index = 0
51
+ heatmap_col = st.selectbox("Select heatmap column", columns, index)
52
+ try:
53
+ m.add_heatmap(df, y, x, heatmap_col)
54
+ except:
55
+ st.error("Please select a numeric column")
56
+
57
+ try:
58
+ m.add_points_from_xy(df, x, y, popups)
59
+ except:
60
+ st.error("Please select a numeric column")
61
+
62
+ except Exception as e:
63
+ st.error(e)
64
+
65
+ m.to_streamlit()
data/cog_files.txt ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ https://www.maxar.com/open-data/california-colorado-fires
2
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif
3
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-08-18/pine-gulch-fire20/1040010041D3B300.tif
4
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-11-13/grizzly-creek-fire20/1040010045785200.tif
5
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-11-13/grizzly-creek-fire20/10400100443AEC00.tif
6
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-02-06/czu-lightning-complex-fire/104001004941E100.tif
7
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-02-18/cameron-peak-fire20/103001008DA5B500.tif
8
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-02-22/czu-lightning-complex-fire/103001008DB2E200.tif
9
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-04-01/grizzly-creek-fire20/104001004881EF00.tif
10
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-04-17/czu-lightning-complex-fire/103001008F905300.tif
11
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-04-17/czu-lightning-complex-fire/1030010092B22200.tif
12
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-06-27/czu-lightning-complex-fire/1030010094A52300.tif
13
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-09-08/czu-lightning-complex-fire/103001009C9FBB00.tif
14
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-09-24/lnu-lightning-complex-fire/103001009A079B00.tif
15
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-10-05/czu-lightning-complex-fire/103001009C10F800.tif
16
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-10-05/czu-lightning-complex-fire/103001009A266800.tif
17
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-11-04/czu-lightning-complex-fire/1050010019917900.tif
18
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-11-04/czu-lightning-complex-fire/1050010019917800.tif
19
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-11-18/czu-lightning-complex-fire/1050010019C2F600.tif
20
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-11-28/cameron-peak-fire20/103001009D72E000.tif
21
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-12-10/czu-lightning-complex-fire/105001001A3A8700.tif
22
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-12-28/lnu-lightning-complex-fire/10300100A1972700.tif
23
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2019-12-28/lnu-lightning-complex-fire/103001009F5D6B00.tif
24
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-01-15/cameron-peak-fire20/1040010057992100.tif
25
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-04-15/lnu-lightning-complex-fire/10300100A4B23600.tif
26
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-04-23/czu-lightning-complex-fire/10300100A589D100.tif
27
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-05-09/lnu-lightning-complex-fire/10300100A332EE00.tif
28
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-05-23/river-carmel-fires/10300100A77E9400.tif
29
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-05-23/river-carmel-fires/10300100A500A500.tif
30
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-05-24/river-carmel-fires/105001001D64E200.tif
31
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-06-27/lnu-lightning-complex-fire/10300100A8663800.tif
32
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-06-30/river-carmel-fires/10300100A9D60C00.tif
33
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-06-30/czu-lightning-complex-fire/10300100A8C66400.tif
34
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-06-30/czu-lightning-complex-fire/10300100A8892900.tif
35
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-07-11/czu-lightning-complex-fire/10300100AB381200.tif
36
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-07-11/czu-lightning-complex-fire/10300100AA180600.tif
37
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-07-13/pine-gulch-fire20/10300100AA57D700.tif
38
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-07-20/lnu-lightning-complex-fire/104001005C529000.tif
39
+ https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2020-07-28/pine-gulch-fire20/104001005DB06E00.tif
40
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-14/pine-gulch-fire20/10300100AAC8DD00.tif
41
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-16/pine-gulch-fire20/104001005D4A6100.tif
42
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-17/grizzly-creek-fire20/10300100ACCA3700.tif
43
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-17/cameron-peak-fire20/10300100AB4ED400.tif
44
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-20/swir-cog/104A0100606FFE00.tif
45
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-20/pine-gulch-fire20/10300100ACD06200.tif
46
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-20/pine-gulch-fire20/10300100AAD4A000.tif
47
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-20/pine-gulch-fire20/10300100AA293800.tif
48
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-20/lnu-lightning-complex-fire/10400100606FFE00.tif
49
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/river-carmel-fires/10300100ACBA2B00.tif
50
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/river-carmel-fires/10300100AA49F600.tif
51
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/lnu-lightning-complex-fire/104001005C1AC900.tif
52
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/river-carmel-fires/104001005F9F5300.tif
53
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/river-carmel-fires/104001005F453300.tif
54
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/river-carmel-fires/10300100ADC14400.tif
55
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-21/czu-lightning-complex-fire/104001005F43D400.tif
56
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-23/grizzly-creek-fire20/104001005FA09C00.tif
57
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-23/grizzly-creek-fire20/104001005DC71000.tif
58
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-26/river-carmel-fires/105001001F58F000.tif
59
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-26/lnu-lightning-complex-fire/10300100AC163A00.tif
60
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-29/river-carmel-fires/10300100AAD27500.tif
61
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-29/river-carmel-fires/10300100A9C75A00.tif
62
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-09-03/cameron-peak-fire20/1040010060188800.tif
63
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-09-03/cameron-peak-fire20/104001005F7E6500.tif
64
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-09-03/cameron-peak-fire20/10300100AE685A00.tif
65
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-09-04/cameron-peak-fire20/1040010060761C00.tif
66
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-05/cameron-peak-fire20/104001006113B700.tif
67
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-05/cameron-peak-fire20/10400100610CD400.tif
68
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-12/cameron-peak-fire20/1040010062B14C00.tif
69
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-12/cameron-peak-fire20/10400100626BFA00.tif
70
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-12/cameron-peak-fire20/10400100622A6600.tif
71
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-12/cameron-peak-fire20/10400100606B6300.tif
72
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-12/cameron-peak-fire20/104001005F908800.tif
73
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-15/cameron-peak-fire20/10500100205EDA00.tif
74
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-15/cameron-peak-fire20/10500100205ED900.tif
75
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-22/east-troublesome-fire20/10300100B0004A00.tif
76
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-22/east-troublesome-fire20/10300100AD0D1200.tif
77
+ https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-10-22/east-troublesome-fire20/10300100AD0CA600.tif
data/html/sfo_buildings.html ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <!-- Include the CesiumJS JavaScript and CSS files -->
6
+ <script src="https://cesium.com/downloads/cesiumjs/releases/1.88/Build/Cesium/Cesium.js"></script>
7
+ <link href="https://cesium.com/downloads/cesiumjs/releases/1.88/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
8
+ </head>
9
+ <body>
10
+ <div id="cesiumContainer"></div>
11
+ <script>
12
+ // Your access token can be found at: https://cesium.com/ion/tokens.
13
+ // Replace `your_access_token` with your Cesium ion access token.
14
+
15
+ Cesium.Ion.defaultAccessToken = 'your_access_token';
16
+
17
+ // Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
18
+ const viewer = new Cesium.Viewer('cesiumContainer', {
19
+ terrainProvider: Cesium.createWorldTerrain()
20
+ });
21
+ // Add Cesium OSM Buildings, a global 3D buildings layer.
22
+ const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());
23
+ // Fly the camera to San Francisco at the given longitude, latitude, and height.
24
+ viewer.camera.flyTo({
25
+ destination : Cesium.Cartesian3.fromDegrees(-122.4175, 37.655, 400),
26
+ orientation : {
27
+ heading : Cesium.Math.toRadians(0.0),
28
+ pitch : Cesium.Math.toRadians(-15.0),
29
+ }
30
+ });
31
+ </script>
32
+ </div>
33
+ </body>
34
+ </html>
data/realtor_data_dict.csv ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Name,Label,Description
2
+ median_listing_price,Median Listing Price,The median listing price within the specified geography during the specified month.
3
+ median_listing_price_mm,Median Listing Price M/M,The percentage change in the median listing price from the previous month.
4
+ median_listing_price_yy,Median Listing Price Y/Y,The percentage change in the median listing price from the same month in the previous year.
5
+ active_listing_count,Active Listing Count,"The count of active listings within the specified geography during the specified month. The active listing count tracks the number of for sale properties on the market, excluding pending listings where a pending status is available. This is a snapshot measure of how many active listings can be expected on any given day of the specified month."
6
+ active_listing_count_mm,Active Listing Count M/M,The percentage change in the active listing count from the previous month.
7
+ active_listing_count_yy,Active Listing Count Y/Y,The percentage change in the active listing count from the same month in the previous year.
8
+ median_days_on_market,Days on Market,The median number of days property listings spend on the market within the specified geography during the specified month. Time spent on the market is defined as the time between the initial listing of a property and either its closing date or the date it is taken off the market.
9
+ median_days_on_market_mm,Days on Market M/M,The percentage change in the median days on market from the previous month.
10
+ median_days_on_market_yy,Days on Market Y/Y,The percentage change in the median days on market from the same month in the previous year.
11
+ new_listing_count,New Listing Count,The count of new listings added to the market within the specified geography. The new listing count represents a typical week’s worth of new listings in a given month. The new listing count can be multiplied by the number of weeks in a month to produce a monthly new listing count.
12
+ new_listing_count_mm,New Listing Count M/M,The percentage change in the new listing count from the previous month.
13
+ new_listing_count_yy,New Listing Count Y/Y,The percentage change in the new listing count from the same month in the previous year.
14
+ price_increased_count,Price Increase Count,The count of listings which have had their price increased within the specified geography. The price increase count represents a typical week’s worth of listings which have had their price increased in a given month. The price increase count can be multiplied by the number of weeks in a month to produce a monthly price increase count.
15
+ price_increased_count_mm,Price Increase Count M/M,The percentage change in the price increase count from the previous month.
16
+ price_increased_count_yy,Price Increase Count Y/Y,The percentage change in the price increase count from the same month in the previous year.
17
+ price_reduced_count,Price Decrease Count,The count of listings which have had their price reduced within the specified geography. The price decrease count represents a typical week’s worth of listings which have had their price reduced in a given month. The price decrease count can be multiplied by the number of weeks in a month to produce a monthly price decrease count.
18
+ price_reduced_count_mm,Price Decrease Count M/M,The percentage change in the price decrease count from the previous month.
19
+ price_reduced_count_yy,Price Decrease Count Y/Y,The percentage change in the price decrease count from the same month in the previous year.
20
+ pending_listing_count,Pending Listing Count,"The count of pending listings within the specified geography during the specified month, if a pending definition is available for that geography. This is a snapshot measure of how many pending listings can be expected on any given day of the specified month."
21
+ pending_listing_count_mm,Pending Listing Count M/M,The percentage change in the pending listing count from the previous month.
22
+ pending_listing_count_yy,Pending Listing Count Y/Y,The percentage change in the pending listing count from the same month in the previous year.
23
+ median_listing_price_per_square_foot,Median List Price Per Sqft,The median listing price per square foot within the specified geography during the specified month.
24
+ median_listing_price_per_square_foot_mm,Median List Price Per Sqft M/M,The percentage change in the median listing price per square foot from the previous month.
25
+ median_listing_price_per_square_foot_yy,Median List Price Per Sqft Y/Y,The percentage change in the median listing price per square foot from the same month in the previous year.
26
+ median_square_feet,Median Listing Sqft,The median listing square feet within the specified geography during the specified month.
27
+ median_square_feet_mm,Median Listing Sqft M/M,The percentage change in the median listing square feet from the previous month.
28
+ median_square_feet_yy,Median Listing Sqft Y/Y,The percentage change in the median listing square feet from the same month in the previous year.
29
+ average_listing_price,Avg Listing Price,The average listing price within the specified geography during the specified month.
30
+ average_listing_price_mm,Avg Listing Price M/M,The percentage change in the average listing price from the previous month.
31
+ average_listing_price_yy,Avg Listing Price Y/Y,The percentage change in the average listing price from the same month in the previous year.
32
+ total_listing_count,Total Listing Count,The total of both active listings and pending listings within the specified geography during the specified month. This is a snapshot measure of how many total listings can be expected on any given day of the specified month.
33
+ total_listing_count_mm,Total Listing Count M/M,The percentage change in the total listing count from the previous month.
34
+ total_listing_count_yy,Total Listing Count Y/Y,The percentage change in the total listing count from the same month in the previous year.
35
+ pending_ratio,Pending Ratio,The ratio of the pending listing count to the active listing count within the specified geography during the specified month.
36
+ pending_ratio_mm,Pending Ratio M/M,The change in the pending ratio from the previous month.
37
+ pending_ratio_yy,Pending Ratio Y/Y,The change in the pending ratio from the same month in the previous year.
data/scotland_xyz.tsv ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Name URL
2
+ Ordnance Survey - Air Photos, 1944-1950 - 1:10,560 https://geo.nls.uk/maps/air-photos/{z}/{x}/{y}.png
3
+ Ordnance Survey - Six Inch Scotland, 1843-1882 - 1:10,560 https://mapseries-tilesets.s3.amazonaws.com/os/6inchfirst/{z}/{x}/{y}.png
4
+ War Office, Great Britain 1:25,000. GSGS 3906, 1940-43 https://mapseries-tilesets.s3.amazonaws.com/gsgs3906/{z}/{x}/{y}.png
5
+ Roy - Roy Highlands, 1747-1752 - 1:36000 https://mapseries-tilesets.s3.amazonaws.com/roy/highlands/{z}/{x}/{y}.png
6
+ Roy - Roy Lowlands, 1752-1755 - 1:36000 https://mapseries-tilesets.s3.amazonaws.com/roy/lowlands/{z}/{x}/{y}.png
7
+ Great Britain - OS 1:10,560, 1949-1970 https://mapseries-tilesets.s3.amazonaws.com/os/britain10knatgrid/{z}/{x}/{y}.png
8
+ Great Britain - Bartholomew Half Inch, 1897-1907 https://mapseries-tilesets.s3.amazonaws.com/bartholomew_great_britain/{z}/{x}/{y}.png
9
+ OS 25 inch, 1892-1914 - Scotland South https://mapseries-tilesets.s3.amazonaws.com/25_inch/scotland_1/{z}/{x}/{y}.png
10
+ OS 25 inch, 1892-1914 - Scotland North https://mapseries-tilesets.s3.amazonaws.com/25_inch/scotland_2/{z}/{x}/{y}.png
11
+ OS 25 inch, 1892-1914 - Bedfordshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/bedfordshire/{z}/{x}/{y}.png
12
+ OS 25 inch, 1892-1914 - Berkshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/berkshire/{z}/{x}/{y}.png
13
+ OS 25 inch, 1892-1914 - Buckinghamshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/buckingham/{z}/{x}/{y}.png
14
+ OS 25 inch, 1892-1914 - Cambridgeshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/cambridge/{z}/{x}/{y}.png
15
+ OS 25 inch, 1892-1914 - Cheshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/cheshire/{z}/{x}/{y}.png
16
+ OS 25 inch, 1892-1914 - Cornwall https://mapseries-tilesets.s3.amazonaws.com/25_inch/cornwall/{z}/{x}/{y}.png
17
+ OS 25 inch, 1892-1914 - Cumberland https://mapseries-tilesets.s3.amazonaws.com/25_inch/cumberland/{z}/{x}/{y}.png
18
+ OS 25 inch, 1892-1914 - Devon https://mapseries-tilesets.s3.amazonaws.com/25_inch/devon/{z}/{x}/{y}.png
19
+ OS 25 inch, 1892-1914 - Dorset https://mapseries-tilesets.s3.amazonaws.com/25_inch/dorset/{z}/{x}/{y}.png
20
+ OS 25 inch, 1892-1914 - Durham https://mapseries-tilesets.s3.amazonaws.com/25_inch/durham/{z}/{x}/{y}.png
21
+ OS 25 inch, 1892-1914 - Essex https://mapseries-tilesets.s3.amazonaws.com/25_inch/essex/{z}/{x}/{y}.png
22
+ OS 25 inch, 1892-1914 - Gloucestershire https://mapseries-tilesets.s3.amazonaws.com/25_inch/gloucestershire/{z}/{x}/{y}.png
23
+ OS 25 inch, 1892-1914 - Hampshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/hampshire/{z}/{x}/{y}.png
24
+ OS 25 inch, 1892-1914 - Herefordshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/herefordshire/{z}/{x}/{y}.png
25
+ OS 25 inch, 1892-1914 - Hertfordshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/hertfordshire/{z}/{x}/{y}.png
26
+ OS 25 inch, 1892-1914 - Huntingdon https://mapseries-tilesets.s3.amazonaws.com/25_inch/huntingdon/{z}/{x}/{y}.png
27
+ OS 25 inch, 1892-1914 - Kent https://mapseries-tilesets.s3.amazonaws.com/25_inch/kent/{z}/{x}/{y}.png
28
+ OS 25 inch, 1892-1914 - Lancashire https://mapseries-tilesets.s3.amazonaws.com/25_inch/lancashire/{z}/{x}/{y}.png
29
+ OS 25 inch, 1892-1914 - Leicestershire https://mapseries-tilesets.s3.amazonaws.com/25_inch/leicestershire/{z}/{x}/{y}.png
30
+ OS 25 inch, 1892-1914 - Lincolnshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/lincolnshire/{z}/{x}/{y}.png
31
+ OS 25 inch, 1892-1914 - London https://mapseries-tilesets.s3.amazonaws.com/25_inch/london/{z}/{x}/{y}.png
32
+ OS 25 inch, 1892-1914 - Middlesex https://mapseries-tilesets.s3.amazonaws.com/25_inch/middlesex/{z}/{x}/{y}.png
33
+ OS 25 inch, 1892-1914 - Norfolk https://mapseries-tilesets.s3.amazonaws.com/25_inch/norfolk/{z}/{x}/{y}.png
34
+ OS 25 inch, 1892-1914 - Northamptonshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/northampton/{z}/{x}/{y}.png
35
+ OS 25 inch, 1892-1914 - Northumberland https://mapseries-tilesets.s3.amazonaws.com/25_inch/northumberland/{z}/{x}/{y}.png
36
+ OS 25 inch, 1892-1914 - Nottinghamshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/nottinghamshire/{z}/{x}/{y}.png
37
+ OS 25 inch, 1892-1914 - Oxford https://mapseries-tilesets.s3.amazonaws.com/25_inch/oxford/{z}/{x}/{y}.png
38
+ OS 25 inch, 1892-1914 - Rutland https://mapseries-tilesets.s3.amazonaws.com/25_inch/rutland/{z}/{x}/{y}.png
39
+ OS 25 inch, 1892-1914 - Shropshire / Derbyshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/Shrop_Derby/{z}/{x}/{y}.png
40
+ OS 25 inch, 1892-1914 - Somerset https://mapseries-tilesets.s3.amazonaws.com/25_inch/somerset/{z}/{x}/{y}.png
41
+ OS 25 inch, 1892-1914 - Stafford https://mapseries-tilesets.s3.amazonaws.com/25_inch/stafford/{z}/{x}/{y}.png
42
+ OS 25 inch, 1892-1914 - Suffolk https://mapseries-tilesets.s3.amazonaws.com/25_inch/suffolk/{z}/{x}/{y}.png
43
+ OS 25 inch, 1892-1914 - Surrey https://mapseries-tilesets.s3.amazonaws.com/25_inch/surrey/{z}/{x}/{y}.png
44
+ OS 25 inch, 1892-1914 - Sussex https://mapseries-tilesets.s3.amazonaws.com/25_inch/sussex/{z}/{x}/{y}.png
45
+ OS 25 inch, 1892-1914 - Wales https://mapseries-tilesets.s3.amazonaws.com/25_inch/wales/{z}/{x}/{y}.png
46
+ OS 25 inch, 1892-1914 - Warwick https://mapseries-tilesets.s3.amazonaws.com/25_inch/warwick/{z}/{x}/{y}.png
47
+ OS 25 inch, 1892-1914 - Westmorland https://mapseries-tilesets.s3.amazonaws.com/25_inch/westmorland/{z}/{x}/{y}.png
48
+ OS 25 inch, 1892-1914 - Wiltshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/wiltshire2nd/{z}/{x}/{y}.png
49
+ OS 25 inch, 1892-1914 - Worcestershire https://mapseries-tilesets.s3.amazonaws.com/25_inch/Worcestershire/{z}/{x}/{y}.png
50
+ OS 25 inch, 1892-1914 - Yorkshire https://mapseries-tilesets.s3.amazonaws.com/25_inch/yorkshire/{z}/{x}/{y}.png
51
+ OS 25 inch, 1892-1914 'Holes' (fills gaps in series) https://geo.nls.uk/mapdata3/os/25_inch_holes_england/{z}/{x}/{y}.png
data/us_counties.geojson ADDED
The diff for this file is too large to render. See raw diff
 
data/us_metro_areas.geojson ADDED
The diff for this file is too large to render. See raw diff
 
data/us_nation.geojson ADDED
The diff for this file is too large to render. See raw diff
 
data/us_states.geojson ADDED
The diff for this file is too large to render. See raw diff
 
environment-bk.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: geo
2
+ channels:
3
+ - conda-forge
4
+ dependencies:
5
+ - gdal=3.4.3
6
+ - pip
7
+ - pip:
8
+ - geopandas
9
+ - keplergl
10
+ - streamlit
11
+ - localtileserver
12
+ - palettable
13
+ - streamlit-folium
14
+ - streamlit-keplergl
15
+ - streamlit-bokeh-events
16
+ - git+https://github.com/giswqs/leafmap
17
+ - git+https://github.com/giswqs/geemap
index.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Streamlit for Geospatial</title>
5
+ <style type="text/css">
6
+ html {
7
+ overflow: auto;
8
+ }
9
+ html,
10
+ body,
11
+ div,
12
+ iframe {
13
+ margin: 0px;
14
+ padding: 0px;
15
+ height: 100%;
16
+ border: none;
17
+ }
18
+ iframe {
19
+ display: block;
20
+ width: 100%;
21
+ border: none;
22
+ overflow-y: auto;
23
+ overflow-x: hidden;
24
+ }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <iframe
29
+ src="https://share.streamlit.io/giswqs/streamlit-geospatial/app.py"
30
+ frameborder="0"
31
+ marginheight="0"
32
+ marginwidth="0"
33
+ width="100%"
34
+ height="100%"
35
+ scrolling="auto"
36
+ >
37
+ </iframe>
38
+ </body>
39
+ </html>
multiapp.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frameworks for running multiple Streamlit applications as a single app.
2
+ """
3
+ import streamlit as st
4
+
5
+ # app_state = st.experimental_get_query_params()
6
+ # app_state = {k: v[0] if isinstance(v, list) else v for k, v in app_state.items()} # fetch the first item in each query string as we don't have multiple values for each query string key in this example
7
+
8
+
9
+ class MultiApp:
10
+ """Framework for combining multiple streamlit applications.
11
+ Usage:
12
+ def foo():
13
+ st.title("Hello Foo")
14
+ def bar():
15
+ st.title("Hello Bar")
16
+ app = MultiApp()
17
+ app.add_app("Foo", foo)
18
+ app.add_app("Bar", bar)
19
+ app.run()
20
+ It is also possible keep each application in a separate file.
21
+ import foo
22
+ import bar
23
+ app = MultiApp()
24
+ app.add_app("Foo", foo.app)
25
+ app.add_app("Bar", bar.app)
26
+ app.run()
27
+ """
28
+
29
+ def __init__(self):
30
+ self.apps = []
31
+
32
+ def add_app(self, title, func):
33
+ """Adds a new application.
34
+ Parameters
35
+ ----------
36
+ func:
37
+ the python function to render this app.
38
+ title:
39
+ title of the app. Appears in the dropdown in the sidebar.
40
+ """
41
+ self.apps.append({"title": title, "function": func})
42
+
43
+ def run(self):
44
+ app_state = st.experimental_get_query_params()
45
+ app_state = {
46
+ k: v[0] if isinstance(v, list) else v for k, v in app_state.items()
47
+ } # fetch the first item in each query string as we don't have multiple values for each query string key in this example
48
+
49
+ # st.write('before', app_state)
50
+
51
+ titles = [a["title"] for a in self.apps]
52
+ functions = [a["function"] for a in self.apps]
53
+ default_radio = titles.index(app_state["page"]) if "page" in app_state else 0
54
+
55
+ st.sidebar.title("Navigation")
56
+
57
+ title = st.sidebar.radio("Go To", titles, index=default_radio, key="radio")
58
+
59
+ app_state["page"] = st.session_state.radio
60
+ # st.write('after', app_state)
61
+
62
+ st.experimental_set_query_params(**app_state)
63
+ # st.experimental_set_query_params(**st.session_state.to_dict())
64
+ functions[titles.index(title)]()
65
+
66
+ st.sidebar.title("Contribute")
67
+ st.sidebar.info(
68
+ "This is an open source project and you are very welcome to contribute your "
69
+ "comments, questions, resources and apps as "
70
+ "[issues](https://github.com/giswqs/streamlit-geospatial/issues) or "
71
+ "[pull requests](https://github.com/giswqs/streamlit-geospatial/pulls) "
72
+ "to the [source code](https://github.com/giswqs/streamlit-geospatial). "
73
+ )
74
+ st.sidebar.title("About")
75
+ st.sidebar.info(
76
+ """
77
+ This web [app](https://share.streamlit.io/giswqs/streamlit-geospatial/app.py) is maintained by [Qiusheng Wu](https://wetlands.io). You can follow me on social media:
78
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu).
79
+ This web app URL: <https://streamlit.geemap.org>
80
+ """
81
+ )
packages.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ gifsicle
3
+ build-essential
4
+ python3-dev
5
+ gdal-bin
6
+ libgdal-dev
7
+ libproj-dev
8
+ libgeos-dev
9
+ proj-bin
pages/10_🌍_Earth_Engine_Datasets.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import streamlit as st
3
+ import geemap.foliumap as geemap
4
+
5
+ st.set_page_config(layout="wide")
6
+
7
+ st.sidebar.title("About")
8
+ st.sidebar.info(
9
+ """
10
+ Web App URL: <https://geospatial.streamlitapp.com>
11
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
12
+ """
13
+ )
14
+
15
+ st.sidebar.title("Contact")
16
+ st.sidebar.info(
17
+ """
18
+ Qiusheng Wu: <https://wetlands.io>
19
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
20
+ """
21
+ )
22
+
23
+
24
+ def nlcd():
25
+
26
+ # st.header("National Land Cover Database (NLCD)")
27
+
28
+ row1_col1, row1_col2 = st.columns([3, 1])
29
+ width = 950
30
+ height = 600
31
+
32
+ Map = geemap.Map(center=[40, -100], zoom=4)
33
+
34
+ # Select the seven NLCD epoches after 2000.
35
+ years = ["2001", "2004", "2006", "2008", "2011", "2013", "2016", "2019"]
36
+
37
+ # Get an NLCD image by year.
38
+ def getNLCD(year):
39
+ # Import the NLCD collection.
40
+ dataset = ee.ImageCollection("USGS/NLCD_RELEASES/2019_REL/NLCD")
41
+
42
+ # Filter the collection by year.
43
+ nlcd = dataset.filter(ee.Filter.eq("system:index", year)).first()
44
+
45
+ # Select the land cover band.
46
+ landcover = nlcd.select("landcover")
47
+ return landcover
48
+
49
+ with row1_col2:
50
+ selected_year = st.multiselect("Select a year", years)
51
+ add_legend = st.checkbox("Show legend")
52
+
53
+ if selected_year:
54
+ for year in selected_year:
55
+ Map.addLayer(getNLCD(year), {}, "NLCD " + year)
56
+
57
+ if add_legend:
58
+ Map.add_legend(
59
+ legend_title="NLCD Land Cover Classification", builtin_legend="NLCD"
60
+ )
61
+ with row1_col1:
62
+ Map.to_streamlit(width=width, height=height)
63
+
64
+ else:
65
+ with row1_col1:
66
+ Map.to_streamlit(width=width, height=height)
67
+
68
+
69
+ def search_data():
70
+
71
+ # st.header("Search Earth Engine Data Catalog")
72
+
73
+ Map = geemap.Map()
74
+
75
+ if "ee_assets" not in st.session_state:
76
+ st.session_state["ee_assets"] = None
77
+ if "asset_titles" not in st.session_state:
78
+ st.session_state["asset_titles"] = None
79
+
80
+ col1, col2 = st.columns([2, 1])
81
+
82
+ dataset = None
83
+ with col2:
84
+ keyword = st.text_input(
85
+ "Enter a keyword to search (e.g., elevation)", "")
86
+ if keyword:
87
+ ee_assets = geemap.search_ee_data(keyword)
88
+ asset_titles = [x["title"] for x in ee_assets]
89
+ asset_types = [x["type"] for x in ee_assets]
90
+
91
+ translate = {
92
+ "image_collection": "ee.ImageCollection('",
93
+ "image": "ee.Image('",
94
+ "table": "ee.FeatureCollection('",
95
+ "table_collection": "ee.FeatureCollection('",
96
+ }
97
+
98
+ dataset = st.selectbox("Select a dataset", asset_titles)
99
+ if len(ee_assets) > 0:
100
+ st.session_state["ee_assets"] = ee_assets
101
+ st.session_state["asset_titles"] = asset_titles
102
+
103
+ if dataset is not None:
104
+ with st.expander("Show dataset details", True):
105
+ index = asset_titles.index(dataset)
106
+
107
+ html = geemap.ee_data_html(
108
+ st.session_state["ee_assets"][index])
109
+ html = html.replace("\n", "")
110
+ st.markdown(html, True)
111
+
112
+ ee_id = ee_assets[index]["id"]
113
+ uid = ee_assets[index]["uid"]
114
+ st.markdown(f"""**Earth Engine Snippet:** `{ee_id}`""")
115
+ ee_asset = f"{translate[asset_types[index]]}{ee_id}')"
116
+ vis_params = st.text_input(
117
+ "Enter visualization parameters as a dictionary", {}
118
+ )
119
+ layer_name = st.text_input("Enter a layer name", uid)
120
+ button = st.button("Add dataset to map")
121
+ if button:
122
+ vis = {}
123
+ try:
124
+ if vis_params.strip() == "":
125
+ # st.error("Please enter visualization parameters")
126
+ vis_params = "{}"
127
+ vis = eval(vis_params)
128
+ if not isinstance(vis, dict):
129
+ st.error(
130
+ "Visualization parameters must be a dictionary")
131
+ try:
132
+ Map.addLayer(eval(ee_asset), vis, layer_name)
133
+ except Exception as e:
134
+ st.error(f"Error adding layer: {e}")
135
+ except Exception as e:
136
+ st.error(f"Invalid visualization parameters: {e}")
137
+
138
+ with col1:
139
+ Map.to_streamlit()
140
+ else:
141
+ with col1:
142
+ Map.to_streamlit()
143
+
144
+
145
+ def app():
146
+ st.title("Earth Engine Data Catalog")
147
+
148
+ apps = ["Search Earth Engine Data Catalog",
149
+ "National Land Cover Database (NLCD)"]
150
+
151
+ selected_app = st.selectbox("Select an app", apps)
152
+
153
+ if selected_app == "National Land Cover Database (NLCD)":
154
+ nlcd()
155
+ elif selected_app == "Search Earth Engine Data Catalog":
156
+ search_data()
157
+
158
+
159
+ app()
pages/11_🧱_Ordnance_Survey.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import folium
2
+ import pandas as pd
3
+ import streamlit as st
4
+ import leafmap.foliumap as leafmap
5
+ import folium.plugins as plugins
6
+
7
+ st.set_page_config(layout="wide")
8
+
9
+ st.sidebar.title("About")
10
+ st.sidebar.info(
11
+ """
12
+ Web App URL: <https://geospatial.streamlitapp.com>
13
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
14
+ """
15
+ )
16
+
17
+ st.sidebar.title("Contact")
18
+ st.sidebar.info(
19
+ """
20
+ Qiusheng Wu: <https://wetlands.io>
21
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
22
+ """
23
+ )
24
+
25
+ st.title("National Library of Scotland XYZ Layers")
26
+ df = pd.read_csv("data/scotland_xyz.tsv", sep="\t")
27
+ basemaps = leafmap.basemaps
28
+ names = df["Name"].values.tolist() + list(basemaps.keys())
29
+ links = df["URL"].values.tolist() + list(basemaps.values())
30
+
31
+ col1, col2, col3, col4, col5, col6, col7 = st.columns([3, 3, 1, 1, 1, 1.5, 1.5])
32
+ with col1:
33
+ left_name = st.selectbox(
34
+ "Select the left layer",
35
+ names,
36
+ index=names.index("Great Britain - Bartholomew Half Inch, 1897-1907"),
37
+ )
38
+
39
+ with col2:
40
+ right_name = st.selectbox(
41
+ "Select the right layer",
42
+ names,
43
+ index=names.index("HYBRID"),
44
+ )
45
+
46
+ with col3:
47
+ # lat = st.slider('Latitude', -90.0, 90.0, 55.68, step=0.01)
48
+ lat = st.text_input("Latitude", " 55.68")
49
+
50
+ with col4:
51
+ # lon = st.slider('Longitude', -180.0, 180.0, -2.98, step=0.01)
52
+ lon = st.text_input("Longitude", "-2.98")
53
+
54
+ with col5:
55
+ # zoom = st.slider('Zoom', 1, 24, 6, step=1)
56
+ zoom = st.text_input("Zoom", "6")
57
+
58
+ with col6:
59
+ checkbox = st.checkbox("Add OS 25 inch")
60
+
61
+ # with col7:
62
+ with st.expander("Acknowledgements"):
63
+ markdown = """
64
+ The map tile access is by kind arrangement of the National Library of Scotland on the understanding that re-use is for personal purposes. They host most of the map layers except these:
65
+ - The Roy Maps are owned by the British Library.
66
+ - The Great Britain – OS maps 1:25,000, 1937-61 and One Inch 7th series, 1955-61 are hosted by MapTiler.
67
+
68
+ If you wish you use these layers within a website, or for a commercial or public purpose, please view the [National Library of Scotland Historic Maps Subscription API](https://maps.nls.uk/projects/subscription-api/) or contact them at maps@nls.uk.
69
+ """
70
+ st.markdown(markdown, unsafe_allow_html=True)
71
+
72
+ m = leafmap.Map(
73
+ center=[float(lat), float(lon)],
74
+ zoom=int(zoom),
75
+ locate_control=True,
76
+ draw_control=False,
77
+ measure_control=False,
78
+ )
79
+ measure = plugins.MeasureControl(position="bottomleft", active_color="orange")
80
+ measure.add_to(m)
81
+
82
+ if left_name in basemaps:
83
+ left_layer = basemaps[left_name]
84
+ else:
85
+ left_layer = folium.TileLayer(
86
+ tiles=links[names.index(left_name)],
87
+ name=left_name,
88
+ attr="National Library of Scotland",
89
+ overlay=True,
90
+ )
91
+
92
+ if right_name in basemaps:
93
+ right_layer = basemaps[right_name]
94
+ else:
95
+ right_layer = folium.TileLayer(
96
+ tiles=links[names.index(right_name)],
97
+ name=right_name,
98
+ attr="National Library of Scotland",
99
+ overlay=True,
100
+ )
101
+
102
+ if checkbox:
103
+ for index, name in enumerate(names):
104
+ if "OS 25 inch" in name:
105
+ m.add_tile_layer(
106
+ links[index], name, attribution="National Library of Scotland"
107
+ )
108
+
109
+ m.split_map(left_layer, right_layer)
110
+ m.to_streamlit(height=600)
pages/12_🌲_Land_Cover_Mapping.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import ee
3
+ import streamlit as st
4
+ import geemap.foliumap as geemap
5
+
6
+ st.set_page_config(layout="wide")
7
+
8
+ st.sidebar.title("About")
9
+ st.sidebar.info(
10
+ """
11
+ Web App URL: <https://geospatial.streamlitapp.com>
12
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
13
+ """
14
+ )
15
+
16
+ st.sidebar.title("Contact")
17
+ st.sidebar.info(
18
+ """
19
+ Qiusheng Wu: <https://wetlands.io>
20
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
21
+ """
22
+ )
23
+
24
+ st.title("Comparing Global Land Cover Maps")
25
+
26
+ col1, col2 = st.columns([4, 1])
27
+
28
+ Map = geemap.Map()
29
+ Map.add_basemap("ESA WorldCover 2020 S2 FCC")
30
+ Map.add_basemap("ESA WorldCover 2020 S2 TCC")
31
+ Map.add_basemap("HYBRID")
32
+
33
+ esa = ee.ImageCollection("ESA/WorldCover/v100").first()
34
+ esa_vis = {"bands": ["Map"]}
35
+
36
+
37
+ esri = ee.ImageCollection(
38
+ "projects/sat-io/open-datasets/landcover/ESRI_Global-LULC_10m"
39
+ ).mosaic()
40
+ esri_vis = {
41
+ "min": 1,
42
+ "max": 10,
43
+ "palette": [
44
+ "#1A5BAB",
45
+ "#358221",
46
+ "#A7D282",
47
+ "#87D19E",
48
+ "#FFDB5C",
49
+ "#EECFA8",
50
+ "#ED022A",
51
+ "#EDE9E4",
52
+ "#F2FAFF",
53
+ "#C8C8C8",
54
+ ],
55
+ }
56
+
57
+
58
+ markdown = """
59
+ - [Dynamic World Land Cover](https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_DYNAMICWORLD_V1?hl=en)
60
+ - [ESA Global Land Cover](https://developers.google.com/earth-engine/datasets/catalog/ESA_WorldCover_v100)
61
+ - [ESRI Global Land Cover](https://samapriya.github.io/awesome-gee-community-datasets/projects/esrilc2020)
62
+
63
+ """
64
+
65
+ with col2:
66
+
67
+ longitude = st.number_input("Longitude", -180.0, 180.0, -89.3998)
68
+ latitude = st.number_input("Latitude", -90.0, 90.0, 43.0886)
69
+ zoom = st.number_input("Zoom", 0, 20, 11)
70
+
71
+ Map.setCenter(longitude, latitude, zoom)
72
+
73
+ start = st.date_input("Start Date for Dynamic World", datetime.date(2020, 1, 1))
74
+ end = st.date_input("End Date for Dynamic World", datetime.date(2021, 1, 1))
75
+
76
+ start_date = start.strftime("%Y-%m-%d")
77
+ end_date = end.strftime("%Y-%m-%d")
78
+
79
+ region = ee.Geometry.BBox(-179, -89, 179, 89)
80
+ dw = geemap.dynamic_world(region, start_date, end_date, return_type="hillshade")
81
+
82
+ layers = {
83
+ "Dynamic World": geemap.ee_tile_layer(dw, {}, "Dynamic World Land Cover"),
84
+ "ESA Land Cover": geemap.ee_tile_layer(esa, esa_vis, "ESA Land Cover"),
85
+ "ESRI Land Cover": geemap.ee_tile_layer(esri, esri_vis, "ESRI Land Cover"),
86
+ }
87
+
88
+ options = list(layers.keys())
89
+ left = st.selectbox("Select a left layer", options, index=1)
90
+ right = st.selectbox("Select a right layer", options, index=0)
91
+
92
+ left_layer = layers[left]
93
+ right_layer = layers[right]
94
+
95
+ Map.split_map(left_layer, right_layer)
96
+
97
+ legend = st.selectbox("Select a legend", options, index=options.index(right))
98
+ if legend == "Dynamic World":
99
+ Map.add_legend(
100
+ title="Dynamic World Land Cover",
101
+ builtin_legend="Dynamic_World",
102
+ )
103
+ elif legend == "ESA Land Cover":
104
+ Map.add_legend(title="ESA Land Cover", builtin_legend="ESA_WorldCover")
105
+ elif legend == "ESRI Land Cover":
106
+ Map.add_legend(title="ESRI Land Cover", builtin_legend="ESRI_LandCover")
107
+
108
+ with st.expander("Data sources"):
109
+ st.markdown(markdown)
110
+
111
+
112
+ with col1:
113
+ Map.to_streamlit(height=750)
pages/13_🏘️_Global_Building_Footprints.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import geemap.foliumap as geemap
3
+ import geopandas as gpd
4
+ import streamlit as st
5
+
6
+ st.set_page_config(layout="wide")
7
+
8
+
9
+ @st.cache(persist=True)
10
+ def ee_authenticate(token_name="EARTHENGINE_TOKEN"):
11
+ geemap.ee_initialize(token_name=token_name)
12
+
13
+
14
+ st.sidebar.title("About")
15
+ st.sidebar.info(
16
+ """
17
+ Web App URL: <https://geospatial.streamlitapp.com>
18
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
19
+ """
20
+ )
21
+
22
+ st.sidebar.title("Contact")
23
+ st.sidebar.info(
24
+ """
25
+ Qiusheng Wu: <https://wetlands.io>
26
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
27
+ """
28
+ )
29
+
30
+ st.title("Global Building Footprints")
31
+
32
+ col1, col2 = st.columns([8, 2])
33
+
34
+
35
+ @st.cache(persist=True)
36
+ def read_data(url):
37
+ return gpd.read_file(url)
38
+
39
+
40
+ countries = 'https://github.com/giswqs/geemap/raw/master/examples/data/countries.geojson'
41
+ states = 'https://github.com/giswqs/geemap/raw/master/examples/data/us_states.json'
42
+
43
+ countries_gdf = read_data(countries)
44
+ states_gdf = read_data(states)
45
+
46
+ country_names = countries_gdf['NAME'].values.tolist()
47
+ country_names.remove('United States of America')
48
+ country_names.append('USA')
49
+ country_names.sort()
50
+ country_names = [name.replace('.', '').replace(' ', '_')
51
+ for name in country_names]
52
+
53
+ state_names = states_gdf['name'].values.tolist()
54
+
55
+ basemaps = list(geemap.basemaps)
56
+
57
+ Map = geemap.Map()
58
+
59
+ with col2:
60
+
61
+ basemap = st.selectbox("Select a basemap", basemaps,
62
+ index=basemaps.index('HYBRID'))
63
+ Map.add_basemap(basemap)
64
+
65
+ country = st.selectbox('Select a country', country_names,
66
+ index=country_names.index('USA'))
67
+
68
+ if country == 'USA':
69
+ state = st.selectbox('Select a state', state_names,
70
+ index=state_names.index('Florida'))
71
+ layer_name = state
72
+
73
+ try:
74
+ fc = ee.FeatureCollection(
75
+ f'projects/sat-io/open-datasets/MSBuildings/US/{state}')
76
+ except:
77
+ st.error('No data available for the selected state.')
78
+
79
+ else:
80
+ try:
81
+ fc = ee.FeatureCollection(
82
+ f'projects/sat-io/open-datasets/MSBuildings/{country}')
83
+ except:
84
+ st.error('No data available for the selected country.')
85
+
86
+ layer_name = country
87
+
88
+ color = st.color_picker('Select a color', '#FF5500')
89
+
90
+ style = {'fillColor': '00000000', 'color': color}
91
+
92
+ split = st.checkbox("Split-panel map")
93
+
94
+ if split:
95
+ left = geemap.ee_tile_layer(fc.style(**style), {}, 'Left')
96
+ right = left
97
+ Map.split_map(left, right)
98
+ else:
99
+ Map.addLayer(fc.style(**style), {}, layer_name)
100
+
101
+ Map.centerObject(fc.first(), zoom=16)
102
+
103
+ with st.expander("Data Sources"):
104
+ st.info(
105
+ """
106
+ [Microsoft Building Footprints](https://gee-community-catalog.org/projects/msbuildings/)
107
+ """
108
+ )
109
+
110
+
111
+ with col1:
112
+
113
+ Map.to_streamlit(height=1000)
pages/1_πŸ“·_Timelapse.py ADDED
@@ -0,0 +1,1529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ee
2
+ import os
3
+ import warnings
4
+ import datetime
5
+ import fiona
6
+ import geopandas as gpd
7
+ import folium
8
+ import streamlit as st
9
+ import geemap.colormaps as cm
10
+ import geemap.foliumap as geemap
11
+ from datetime import date
12
+ from shapely.geometry import Polygon
13
+
14
+ st.set_page_config(layout="wide")
15
+ warnings.filterwarnings("ignore")
16
+
17
+
18
+ @st.cache(persist=True)
19
+ def ee_authenticate(token_name="EARTHENGINE_TOKEN"):
20
+ geemap.ee_initialize(token_name=token_name)
21
+
22
+
23
+ st.sidebar.title("About")
24
+ st.sidebar.info(
25
+ """
26
+ Web App URL: <https://geospatial.streamlitapp.com>
27
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
28
+ """
29
+ )
30
+
31
+ st.sidebar.title("Contact")
32
+ st.sidebar.info(
33
+ """
34
+ Qiusheng Wu: <https://wetlands.io>
35
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
36
+ """
37
+ )
38
+
39
+ goes_rois = {
40
+ "Creek Fire, CA (2020-09-05)": {
41
+ "region": Polygon(
42
+ [
43
+ [-121.003418, 36.848857],
44
+ [-121.003418, 39.049052],
45
+ [-117.905273, 39.049052],
46
+ [-117.905273, 36.848857],
47
+ [-121.003418, 36.848857],
48
+ ]
49
+ ),
50
+ "start_time": "2020-09-05T15:00:00",
51
+ "end_time": "2020-09-06T02:00:00",
52
+ },
53
+ "Bomb Cyclone (2021-10-24)": {
54
+ "region": Polygon(
55
+ [
56
+ [-159.5954, 60.4088],
57
+ [-159.5954, 24.5178],
58
+ [-114.2438, 24.5178],
59
+ [-114.2438, 60.4088],
60
+ ]
61
+ ),
62
+ "start_time": "2021-10-24T14:00:00",
63
+ "end_time": "2021-10-25T01:00:00",
64
+ },
65
+ "Hunga Tonga Volcanic Eruption (2022-01-15)": {
66
+ "region": Polygon(
67
+ [
68
+ [-192.480469, -32.546813],
69
+ [-192.480469, -8.754795],
70
+ [-157.587891, -8.754795],
71
+ [-157.587891, -32.546813],
72
+ [-192.480469, -32.546813],
73
+ ]
74
+ ),
75
+ "start_time": "2022-01-15T03:00:00",
76
+ "end_time": "2022-01-15T07:00:00",
77
+ },
78
+ "Hunga Tonga Volcanic Eruption Closer Look (2022-01-15)": {
79
+ "region": Polygon(
80
+ [
81
+ [-178.901367, -22.958393],
82
+ [-178.901367, -17.85329],
83
+ [-171.452637, -17.85329],
84
+ [-171.452637, -22.958393],
85
+ [-178.901367, -22.958393],
86
+ ]
87
+ ),
88
+ "start_time": "2022-01-15T03:00:00",
89
+ "end_time": "2022-01-15T07:00:00",
90
+ },
91
+ }
92
+
93
+
94
+ landsat_rois = {
95
+ "Aral Sea": Polygon(
96
+ [
97
+ [57.667236, 43.834527],
98
+ [57.667236, 45.996962],
99
+ [61.12793, 45.996962],
100
+ [61.12793, 43.834527],
101
+ [57.667236, 43.834527],
102
+ ]
103
+ ),
104
+ "Dubai": Polygon(
105
+ [
106
+ [54.541626, 24.763044],
107
+ [54.541626, 25.427152],
108
+ [55.632019, 25.427152],
109
+ [55.632019, 24.763044],
110
+ [54.541626, 24.763044],
111
+ ]
112
+ ),
113
+ "Hong Kong International Airport": Polygon(
114
+ [
115
+ [113.825226, 22.198849],
116
+ [113.825226, 22.349758],
117
+ [114.085121, 22.349758],
118
+ [114.085121, 22.198849],
119
+ [113.825226, 22.198849],
120
+ ]
121
+ ),
122
+ "Las Vegas, NV": Polygon(
123
+ [
124
+ [-115.554199, 35.804449],
125
+ [-115.554199, 36.558188],
126
+ [-113.903503, 36.558188],
127
+ [-113.903503, 35.804449],
128
+ [-115.554199, 35.804449],
129
+ ]
130
+ ),
131
+ "Pucallpa, Peru": Polygon(
132
+ [
133
+ [-74.672699, -8.600032],
134
+ [-74.672699, -8.254983],
135
+ [-74.279938, -8.254983],
136
+ [-74.279938, -8.600032],
137
+ ]
138
+ ),
139
+ "Sierra Gorda, Chile": Polygon(
140
+ [
141
+ [-69.315491, -22.837104],
142
+ [-69.315491, -22.751488],
143
+ [-69.190006, -22.751488],
144
+ [-69.190006, -22.837104],
145
+ [-69.315491, -22.837104],
146
+ ]
147
+ ),
148
+ }
149
+
150
+ modis_rois = {
151
+ "World": Polygon(
152
+ [
153
+ [-171.210938, -57.136239],
154
+ [-171.210938, 79.997168],
155
+ [177.539063, 79.997168],
156
+ [177.539063, -57.136239],
157
+ [-171.210938, -57.136239],
158
+ ]
159
+ ),
160
+ "Africa": Polygon(
161
+ [
162
+ [-18.6983, 38.1446],
163
+ [-18.6983, -36.1630],
164
+ [52.2293, -36.1630],
165
+ [52.2293, 38.1446],
166
+ ]
167
+ ),
168
+ "USA": Polygon(
169
+ [
170
+ [-127.177734, 23.725012],
171
+ [-127.177734, 50.792047],
172
+ [-66.269531, 50.792047],
173
+ [-66.269531, 23.725012],
174
+ [-127.177734, 23.725012],
175
+ ]
176
+ ),
177
+ }
178
+
179
+ ocean_rois = {
180
+ "Gulf of Mexico": Polygon(
181
+ [
182
+ [-101.206055, 15.496032],
183
+ [-101.206055, 32.361403],
184
+ [-75.673828, 32.361403],
185
+ [-75.673828, 15.496032],
186
+ [-101.206055, 15.496032],
187
+ ]
188
+ ),
189
+ "North Atlantic Ocean": Polygon(
190
+ [
191
+ [-85.341797, 24.046464],
192
+ [-85.341797, 45.02695],
193
+ [-55.810547, 45.02695],
194
+ [-55.810547, 24.046464],
195
+ [-85.341797, 24.046464],
196
+ ]
197
+ ),
198
+ "World": Polygon(
199
+ [
200
+ [-171.210938, -57.136239],
201
+ [-171.210938, 79.997168],
202
+ [177.539063, 79.997168],
203
+ [177.539063, -57.136239],
204
+ [-171.210938, -57.136239],
205
+ ]
206
+ ),
207
+ }
208
+
209
+
210
+ @st.cache(allow_output_mutation=True)
211
+ def uploaded_file_to_gdf(data):
212
+ import tempfile
213
+ import os
214
+ import uuid
215
+
216
+ _, file_extension = os.path.splitext(data.name)
217
+ file_id = str(uuid.uuid4())
218
+ file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_extension}")
219
+
220
+ with open(file_path, "wb") as file:
221
+ file.write(data.getbuffer())
222
+
223
+ if file_path.lower().endswith(".kml"):
224
+ fiona.drvsupport.supported_drivers["KML"] = "rw"
225
+ gdf = gpd.read_file(file_path, driver="KML")
226
+ else:
227
+ gdf = gpd.read_file(file_path)
228
+
229
+ return gdf
230
+
231
+
232
+ def app():
233
+
234
+ today = date.today()
235
+
236
+ st.title("Create Satellite Timelapse")
237
+
238
+ st.markdown(
239
+ """
240
+ An interactive web app for creating [Landsat](https://developers.google.com/earth-engine/datasets/catalog/landsat)/[GOES](https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16) timelapse for any location around the globe.
241
+ The app was built using [streamlit](https://streamlit.io), [geemap](https://geemap.org), and [Google Earth Engine](https://earthengine.google.com). For more info, check out my streamlit [blog post](https://blog.streamlit.io/creating-satellite-timelapse-with-streamlit-and-earth-engine).
242
+ """
243
+ )
244
+
245
+ row1_col1, row1_col2 = st.columns([2, 1])
246
+
247
+ if st.session_state.get("zoom_level") is None:
248
+ st.session_state["zoom_level"] = 4
249
+
250
+ st.session_state["ee_asset_id"] = None
251
+ st.session_state["bands"] = None
252
+ st.session_state["palette"] = None
253
+ st.session_state["vis_params"] = None
254
+
255
+ with row1_col1:
256
+ ee_authenticate(token_name="EARTHENGINE_TOKEN")
257
+ m = geemap.Map(
258
+ basemap="HYBRID",
259
+ plugin_Draw=True,
260
+ Draw_export=True,
261
+ locate_control=True,
262
+ plugin_LatLngPopup=False,
263
+ )
264
+ m.add_basemap("ROADMAP")
265
+
266
+ with row1_col2:
267
+
268
+ keyword = st.text_input("Search for a location:", "")
269
+ if keyword:
270
+ locations = geemap.geocode(keyword)
271
+ if locations is not None and len(locations) > 0:
272
+ str_locations = [str(g)[1:-1] for g in locations]
273
+ location = st.selectbox("Select a location:", str_locations)
274
+ loc_index = str_locations.index(location)
275
+ selected_loc = locations[loc_index]
276
+ lat, lng = selected_loc.lat, selected_loc.lng
277
+ folium.Marker(location=[lat, lng], popup=location).add_to(m)
278
+ m.set_center(lng, lat, 12)
279
+ st.session_state["zoom_level"] = 12
280
+
281
+ collection = st.selectbox(
282
+ "Select a satellite image collection: ",
283
+ [
284
+ "Any Earth Engine ImageCollection",
285
+ "Landsat TM-ETM-OLI Surface Reflectance",
286
+ "Sentinel-2 MSI Surface Reflectance",
287
+ "Geostationary Operational Environmental Satellites (GOES)",
288
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
289
+ "MODIS Gap filled Land Surface Temperature Daily",
290
+ "MODIS Ocean Color SMI",
291
+ "USDA National Agriculture Imagery Program (NAIP)",
292
+ ],
293
+ index=1,
294
+ )
295
+
296
+ if collection in [
297
+ "Landsat TM-ETM-OLI Surface Reflectance",
298
+ "Sentinel-2 MSI Surface Reflectance",
299
+ ]:
300
+ roi_options = ["Uploaded GeoJSON"] + list(landsat_rois.keys())
301
+
302
+ elif collection == "Geostationary Operational Environmental Satellites (GOES)":
303
+ roi_options = ["Uploaded GeoJSON"] + list(goes_rois.keys())
304
+
305
+ elif collection in [
306
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
307
+ "MODIS Gap filled Land Surface Temperature Daily",
308
+ ]:
309
+ roi_options = ["Uploaded GeoJSON"] + list(modis_rois.keys())
310
+ elif collection == "MODIS Ocean Color SMI":
311
+ roi_options = ["Uploaded GeoJSON"] + list(ocean_rois.keys())
312
+ else:
313
+ roi_options = ["Uploaded GeoJSON"]
314
+
315
+ if collection == "Any Earth Engine ImageCollection":
316
+ keyword = st.text_input("Enter a keyword to search (e.g., MODIS):", "")
317
+ if keyword:
318
+
319
+ assets = geemap.search_ee_data(keyword)
320
+ ee_assets = []
321
+ for asset in assets:
322
+ if asset["ee_id_snippet"].startswith("ee.ImageCollection"):
323
+ ee_assets.append(asset)
324
+
325
+ asset_titles = [x["title"] for x in ee_assets]
326
+ dataset = st.selectbox("Select a dataset:", asset_titles)
327
+ if len(ee_assets) > 0:
328
+ st.session_state["ee_assets"] = ee_assets
329
+ st.session_state["asset_titles"] = asset_titles
330
+ index = asset_titles.index(dataset)
331
+ ee_id = ee_assets[index]["id"]
332
+ else:
333
+ ee_id = ""
334
+
335
+ if dataset is not None:
336
+ with st.expander("Show dataset details", False):
337
+ index = asset_titles.index(dataset)
338
+ html = geemap.ee_data_html(st.session_state["ee_assets"][index])
339
+ st.markdown(html, True)
340
+ # elif collection == "MODIS Gap filled Land Surface Temperature Daily":
341
+ # ee_id = ""
342
+ else:
343
+ ee_id = ""
344
+
345
+ asset_id = st.text_input("Enter an ee.ImageCollection asset ID:", ee_id)
346
+
347
+ if asset_id:
348
+ with st.expander("Customize band combination and color palette", True):
349
+ try:
350
+ col = ee.ImageCollection.load(asset_id)
351
+ st.session_state["ee_asset_id"] = asset_id
352
+ except:
353
+ st.error("Invalid Earth Engine asset ID.")
354
+ st.session_state["ee_asset_id"] = None
355
+ return
356
+
357
+ img_bands = col.first().bandNames().getInfo()
358
+ if len(img_bands) >= 3:
359
+ default_bands = img_bands[:3][::-1]
360
+ else:
361
+ default_bands = img_bands[:]
362
+ bands = st.multiselect(
363
+ "Select one or three bands (RGB):", img_bands, default_bands
364
+ )
365
+ st.session_state["bands"] = bands
366
+
367
+ if len(bands) == 1:
368
+ palette_options = st.selectbox(
369
+ "Color palette",
370
+ cm.list_colormaps(),
371
+ index=2,
372
+ )
373
+ palette_values = cm.get_palette(palette_options, 15)
374
+ palette = st.text_area(
375
+ "Enter a custom palette:",
376
+ palette_values,
377
+ )
378
+ st.write(
379
+ cm.plot_colormap(cmap=palette_options, return_fig=True)
380
+ )
381
+ st.session_state["palette"] = eval(palette)
382
+
383
+ if bands:
384
+ vis_params = st.text_area(
385
+ "Enter visualization parameters",
386
+ "{'bands': ["
387
+ + ", ".join([f"'{band}'" for band in bands])
388
+ + "]}",
389
+ )
390
+ else:
391
+ vis_params = st.text_area(
392
+ "Enter visualization parameters",
393
+ "{}",
394
+ )
395
+ try:
396
+ st.session_state["vis_params"] = eval(vis_params)
397
+ st.session_state["vis_params"]["palette"] = st.session_state[
398
+ "palette"
399
+ ]
400
+ except Exception as e:
401
+ st.session_state["vis_params"] = None
402
+ st.error(
403
+ f"Invalid visualization parameters. It must be a dictionary."
404
+ )
405
+
406
+ elif collection == "MODIS Gap filled Land Surface Temperature Daily":
407
+ with st.expander("Show dataset details", False):
408
+ st.markdown(
409
+ """
410
+ See the [Awesome GEE Community Datasets](https://samapriya.github.io/awesome-gee-community-datasets/projects/daily_lst/).
411
+ """
412
+ )
413
+
414
+ MODIS_options = ["Daytime (1:30 pm)", "Nighttime (1:30 am)"]
415
+ MODIS_option = st.selectbox("Select a MODIS dataset:", MODIS_options)
416
+ if MODIS_option == "Daytime (1:30 pm)":
417
+ st.session_state[
418
+ "ee_asset_id"
419
+ ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
420
+ else:
421
+ st.session_state[
422
+ "ee_asset_id"
423
+ ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"
424
+
425
+ palette_options = st.selectbox(
426
+ "Color palette",
427
+ cm.list_colormaps(),
428
+ index=90,
429
+ )
430
+ palette_values = cm.get_palette(palette_options, 15)
431
+ palette = st.text_area(
432
+ "Enter a custom palette:",
433
+ palette_values,
434
+ )
435
+ st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
436
+ st.session_state["palette"] = eval(palette)
437
+ elif collection == "MODIS Ocean Color SMI":
438
+ with st.expander("Show dataset details", False):
439
+ st.markdown(
440
+ """
441
+ See the [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI).
442
+ """
443
+ )
444
+
445
+ MODIS_options = ["Aqua", "Terra"]
446
+ MODIS_option = st.selectbox("Select a satellite:", MODIS_options)
447
+ st.session_state["ee_asset_id"] = MODIS_option
448
+ # if MODIS_option == "Daytime (1:30 pm)":
449
+ # st.session_state[
450
+ # "ee_asset_id"
451
+ # ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
452
+ # else:
453
+ # st.session_state[
454
+ # "ee_asset_id"
455
+ # ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"
456
+
457
+ band_dict = {
458
+ "Chlorophyll a concentration": "chlor_a",
459
+ "Normalized fluorescence line height": "nflh",
460
+ "Particulate organic carbon": "poc",
461
+ "Sea surface temperature": "sst",
462
+ "Remote sensing reflectance at band 412nm": "Rrs_412",
463
+ "Remote sensing reflectance at band 443nm": "Rrs_443",
464
+ "Remote sensing reflectance at band 469nm": "Rrs_469",
465
+ "Remote sensing reflectance at band 488nm": "Rrs_488",
466
+ "Remote sensing reflectance at band 531nm": "Rrs_531",
467
+ "Remote sensing reflectance at band 547nm": "Rrs_547",
468
+ "Remote sensing reflectance at band 555nm": "Rrs_555",
469
+ "Remote sensing reflectance at band 645nm": "Rrs_645",
470
+ "Remote sensing reflectance at band 667nm": "Rrs_667",
471
+ "Remote sensing reflectance at band 678nm": "Rrs_678",
472
+ }
473
+
474
+ band_options = list(band_dict.keys())
475
+ band = st.selectbox(
476
+ "Select a band",
477
+ band_options,
478
+ band_options.index("Sea surface temperature"),
479
+ )
480
+ st.session_state["band"] = band_dict[band]
481
+
482
+ colors = cm.list_colormaps()
483
+ palette_options = st.selectbox(
484
+ "Color palette",
485
+ colors,
486
+ index=colors.index("coolwarm"),
487
+ )
488
+ palette_values = cm.get_palette(palette_options, 15)
489
+ palette = st.text_area(
490
+ "Enter a custom palette:",
491
+ palette_values,
492
+ )
493
+ st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
494
+ st.session_state["palette"] = eval(palette)
495
+
496
+ sample_roi = st.selectbox(
497
+ "Select a sample ROI or upload a GeoJSON file:",
498
+ roi_options,
499
+ index=0,
500
+ )
501
+
502
+ add_outline = st.checkbox(
503
+ "Overlay an administrative boundary on timelapse", False
504
+ )
505
+
506
+ if add_outline:
507
+
508
+ with st.expander("Customize administrative boundary", True):
509
+
510
+ overlay_options = {
511
+ "User-defined": None,
512
+ "Continents": "continents",
513
+ "Countries": "countries",
514
+ "US States": "us_states",
515
+ "China": "china",
516
+ }
517
+
518
+ overlay = st.selectbox(
519
+ "Select an administrative boundary:",
520
+ list(overlay_options.keys()),
521
+ index=2,
522
+ )
523
+
524
+ overlay_data = overlay_options[overlay]
525
+
526
+ if overlay_data is None:
527
+ overlay_data = st.text_input(
528
+ "Enter an HTTP URL to a GeoJSON file or an ee.FeatureCollection asset id:",
529
+ "https://raw.githubusercontent.com/giswqs/geemap/master/examples/data/countries.geojson",
530
+ )
531
+
532
+ overlay_color = st.color_picker(
533
+ "Select a color for the administrative boundary:", "#000000"
534
+ )
535
+ overlay_width = st.slider(
536
+ "Select a line width for the administrative boundary:", 1, 20, 1
537
+ )
538
+ overlay_opacity = st.slider(
539
+ "Select an opacity for the administrative boundary:",
540
+ 0.0,
541
+ 1.0,
542
+ 1.0,
543
+ 0.05,
544
+ )
545
+ else:
546
+ overlay_data = None
547
+ overlay_color = "black"
548
+ overlay_width = 1
549
+ overlay_opacity = 1
550
+
551
+ with row1_col1:
552
+
553
+ with st.expander(
554
+ "Steps: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Expand this tab to see a demo πŸ‘‰"
555
+ ):
556
+ video_empty = st.empty()
557
+
558
+ data = st.file_uploader(
559
+ "Upload a GeoJSON file to use as an ROI. Customize timelapse parameters and then click the Submit button πŸ˜‡πŸ‘‡",
560
+ type=["geojson", "kml", "zip"],
561
+ )
562
+
563
+ crs = "epsg:4326"
564
+ if sample_roi == "Uploaded GeoJSON":
565
+ if data is None:
566
+ # st.info(
567
+ # "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click Submit button"
568
+ # )
569
+ if collection in [
570
+ "Geostationary Operational Environmental Satellites (GOES)",
571
+ "USDA National Agriculture Imagery Program (NAIP)",
572
+ ] and (not keyword):
573
+ m.set_center(-100, 40, 3)
574
+ # else:
575
+ # m.set_center(4.20, 18.63, zoom=2)
576
+ else:
577
+ if collection in [
578
+ "Landsat TM-ETM-OLI Surface Reflectance",
579
+ "Sentinel-2 MSI Surface Reflectance",
580
+ ]:
581
+ gdf = gpd.GeoDataFrame(
582
+ index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
583
+ )
584
+ elif (
585
+ collection
586
+ == "Geostationary Operational Environmental Satellites (GOES)"
587
+ ):
588
+ gdf = gpd.GeoDataFrame(
589
+ index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
590
+ )
591
+ elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":
592
+ gdf = gpd.GeoDataFrame(
593
+ index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
594
+ )
595
+
596
+ if sample_roi != "Uploaded GeoJSON":
597
+
598
+ if collection in [
599
+ "Landsat TM-ETM-OLI Surface Reflectance",
600
+ "Sentinel-2 MSI Surface Reflectance",
601
+ ]:
602
+ gdf = gpd.GeoDataFrame(
603
+ index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
604
+ )
605
+ elif (
606
+ collection
607
+ == "Geostationary Operational Environmental Satellites (GOES)"
608
+ ):
609
+ gdf = gpd.GeoDataFrame(
610
+ index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
611
+ )
612
+ elif collection in [
613
+ "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
614
+ "MODIS Gap filled Land Surface Temperature Daily",
615
+ ]:
616
+ gdf = gpd.GeoDataFrame(
617
+ index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
618
+ )
619
+ elif collection == "MODIS Ocean Color SMI":
620
+ gdf = gpd.GeoDataFrame(
621
+ index=[0], crs=crs, geometry=[ocean_rois[sample_roi]]
622
+ )
623
+ try:
624
+ st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
625
+ except Exception as e:
626
+ st.error(e)
627
+ st.error("Please draw another ROI and try again.")
628
+ return
629
+ m.add_gdf(gdf, "ROI")
630
+
631
+ elif data:
632
+ gdf = uploaded_file_to_gdf(data)
633
+ try:
634
+ st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
635
+ m.add_gdf(gdf, "ROI")
636
+ except Exception as e:
637
+ st.error(e)
638
+ st.error("Please draw another ROI and try again.")
639
+ return
640
+
641
+ m.to_streamlit(height=600)
642
+
643
+ with row1_col2:
644
+
645
+ if collection in [
646
+ "Landsat TM-ETM-OLI Surface Reflectance",
647
+ "Sentinel-2 MSI Surface Reflectance",
648
+ ]:
649
+
650
+ if collection == "Landsat TM-ETM-OLI Surface Reflectance":
651
+ sensor_start_year = 1984
652
+ timelapse_title = "Landsat Timelapse"
653
+ timelapse_speed = 5
654
+ elif collection == "Sentinel-2 MSI Surface Reflectance":
655
+ sensor_start_year = 2015
656
+ timelapse_title = "Sentinel-2 Timelapse"
657
+ timelapse_speed = 5
658
+ video_empty.video("https://youtu.be/VVRK_-dEjR4")
659
+
660
+ with st.form("submit_landsat_form"):
661
+
662
+ roi = None
663
+ if st.session_state.get("roi") is not None:
664
+ roi = st.session_state.get("roi")
665
+ out_gif = geemap.temp_file_path(".gif")
666
+
667
+ title = st.text_input(
668
+ "Enter a title to show on the timelapse: ", timelapse_title
669
+ )
670
+ RGB = st.selectbox(
671
+ "Select an RGB band combination:",
672
+ [
673
+ "Red/Green/Blue",
674
+ "NIR/Red/Green",
675
+ "SWIR2/SWIR1/NIR",
676
+ "NIR/SWIR1/Red",
677
+ "SWIR2/NIR/Red",
678
+ "SWIR2/SWIR1/Red",
679
+ "SWIR1/NIR/Blue",
680
+ "NIR/SWIR1/Blue",
681
+ "SWIR2/NIR/Green",
682
+ "SWIR1/NIR/Red",
683
+ "SWIR2/NIR/SWIR1",
684
+ "SWIR1/NIR/SWIR2",
685
+ ],
686
+ index=9,
687
+ )
688
+
689
+ frequency = st.selectbox(
690
+ "Select a temporal frequency:",
691
+ ["year", "quarter", "month"],
692
+ index=0,
693
+ )
694
+
695
+ with st.expander("Customize timelapse"):
696
+
697
+ speed = st.slider("Frames per second:", 1, 30, timelapse_speed)
698
+ dimensions = st.slider(
699
+ "Maximum dimensions (Width*Height) in pixels", 768, 2000, 768
700
+ )
701
+ progress_bar_color = st.color_picker(
702
+ "Progress bar color:", "#0000ff"
703
+ )
704
+ years = st.slider(
705
+ "Start and end year:",
706
+ sensor_start_year,
707
+ today.year,
708
+ (sensor_start_year, today.year),
709
+ )
710
+ months = st.slider("Start and end month:", 1, 12, (1, 12))
711
+ font_size = st.slider("Font size:", 10, 50, 30)
712
+ font_color = st.color_picker("Font color:", "#ffffff")
713
+ apply_fmask = st.checkbox(
714
+ "Apply fmask (remove clouds, shadows, snow)", True
715
+ )
716
+ font_type = st.selectbox(
717
+ "Select the font type for the title:",
718
+ ["arial.ttf", "alibaba.otf"],
719
+ index=0,
720
+ )
721
+ fading = st.slider(
722
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
723
+ )
724
+ mp4 = st.checkbox("Save timelapse as MP4", True)
725
+
726
+ empty_text = st.empty()
727
+ empty_image = st.empty()
728
+ empty_fire_image = st.empty()
729
+ empty_video = st.container()
730
+ submitted = st.form_submit_button("Submit")
731
+ if submitted:
732
+
733
+ if sample_roi == "Uploaded GeoJSON" and data is None:
734
+ empty_text.warning(
735
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
736
+ )
737
+ else:
738
+
739
+ empty_text.text("Computing... Please wait...")
740
+
741
+ start_year = years[0]
742
+ end_year = years[1]
743
+ start_date = str(months[0]).zfill(2) + "-01"
744
+ end_date = str(months[1]).zfill(2) + "-30"
745
+ bands = RGB.split("/")
746
+
747
+ try:
748
+ if collection == "Landsat TM-ETM-OLI Surface Reflectance":
749
+ out_gif = geemap.landsat_timelapse(
750
+ roi=roi,
751
+ out_gif=out_gif,
752
+ start_year=start_year,
753
+ end_year=end_year,
754
+ start_date=start_date,
755
+ end_date=end_date,
756
+ bands=bands,
757
+ apply_fmask=apply_fmask,
758
+ frames_per_second=speed,
759
+ # dimensions=dimensions,
760
+ dimensions=768,
761
+ overlay_data=overlay_data,
762
+ overlay_color=overlay_color,
763
+ overlay_width=overlay_width,
764
+ overlay_opacity=overlay_opacity,
765
+ frequency=frequency,
766
+ date_format=None,
767
+ title=title,
768
+ title_xy=("2%", "90%"),
769
+ add_text=True,
770
+ text_xy=("2%", "2%"),
771
+ text_sequence=None,
772
+ font_type=font_type,
773
+ font_size=font_size,
774
+ font_color=font_color,
775
+ add_progress_bar=True,
776
+ progress_bar_color=progress_bar_color,
777
+ progress_bar_height=5,
778
+ loop=0,
779
+ mp4=mp4,
780
+ fading=fading,
781
+ )
782
+ elif collection == "Sentinel-2 MSI Surface Reflectance":
783
+ out_gif = geemap.sentinel2_timelapse(
784
+ roi=roi,
785
+ out_gif=out_gif,
786
+ start_year=start_year,
787
+ end_year=end_year,
788
+ start_date=start_date,
789
+ end_date=end_date,
790
+ bands=bands,
791
+ apply_fmask=apply_fmask,
792
+ frames_per_second=speed,
793
+ dimensions=768,
794
+ # dimensions=dimensions,
795
+ overlay_data=overlay_data,
796
+ overlay_color=overlay_color,
797
+ overlay_width=overlay_width,
798
+ overlay_opacity=overlay_opacity,
799
+ frequency=frequency,
800
+ date_format=None,
801
+ title=title,
802
+ title_xy=("2%", "90%"),
803
+ add_text=True,
804
+ text_xy=("2%", "2%"),
805
+ text_sequence=None,
806
+ font_type=font_type,
807
+ font_size=font_size,
808
+ font_color=font_color,
809
+ add_progress_bar=True,
810
+ progress_bar_color=progress_bar_color,
811
+ progress_bar_height=5,
812
+ loop=0,
813
+ mp4=mp4,
814
+ fading=fading,
815
+ )
816
+ except:
817
+ empty_text.error(
818
+ "An error occurred while computing the timelapse. Your probably requested too much data. Try reducing the ROI or timespan."
819
+ )
820
+ st.stop()
821
+
822
+ if out_gif is not None and os.path.exists(out_gif):
823
+
824
+ empty_text.text(
825
+ "Right click the GIF to save it to your computerπŸ‘‡"
826
+ )
827
+ empty_image.image(out_gif)
828
+
829
+ out_mp4 = out_gif.replace(".gif", ".mp4")
830
+ if mp4 and os.path.exists(out_mp4):
831
+ with empty_video:
832
+ st.text(
833
+ "Right click the MP4 to save it to your computerπŸ‘‡"
834
+ )
835
+ st.video(out_gif.replace(".gif", ".mp4"))
836
+
837
+ else:
838
+ empty_text.error(
839
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
840
+ )
841
+
842
+ elif collection == "Geostationary Operational Environmental Satellites (GOES)":
843
+
844
+ video_empty.video("https://youtu.be/16fA2QORG4A")
845
+
846
+ with st.form("submit_goes_form"):
847
+
848
+ roi = None
849
+ if st.session_state.get("roi") is not None:
850
+ roi = st.session_state.get("roi")
851
+ out_gif = geemap.temp_file_path(".gif")
852
+
853
+ satellite = st.selectbox("Select a satellite:", ["GOES-17", "GOES-16"])
854
+ earliest_date = datetime.date(2017, 7, 10)
855
+ latest_date = datetime.date.today()
856
+
857
+ if sample_roi == "Uploaded GeoJSON":
858
+ roi_start_date = today - datetime.timedelta(days=2)
859
+ roi_end_date = today - datetime.timedelta(days=1)
860
+ roi_start_time = datetime.time(14, 00)
861
+ roi_end_time = datetime.time(1, 00)
862
+ else:
863
+ roi_start = goes_rois[sample_roi]["start_time"]
864
+ roi_end = goes_rois[sample_roi]["end_time"]
865
+ roi_start_date = datetime.datetime.strptime(
866
+ roi_start[:10], "%Y-%m-%d"
867
+ )
868
+ roi_end_date = datetime.datetime.strptime(roi_end[:10], "%Y-%m-%d")
869
+ roi_start_time = datetime.time(
870
+ int(roi_start[11:13]), int(roi_start[14:16])
871
+ )
872
+ roi_end_time = datetime.time(
873
+ int(roi_end[11:13]), int(roi_end[14:16])
874
+ )
875
+
876
+ start_date = st.date_input("Select the start date:", roi_start_date)
877
+ end_date = st.date_input("Select the end date:", roi_end_date)
878
+
879
+ with st.expander("Customize timelapse"):
880
+
881
+ add_fire = st.checkbox("Add Fire/Hotspot Characterization", False)
882
+
883
+ scan_type = st.selectbox(
884
+ "Select a scan type:", ["Full Disk", "CONUS", "Mesoscale"]
885
+ )
886
+
887
+ start_time = st.time_input(
888
+ "Select the start time of the start date:", roi_start_time
889
+ )
890
+
891
+ end_time = st.time_input(
892
+ "Select the end time of the end date:", roi_end_time
893
+ )
894
+
895
+ start = (
896
+ start_date.strftime("%Y-%m-%d")
897
+ + "T"
898
+ + start_time.strftime("%H:%M:%S")
899
+ )
900
+ end = (
901
+ end_date.strftime("%Y-%m-%d")
902
+ + "T"
903
+ + end_time.strftime("%H:%M:%S")
904
+ )
905
+
906
+ speed = st.slider("Frames per second:", 1, 30, 5)
907
+ add_progress_bar = st.checkbox("Add a progress bar", True)
908
+ progress_bar_color = st.color_picker(
909
+ "Progress bar color:", "#0000ff"
910
+ )
911
+ font_size = st.slider("Font size:", 10, 50, 20)
912
+ font_color = st.color_picker("Font color:", "#ffffff")
913
+ fading = st.slider(
914
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
915
+ )
916
+ mp4 = st.checkbox("Save timelapse as MP4", True)
917
+
918
+ empty_text = st.empty()
919
+ empty_image = st.empty()
920
+ empty_video = st.container()
921
+ empty_fire_text = st.empty()
922
+ empty_fire_image = st.empty()
923
+
924
+ submitted = st.form_submit_button("Submit")
925
+ if submitted:
926
+ if sample_roi == "Uploaded GeoJSON" and data is None:
927
+ empty_text.warning(
928
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
929
+ )
930
+ else:
931
+ empty_text.text("Computing... Please wait...")
932
+
933
+ geemap.goes_timelapse(
934
+ roi,
935
+ out_gif,
936
+ start_date=start,
937
+ end_date=end,
938
+ data=satellite,
939
+ scan=scan_type.replace(" ", "_").lower(),
940
+ dimensions=768,
941
+ framesPerSecond=speed,
942
+ date_format="YYYY-MM-dd HH:mm",
943
+ xy=("3%", "3%"),
944
+ text_sequence=None,
945
+ font_type="arial.ttf",
946
+ font_size=font_size,
947
+ font_color=font_color,
948
+ add_progress_bar=add_progress_bar,
949
+ progress_bar_color=progress_bar_color,
950
+ progress_bar_height=5,
951
+ loop=0,
952
+ overlay_data=overlay_data,
953
+ overlay_color=overlay_color,
954
+ overlay_width=overlay_width,
955
+ overlay_opacity=overlay_opacity,
956
+ mp4=mp4,
957
+ fading=fading,
958
+ )
959
+
960
+ if out_gif is not None and os.path.exists(out_gif):
961
+ empty_text.text(
962
+ "Right click the GIF to save it to your computerπŸ‘‡"
963
+ )
964
+ empty_image.image(out_gif)
965
+
966
+ out_mp4 = out_gif.replace(".gif", ".mp4")
967
+ if mp4 and os.path.exists(out_mp4):
968
+ with empty_video:
969
+ st.text(
970
+ "Right click the MP4 to save it to your computerπŸ‘‡"
971
+ )
972
+ st.video(out_gif.replace(".gif", ".mp4"))
973
+
974
+ if add_fire:
975
+ out_fire_gif = geemap.temp_file_path(".gif")
976
+ empty_fire_text.text(
977
+ "Delineating Fire Hotspot... Please wait..."
978
+ )
979
+ geemap.goes_fire_timelapse(
980
+ out_fire_gif,
981
+ start_date=start,
982
+ end_date=end,
983
+ data=satellite,
984
+ scan=scan_type.replace(" ", "_").lower(),
985
+ region=roi,
986
+ dimensions=768,
987
+ framesPerSecond=speed,
988
+ date_format="YYYY-MM-dd HH:mm",
989
+ xy=("3%", "3%"),
990
+ text_sequence=None,
991
+ font_type="arial.ttf",
992
+ font_size=font_size,
993
+ font_color=font_color,
994
+ add_progress_bar=add_progress_bar,
995
+ progress_bar_color=progress_bar_color,
996
+ progress_bar_height=5,
997
+ loop=0,
998
+ )
999
+ if os.path.exists(out_fire_gif):
1000
+ empty_fire_image.image(out_fire_gif)
1001
+ else:
1002
+ empty_text.text(
1003
+ "Something went wrong, either the ROI is too big or there are no data available for the specified date range. Please try a smaller ROI or different date range."
1004
+ )
1005
+
1006
+ elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":
1007
+
1008
+ video_empty.video("https://youtu.be/16fA2QORG4A")
1009
+
1010
+ satellite = st.selectbox("Select a satellite:", ["Terra", "Aqua"])
1011
+ band = st.selectbox("Select a band:", ["NDVI", "EVI"])
1012
+
1013
+ with st.form("submit_modis_form"):
1014
+
1015
+ roi = None
1016
+ if st.session_state.get("roi") is not None:
1017
+ roi = st.session_state.get("roi")
1018
+ out_gif = geemap.temp_file_path(".gif")
1019
+
1020
+ with st.expander("Customize timelapse"):
1021
+
1022
+ start = st.date_input(
1023
+ "Select a start date:", datetime.date(2000, 2, 8)
1024
+ )
1025
+ end = st.date_input("Select an end date:", datetime.date.today())
1026
+
1027
+ start_date = start.strftime("%Y-%m-%d")
1028
+ end_date = end.strftime("%Y-%m-%d")
1029
+
1030
+ speed = st.slider("Frames per second:", 1, 30, 5)
1031
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1032
+ progress_bar_color = st.color_picker(
1033
+ "Progress bar color:", "#0000ff"
1034
+ )
1035
+ font_size = st.slider("Font size:", 10, 50, 20)
1036
+ font_color = st.color_picker("Font color:", "#ffffff")
1037
+
1038
+ font_type = st.selectbox(
1039
+ "Select the font type for the title:",
1040
+ ["arial.ttf", "alibaba.otf"],
1041
+ index=0,
1042
+ )
1043
+ fading = st.slider(
1044
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1045
+ )
1046
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1047
+
1048
+ empty_text = st.empty()
1049
+ empty_image = st.empty()
1050
+ empty_video = st.container()
1051
+
1052
+ submitted = st.form_submit_button("Submit")
1053
+ if submitted:
1054
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1055
+ empty_text.warning(
1056
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1057
+ )
1058
+ else:
1059
+
1060
+ empty_text.text("Computing... Please wait...")
1061
+
1062
+ geemap.modis_ndvi_timelapse(
1063
+ roi,
1064
+ out_gif,
1065
+ satellite,
1066
+ band,
1067
+ start_date,
1068
+ end_date,
1069
+ 768,
1070
+ speed,
1071
+ overlay_data=overlay_data,
1072
+ overlay_color=overlay_color,
1073
+ overlay_width=overlay_width,
1074
+ overlay_opacity=overlay_opacity,
1075
+ mp4=mp4,
1076
+ fading=fading,
1077
+ )
1078
+
1079
+ geemap.reduce_gif_size(out_gif)
1080
+
1081
+ empty_text.text(
1082
+ "Right click the GIF to save it to your computerπŸ‘‡"
1083
+ )
1084
+ empty_image.image(out_gif)
1085
+
1086
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1087
+ if mp4 and os.path.exists(out_mp4):
1088
+ with empty_video:
1089
+ st.text(
1090
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1091
+ )
1092
+ st.video(out_gif.replace(".gif", ".mp4"))
1093
+
1094
+ elif collection == "Any Earth Engine ImageCollection":
1095
+
1096
+ with st.form("submit_ts_form"):
1097
+ with st.expander("Customize timelapse"):
1098
+
1099
+ title = st.text_input(
1100
+ "Enter a title to show on the timelapse: ", "Timelapse"
1101
+ )
1102
+ start_date = st.date_input(
1103
+ "Select the start date:", datetime.date(2020, 1, 1)
1104
+ )
1105
+ end_date = st.date_input(
1106
+ "Select the end date:", datetime.date.today()
1107
+ )
1108
+ frequency = st.selectbox(
1109
+ "Select a temporal frequency:",
1110
+ ["year", "quarter", "month", "day", "hour", "minute", "second"],
1111
+ index=0,
1112
+ )
1113
+ reducer = st.selectbox(
1114
+ "Select a reducer for aggregating data:",
1115
+ ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
1116
+ index=0,
1117
+ )
1118
+ data_format = st.selectbox(
1119
+ "Select a date format to show on the timelapse:",
1120
+ [
1121
+ "YYYY-MM-dd",
1122
+ "YYYY",
1123
+ "YYMM-MM",
1124
+ "YYYY-MM-dd HH:mm",
1125
+ "YYYY-MM-dd HH:mm:ss",
1126
+ "HH:mm",
1127
+ "HH:mm:ss",
1128
+ "w",
1129
+ "M",
1130
+ "d",
1131
+ "D",
1132
+ ],
1133
+ index=0,
1134
+ )
1135
+
1136
+ speed = st.slider("Frames per second:", 1, 30, 5)
1137
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1138
+ progress_bar_color = st.color_picker(
1139
+ "Progress bar color:", "#0000ff"
1140
+ )
1141
+ font_size = st.slider("Font size:", 10, 50, 30)
1142
+ font_color = st.color_picker("Font color:", "#ffffff")
1143
+ font_type = st.selectbox(
1144
+ "Select the font type for the title:",
1145
+ ["arial.ttf", "alibaba.otf"],
1146
+ index=0,
1147
+ )
1148
+ fading = st.slider(
1149
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1150
+ )
1151
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1152
+
1153
+ empty_text = st.empty()
1154
+ empty_image = st.empty()
1155
+ empty_video = st.container()
1156
+ empty_fire_image = st.empty()
1157
+
1158
+ roi = None
1159
+ if st.session_state.get("roi") is not None:
1160
+ roi = st.session_state.get("roi")
1161
+ out_gif = geemap.temp_file_path(".gif")
1162
+
1163
+ submitted = st.form_submit_button("Submit")
1164
+ if submitted:
1165
+
1166
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1167
+ empty_text.warning(
1168
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1169
+ )
1170
+ else:
1171
+
1172
+ empty_text.text("Computing... Please wait...")
1173
+ try:
1174
+ geemap.create_timelapse(
1175
+ st.session_state.get("ee_asset_id"),
1176
+ start_date=start_date.strftime("%Y-%m-%d"),
1177
+ end_date=end_date.strftime("%Y-%m-%d"),
1178
+ region=roi,
1179
+ frequency=frequency,
1180
+ reducer=reducer,
1181
+ date_format=data_format,
1182
+ out_gif=out_gif,
1183
+ bands=st.session_state.get("bands"),
1184
+ palette=st.session_state.get("palette"),
1185
+ vis_params=st.session_state.get("vis_params"),
1186
+ dimensions=768,
1187
+ frames_per_second=speed,
1188
+ crs="EPSG:3857",
1189
+ overlay_data=overlay_data,
1190
+ overlay_color=overlay_color,
1191
+ overlay_width=overlay_width,
1192
+ overlay_opacity=overlay_opacity,
1193
+ title=title,
1194
+ title_xy=("2%", "90%"),
1195
+ add_text=True,
1196
+ text_xy=("2%", "2%"),
1197
+ text_sequence=None,
1198
+ font_type=font_type,
1199
+ font_size=font_size,
1200
+ font_color=font_color,
1201
+ add_progress_bar=add_progress_bar,
1202
+ progress_bar_color=progress_bar_color,
1203
+ progress_bar_height=5,
1204
+ loop=0,
1205
+ mp4=mp4,
1206
+ fading=fading,
1207
+ )
1208
+ except:
1209
+ empty_text.error(
1210
+ "An error occurred while computing the timelapse. You probably requested too much data. Try reducing the ROI or timespan."
1211
+ )
1212
+
1213
+ empty_text.text(
1214
+ "Right click the GIF to save it to your computerπŸ‘‡"
1215
+ )
1216
+ empty_image.image(out_gif)
1217
+
1218
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1219
+ if mp4 and os.path.exists(out_mp4):
1220
+ with empty_video:
1221
+ st.text(
1222
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1223
+ )
1224
+ st.video(out_gif.replace(".gif", ".mp4"))
1225
+
1226
+ elif collection in [
1227
+ "MODIS Gap filled Land Surface Temperature Daily",
1228
+ "MODIS Ocean Color SMI",
1229
+ ]:
1230
+
1231
+ with st.form("submit_ts_form"):
1232
+ with st.expander("Customize timelapse"):
1233
+
1234
+ title = st.text_input(
1235
+ "Enter a title to show on the timelapse: ",
1236
+ "Surface Temperature",
1237
+ )
1238
+ start_date = st.date_input(
1239
+ "Select the start date:", datetime.date(2018, 1, 1)
1240
+ )
1241
+ end_date = st.date_input(
1242
+ "Select the end date:", datetime.date(2020, 12, 31)
1243
+ )
1244
+ frequency = st.selectbox(
1245
+ "Select a temporal frequency:",
1246
+ ["year", "quarter", "month", "week", "day"],
1247
+ index=2,
1248
+ )
1249
+ reducer = st.selectbox(
1250
+ "Select a reducer for aggregating data:",
1251
+ ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
1252
+ index=0,
1253
+ )
1254
+
1255
+ vis_params = st.text_area(
1256
+ "Enter visualization parameters",
1257
+ "",
1258
+ help="Enter a string in the format of a dictionary, such as '{'min': 23, 'max': 32}'",
1259
+ )
1260
+
1261
+ speed = st.slider("Frames per second:", 1, 30, 5)
1262
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1263
+ progress_bar_color = st.color_picker(
1264
+ "Progress bar color:", "#0000ff"
1265
+ )
1266
+ font_size = st.slider("Font size:", 10, 50, 30)
1267
+ font_color = st.color_picker("Font color:", "#ffffff")
1268
+ font_type = st.selectbox(
1269
+ "Select the font type for the title:",
1270
+ ["arial.ttf", "alibaba.otf"],
1271
+ index=0,
1272
+ )
1273
+ add_colorbar = st.checkbox("Add a colorbar", True)
1274
+ colorbar_label = st.text_input(
1275
+ "Enter the colorbar label:", "Surface Temperature (Β°C)"
1276
+ )
1277
+ fading = st.slider(
1278
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1279
+ )
1280
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1281
+
1282
+ empty_text = st.empty()
1283
+ empty_image = st.empty()
1284
+ empty_video = st.container()
1285
+
1286
+ roi = None
1287
+ if st.session_state.get("roi") is not None:
1288
+ roi = st.session_state.get("roi")
1289
+ out_gif = geemap.temp_file_path(".gif")
1290
+
1291
+ submitted = st.form_submit_button("Submit")
1292
+ if submitted:
1293
+
1294
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1295
+ empty_text.warning(
1296
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1297
+ )
1298
+ else:
1299
+
1300
+ empty_text.text("Computing... Please wait...")
1301
+ try:
1302
+ if (
1303
+ collection
1304
+ == "MODIS Gap filled Land Surface Temperature Daily"
1305
+ ):
1306
+ out_gif = geemap.create_timelapse(
1307
+ st.session_state.get("ee_asset_id"),
1308
+ start_date=start_date.strftime("%Y-%m-%d"),
1309
+ end_date=end_date.strftime("%Y-%m-%d"),
1310
+ region=roi,
1311
+ bands=None,
1312
+ frequency=frequency,
1313
+ reducer=reducer,
1314
+ date_format=None,
1315
+ out_gif=out_gif,
1316
+ palette=st.session_state.get("palette"),
1317
+ vis_params=None,
1318
+ dimensions=768,
1319
+ frames_per_second=speed,
1320
+ crs="EPSG:3857",
1321
+ overlay_data=overlay_data,
1322
+ overlay_color=overlay_color,
1323
+ overlay_width=overlay_width,
1324
+ overlay_opacity=overlay_opacity,
1325
+ title=title,
1326
+ title_xy=("2%", "90%"),
1327
+ add_text=True,
1328
+ text_xy=("2%", "2%"),
1329
+ text_sequence=None,
1330
+ font_type=font_type,
1331
+ font_size=font_size,
1332
+ font_color=font_color,
1333
+ add_progress_bar=add_progress_bar,
1334
+ progress_bar_color=progress_bar_color,
1335
+ progress_bar_height=5,
1336
+ add_colorbar=add_colorbar,
1337
+ colorbar_label=colorbar_label,
1338
+ loop=0,
1339
+ mp4=mp4,
1340
+ fading=fading,
1341
+ )
1342
+ elif collection == "MODIS Ocean Color SMI":
1343
+ if vis_params.startswith("{") and vis_params.endswith(
1344
+ "}"
1345
+ ):
1346
+ vis_params = eval(vis_params)
1347
+ else:
1348
+ vis_params = None
1349
+ out_gif = geemap.modis_ocean_color_timelapse(
1350
+ st.session_state.get("ee_asset_id"),
1351
+ start_date=start_date.strftime("%Y-%m-%d"),
1352
+ end_date=end_date.strftime("%Y-%m-%d"),
1353
+ region=roi,
1354
+ bands=st.session_state["band"],
1355
+ frequency=frequency,
1356
+ reducer=reducer,
1357
+ date_format=None,
1358
+ out_gif=out_gif,
1359
+ palette=st.session_state.get("palette"),
1360
+ vis_params=vis_params,
1361
+ dimensions=768,
1362
+ frames_per_second=speed,
1363
+ crs="EPSG:3857",
1364
+ overlay_data=overlay_data,
1365
+ overlay_color=overlay_color,
1366
+ overlay_width=overlay_width,
1367
+ overlay_opacity=overlay_opacity,
1368
+ title=title,
1369
+ title_xy=("2%", "90%"),
1370
+ add_text=True,
1371
+ text_xy=("2%", "2%"),
1372
+ text_sequence=None,
1373
+ font_type=font_type,
1374
+ font_size=font_size,
1375
+ font_color=font_color,
1376
+ add_progress_bar=add_progress_bar,
1377
+ progress_bar_color=progress_bar_color,
1378
+ progress_bar_height=5,
1379
+ add_colorbar=add_colorbar,
1380
+ colorbar_label=colorbar_label,
1381
+ loop=0,
1382
+ mp4=mp4,
1383
+ fading=fading,
1384
+ )
1385
+ except:
1386
+ empty_text.error(
1387
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
1388
+ )
1389
+
1390
+ if out_gif is not None and os.path.exists(out_gif):
1391
+
1392
+ geemap.reduce_gif_size(out_gif)
1393
+
1394
+ empty_text.text(
1395
+ "Right click the GIF to save it to your computerπŸ‘‡"
1396
+ )
1397
+ empty_image.image(out_gif)
1398
+
1399
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1400
+ if mp4 and os.path.exists(out_mp4):
1401
+ with empty_video:
1402
+ st.text(
1403
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1404
+ )
1405
+ st.video(out_gif.replace(".gif", ".mp4"))
1406
+
1407
+ else:
1408
+ st.error(
1409
+ "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
1410
+ )
1411
+
1412
+ elif collection == "USDA National Agriculture Imagery Program (NAIP)":
1413
+
1414
+ with st.form("submit_naip_form"):
1415
+ with st.expander("Customize timelapse"):
1416
+
1417
+ title = st.text_input(
1418
+ "Enter a title to show on the timelapse: ", "NAIP Timelapse"
1419
+ )
1420
+
1421
+ years = st.slider(
1422
+ "Start and end year:",
1423
+ 2003,
1424
+ today.year,
1425
+ (2003, today.year),
1426
+ )
1427
+
1428
+ bands = st.selectbox(
1429
+ "Select a band combination:", ["N/R/G", "R/G/B"], index=0
1430
+ )
1431
+
1432
+ speed = st.slider("Frames per second:", 1, 30, 3)
1433
+ add_progress_bar = st.checkbox("Add a progress bar", True)
1434
+ progress_bar_color = st.color_picker(
1435
+ "Progress bar color:", "#0000ff"
1436
+ )
1437
+ font_size = st.slider("Font size:", 10, 50, 30)
1438
+ font_color = st.color_picker("Font color:", "#ffffff")
1439
+ font_type = st.selectbox(
1440
+ "Select the font type for the title:",
1441
+ ["arial.ttf", "alibaba.otf"],
1442
+ index=0,
1443
+ )
1444
+ fading = st.slider(
1445
+ "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
1446
+ )
1447
+ mp4 = st.checkbox("Save timelapse as MP4", True)
1448
+
1449
+ empty_text = st.empty()
1450
+ empty_image = st.empty()
1451
+ empty_video = st.container()
1452
+ empty_fire_image = st.empty()
1453
+
1454
+ roi = None
1455
+ if st.session_state.get("roi") is not None:
1456
+ roi = st.session_state.get("roi")
1457
+ out_gif = geemap.temp_file_path(".gif")
1458
+
1459
+ submitted = st.form_submit_button("Submit")
1460
+ if submitted:
1461
+
1462
+ if sample_roi == "Uploaded GeoJSON" and data is None:
1463
+ empty_text.warning(
1464
+ "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
1465
+ )
1466
+ else:
1467
+
1468
+ empty_text.text("Computing... Please wait...")
1469
+ try:
1470
+ geemap.naip_timelapse(
1471
+ roi,
1472
+ years[0],
1473
+ years[1],
1474
+ out_gif,
1475
+ bands=bands.split("/"),
1476
+ palette=st.session_state.get("palette"),
1477
+ vis_params=None,
1478
+ dimensions=768,
1479
+ frames_per_second=speed,
1480
+ crs="EPSG:3857",
1481
+ overlay_data=overlay_data,
1482
+ overlay_color=overlay_color,
1483
+ overlay_width=overlay_width,
1484
+ overlay_opacity=overlay_opacity,
1485
+ title=title,
1486
+ title_xy=("2%", "90%"),
1487
+ add_text=True,
1488
+ text_xy=("2%", "2%"),
1489
+ text_sequence=None,
1490
+ font_type=font_type,
1491
+ font_size=font_size,
1492
+ font_color=font_color,
1493
+ add_progress_bar=add_progress_bar,
1494
+ progress_bar_color=progress_bar_color,
1495
+ progress_bar_height=5,
1496
+ loop=0,
1497
+ mp4=mp4,
1498
+ fading=fading,
1499
+ )
1500
+ except:
1501
+ empty_text.error(
1502
+ "Something went wrong. You either requested too much data or the ROI is outside the U.S."
1503
+ )
1504
+
1505
+ if out_gif is not None and os.path.exists(out_gif):
1506
+
1507
+ empty_text.text(
1508
+ "Right click the GIF to save it to your computerπŸ‘‡"
1509
+ )
1510
+ empty_image.image(out_gif)
1511
+
1512
+ out_mp4 = out_gif.replace(".gif", ".mp4")
1513
+ if mp4 and os.path.exists(out_mp4):
1514
+ with empty_video:
1515
+ st.text(
1516
+ "Right click the MP4 to save it to your computerπŸ‘‡"
1517
+ )
1518
+ st.video(out_gif.replace(".gif", ".mp4"))
1519
+
1520
+ else:
1521
+ st.error(
1522
+ "Something went wrong. You either requested too much data or the ROI is outside the U.S."
1523
+ )
1524
+
1525
+
1526
+ try:
1527
+ app()
1528
+ except Exception as e:
1529
+ pass
pages/2_🏠_U.S._Housing.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import pathlib
4
+ import requests
5
+ import zipfile
6
+ import pandas as pd
7
+ import pydeck as pdk
8
+ import geopandas as gpd
9
+ import streamlit as st
10
+ import leafmap.colormaps as cm
11
+ from leafmap.common import hex_to_rgb
12
+
13
+ st.set_page_config(layout="wide")
14
+
15
+ st.sidebar.title("About")
16
+ st.sidebar.info(
17
+ """
18
+ Web App URL: <https://geospatial.streamlitapp.com>
19
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
20
+ """
21
+ )
22
+
23
+ st.sidebar.title("Contact")
24
+ st.sidebar.info(
25
+ """
26
+ Qiusheng Wu: <https://wetlands.io>
27
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
28
+ """
29
+ )
30
+
31
+ STREAMLIT_STATIC_PATH = pathlib.Path(st.__path__[0]) / "static"
32
+ # We create a downloads directory within the streamlit static asset directory
33
+ # and we write output files to it
34
+ DOWNLOADS_PATH = STREAMLIT_STATIC_PATH / "downloads"
35
+ if not DOWNLOADS_PATH.is_dir():
36
+ DOWNLOADS_PATH.mkdir()
37
+
38
+ # Data source: https://www.realtor.com/research/data/
39
+ # link_prefix = "https://econdata.s3-us-west-2.amazonaws.com/Reports/"
40
+ link_prefix = "https://raw.githubusercontent.com/giswqs/data/main/housing/"
41
+
42
+ data_links = {
43
+ "weekly": {
44
+ "national": link_prefix + "Core/listing_weekly_core_aggregate_by_country.csv",
45
+ "metro": link_prefix + "Core/listing_weekly_core_aggregate_by_metro.csv",
46
+ },
47
+ "monthly_current": {
48
+ "national": link_prefix + "Core/RDC_Inventory_Core_Metrics_Country.csv",
49
+ "state": link_prefix + "Core/RDC_Inventory_Core_Metrics_State.csv",
50
+ "metro": link_prefix + "Core/RDC_Inventory_Core_Metrics_Metro.csv",
51
+ "county": link_prefix + "Core/RDC_Inventory_Core_Metrics_County.csv",
52
+ "zip": link_prefix + "Core/RDC_Inventory_Core_Metrics_Zip.csv",
53
+ },
54
+ "monthly_historical": {
55
+ "national": link_prefix + "Core/RDC_Inventory_Core_Metrics_Country_History.csv",
56
+ "state": link_prefix + "Core/RDC_Inventory_Core_Metrics_State_History.csv",
57
+ "metro": link_prefix + "Core/RDC_Inventory_Core_Metrics_Metro_History.csv",
58
+ "county": link_prefix + "Core/RDC_Inventory_Core_Metrics_County_History.csv",
59
+ "zip": link_prefix + "Core/RDC_Inventory_Core_Metrics_Zip_History.csv",
60
+ },
61
+ "hotness": {
62
+ "metro": link_prefix
63
+ + "Hotness/RDC_Inventory_Hotness_Metrics_Metro_History.csv",
64
+ "county": link_prefix
65
+ + "Hotness/RDC_Inventory_Hotness_Metrics_County_History.csv",
66
+ "zip": link_prefix + "Hotness/RDC_Inventory_Hotness_Metrics_Zip_History.csv",
67
+ },
68
+ }
69
+
70
+
71
+ def get_data_columns(df, category, frequency="monthly"):
72
+ if frequency == "monthly":
73
+ if category.lower() == "county":
74
+ del_cols = ["month_date_yyyymm", "county_fips", "county_name"]
75
+ elif category.lower() == "state":
76
+ del_cols = ["month_date_yyyymm", "state", "state_id"]
77
+ elif category.lower() == "national":
78
+ del_cols = ["month_date_yyyymm", "country"]
79
+ elif category.lower() == "metro":
80
+ del_cols = ["month_date_yyyymm", "cbsa_code", "cbsa_title", "HouseholdRank"]
81
+ elif category.lower() == "zip":
82
+ del_cols = ["month_date_yyyymm", "postal_code", "zip_name", "flag"]
83
+ elif frequency == "weekly":
84
+ if category.lower() == "national":
85
+ del_cols = ["week_end_date", "geo_country"]
86
+ elif category.lower() == "metro":
87
+ del_cols = ["week_end_date", "cbsa_code", "cbsa_title", "hh_rank"]
88
+
89
+ cols = df.columns.values.tolist()
90
+
91
+ for col in cols:
92
+ if col.strip() in del_cols:
93
+ cols.remove(col)
94
+ if category.lower() == "metro":
95
+ return cols[2:]
96
+ else:
97
+ return cols[1:]
98
+
99
+
100
+ @st.cache
101
+ def get_inventory_data(url):
102
+ df = pd.read_csv(url)
103
+ url = url.lower()
104
+ if "county" in url:
105
+ df["county_fips"] = df["county_fips"].map(str)
106
+ df["county_fips"] = df["county_fips"].str.zfill(5)
107
+ elif "state" in url:
108
+ df["STUSPS"] = df["state_id"].str.upper()
109
+ elif "metro" in url:
110
+ df["cbsa_code"] = df["cbsa_code"].map(str)
111
+ elif "zip" in url:
112
+ df["postal_code"] = df["postal_code"].map(str)
113
+ df["postal_code"] = df["postal_code"].str.zfill(5)
114
+
115
+ if "listing_weekly_core_aggregate_by_country" in url:
116
+ columns = get_data_columns(df, "national", "weekly")
117
+ for column in columns:
118
+ if column != "median_days_on_market_by_day_yy":
119
+ df[column] = df[column].str.rstrip("%").astype(float) / 100
120
+ if "listing_weekly_core_aggregate_by_metro" in url:
121
+ columns = get_data_columns(df, "metro", "weekly")
122
+ for column in columns:
123
+ if column != "median_days_on_market_by_day_yy":
124
+ df[column] = df[column].str.rstrip("%").astype(float) / 100
125
+ df["cbsa_code"] = df["cbsa_code"].str[:5]
126
+ return df
127
+
128
+
129
+ def filter_weekly_inventory(df, week):
130
+ df = df[df["week_end_date"] == week]
131
+ return df
132
+
133
+
134
+ def get_start_end_year(df):
135
+ start_year = int(str(df["month_date_yyyymm"].min())[:4])
136
+ end_year = int(str(df["month_date_yyyymm"].max())[:4])
137
+ return start_year, end_year
138
+
139
+
140
+ def get_periods(df):
141
+ return [str(d) for d in list(set(df["month_date_yyyymm"].tolist()))]
142
+
143
+
144
+ @st.cache
145
+ def get_geom_data(category):
146
+
147
+ prefix = (
148
+ "https://raw.githubusercontent.com/giswqs/streamlit-geospatial/master/data/"
149
+ )
150
+ links = {
151
+ "national": prefix + "us_nation.geojson",
152
+ "state": prefix + "us_states.geojson",
153
+ "county": prefix + "us_counties.geojson",
154
+ "metro": prefix + "us_metro_areas.geojson",
155
+ "zip": "https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_zcta510_500k.zip",
156
+ }
157
+
158
+ if category.lower() == "zip":
159
+ r = requests.get(links[category])
160
+ out_zip = os.path.join(DOWNLOADS_PATH, "cb_2018_us_zcta510_500k.zip")
161
+ with open(out_zip, "wb") as code:
162
+ code.write(r.content)
163
+ zip_ref = zipfile.ZipFile(out_zip, "r")
164
+ zip_ref.extractall(DOWNLOADS_PATH)
165
+ gdf = gpd.read_file(out_zip.replace("zip", "shp"))
166
+ else:
167
+ gdf = gpd.read_file(links[category])
168
+ return gdf
169
+
170
+
171
+ def join_attributes(gdf, df, category):
172
+
173
+ new_gdf = None
174
+ if category == "county":
175
+ new_gdf = gdf.merge(df, left_on="GEOID", right_on="county_fips", how="outer")
176
+ elif category == "state":
177
+ new_gdf = gdf.merge(df, left_on="STUSPS", right_on="STUSPS", how="outer")
178
+ elif category == "national":
179
+ if "geo_country" in df.columns.values.tolist():
180
+ df["country"] = None
181
+ df.loc[0, "country"] = "United States"
182
+ new_gdf = gdf.merge(df, left_on="NAME", right_on="country", how="outer")
183
+ elif category == "metro":
184
+ new_gdf = gdf.merge(df, left_on="CBSAFP", right_on="cbsa_code", how="outer")
185
+ elif category == "zip":
186
+ new_gdf = gdf.merge(df, left_on="GEOID10", right_on="postal_code", how="outer")
187
+ return new_gdf
188
+
189
+
190
+ def select_non_null(gdf, col_name):
191
+ new_gdf = gdf[~gdf[col_name].isna()]
192
+ return new_gdf
193
+
194
+
195
+ def select_null(gdf, col_name):
196
+ new_gdf = gdf[gdf[col_name].isna()]
197
+ return new_gdf
198
+
199
+
200
+ def get_data_dict(name):
201
+ in_csv = os.path.join(os.getcwd(), "data/realtor_data_dict.csv")
202
+ df = pd.read_csv(in_csv)
203
+ label = list(df[df["Name"] == name]["Label"])[0]
204
+ desc = list(df[df["Name"] == name]["Description"])[0]
205
+ return label, desc
206
+
207
+
208
+ def get_weeks(df):
209
+ seq = list(set(df[~df["week_end_date"].isnull()]["week_end_date"].tolist()))
210
+ weeks = [
211
+ datetime.date(int(d.split("/")[2]), int(d.split("/")[0]), int(d.split("/")[1]))
212
+ for d in seq
213
+ ]
214
+ weeks.sort()
215
+ return weeks
216
+
217
+
218
+ def get_saturday(in_date):
219
+ idx = (in_date.weekday() + 1) % 7
220
+ sat = in_date + datetime.timedelta(6 - idx)
221
+ return sat
222
+
223
+
224
+ def app():
225
+
226
+ st.title("U.S. Real Estate Data and Market Trends")
227
+ st.markdown(
228
+ """**Introduction:** This interactive dashboard is designed for visualizing U.S. real estate data and market trends at multiple levels (i.e., national,
229
+ state, county, and metro). The data sources include [Real Estate Data](https://www.realtor.com/research/data) from realtor.com and
230
+ [Cartographic Boundary Files](https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html) from U.S. Census Bureau.
231
+ Several open-source packages are used to process the data and generate the visualizations, e.g., [streamlit](https://streamlit.io),
232
+ [geopandas](https://geopandas.org), [leafmap](https://leafmap.org), and [pydeck](https://deckgl.readthedocs.io).
233
+ """
234
+ )
235
+
236
+ with st.expander("See a demo"):
237
+ st.image("https://i.imgur.com/Z3dk6Tr.gif")
238
+
239
+ row1_col1, row1_col2, row1_col3, row1_col4, row1_col5 = st.columns(
240
+ [0.6, 0.8, 0.6, 1.4, 2]
241
+ )
242
+ with row1_col1:
243
+ frequency = st.selectbox("Monthly/weekly data", ["Monthly", "Weekly"])
244
+ with row1_col2:
245
+ types = ["Current month data", "Historical data"]
246
+ if frequency == "Weekly":
247
+ types.remove("Current month data")
248
+ cur_hist = st.selectbox(
249
+ "Current/historical data",
250
+ types,
251
+ )
252
+ with row1_col3:
253
+ if frequency == "Monthly":
254
+ scale = st.selectbox(
255
+ "Scale", ["National", "State", "Metro", "County"], index=3
256
+ )
257
+ else:
258
+ scale = st.selectbox("Scale", ["National", "Metro"], index=1)
259
+
260
+ gdf = get_geom_data(scale.lower())
261
+
262
+ if frequency == "Weekly":
263
+ inventory_df = get_inventory_data(data_links["weekly"][scale.lower()])
264
+ weeks = get_weeks(inventory_df)
265
+ with row1_col1:
266
+ selected_date = st.date_input("Select a date", value=weeks[-1])
267
+ saturday = get_saturday(selected_date)
268
+ selected_period = saturday.strftime("%-m/%-d/%Y")
269
+ if saturday not in weeks:
270
+ st.error(
271
+ "The selected date is not available in the data. Please select a date between {} and {}".format(
272
+ weeks[0], weeks[-1]
273
+ )
274
+ )
275
+ selected_period = weeks[-1].strftime("%-m/%-d/%Y")
276
+ inventory_df = get_inventory_data(data_links["weekly"][scale.lower()])
277
+ inventory_df = filter_weekly_inventory(inventory_df, selected_period)
278
+
279
+ if frequency == "Monthly":
280
+ if cur_hist == "Current month data":
281
+ inventory_df = get_inventory_data(
282
+ data_links["monthly_current"][scale.lower()]
283
+ )
284
+ selected_period = get_periods(inventory_df)[0]
285
+ else:
286
+ with row1_col2:
287
+ inventory_df = get_inventory_data(
288
+ data_links["monthly_historical"][scale.lower()]
289
+ )
290
+ start_year, end_year = get_start_end_year(inventory_df)
291
+ periods = get_periods(inventory_df)
292
+ with st.expander("Select year and month", True):
293
+ selected_year = st.slider(
294
+ "Year",
295
+ start_year,
296
+ end_year,
297
+ value=start_year,
298
+ step=1,
299
+ )
300
+ selected_month = st.slider(
301
+ "Month",
302
+ min_value=1,
303
+ max_value=12,
304
+ value=int(periods[0][-2:]),
305
+ step=1,
306
+ )
307
+ selected_period = str(selected_year) + str(selected_month).zfill(2)
308
+ if selected_period not in periods:
309
+ st.error("Data not available for selected year and month")
310
+ selected_period = periods[0]
311
+ inventory_df = inventory_df[
312
+ inventory_df["month_date_yyyymm"] == int(selected_period)
313
+ ]
314
+
315
+ data_cols = get_data_columns(inventory_df, scale.lower(), frequency.lower())
316
+
317
+ with row1_col4:
318
+ selected_col = st.selectbox("Attribute", data_cols)
319
+ with row1_col5:
320
+ show_desc = st.checkbox("Show attribute description")
321
+ if show_desc:
322
+ try:
323
+ label, desc = get_data_dict(selected_col.strip())
324
+ markdown = f"""
325
+ **{label}**: {desc}
326
+ """
327
+ st.markdown(markdown)
328
+ except:
329
+ st.warning("No description available for selected attribute")
330
+
331
+ row2_col1, row2_col2, row2_col3, row2_col4, row2_col5, row2_col6 = st.columns(
332
+ [0.6, 0.68, 0.7, 0.7, 1.5, 0.8]
333
+ )
334
+
335
+ palettes = cm.list_colormaps()
336
+ with row2_col1:
337
+ palette = st.selectbox("Color palette", palettes, index=palettes.index("Blues"))
338
+ with row2_col2:
339
+ n_colors = st.slider("Number of colors", min_value=2, max_value=20, value=8)
340
+ with row2_col3:
341
+ show_nodata = st.checkbox("Show nodata areas", value=True)
342
+ with row2_col4:
343
+ show_3d = st.checkbox("Show 3D view", value=False)
344
+ with row2_col5:
345
+ if show_3d:
346
+ elev_scale = st.slider(
347
+ "Elevation scale", min_value=1, max_value=1000000, value=1, step=10
348
+ )
349
+ with row2_col6:
350
+ st.info("Press Ctrl and move the left mouse button.")
351
+ else:
352
+ elev_scale = 1
353
+
354
+ gdf = join_attributes(gdf, inventory_df, scale.lower())
355
+ gdf_null = select_null(gdf, selected_col)
356
+ gdf = select_non_null(gdf, selected_col)
357
+ gdf = gdf.sort_values(by=selected_col, ascending=True)
358
+
359
+ colors = cm.get_palette(palette, n_colors)
360
+ colors = [hex_to_rgb(c) for c in colors]
361
+
362
+ for i, ind in enumerate(gdf.index):
363
+ index = int(i / (len(gdf) / len(colors)))
364
+ if index >= len(colors):
365
+ index = len(colors) - 1
366
+ gdf.loc[ind, "R"] = colors[index][0]
367
+ gdf.loc[ind, "G"] = colors[index][1]
368
+ gdf.loc[ind, "B"] = colors[index][2]
369
+
370
+ initial_view_state = pdk.ViewState(
371
+ latitude=40,
372
+ longitude=-100,
373
+ zoom=3,
374
+ max_zoom=16,
375
+ pitch=0,
376
+ bearing=0,
377
+ height=900,
378
+ width=None,
379
+ )
380
+
381
+ min_value = gdf[selected_col].min()
382
+ max_value = gdf[selected_col].max()
383
+ color = "color"
384
+ # color_exp = f"[({selected_col}-{min_value})/({max_value}-{min_value})*255, 0, 0]"
385
+ color_exp = f"[R, G, B]"
386
+
387
+ geojson = pdk.Layer(
388
+ "GeoJsonLayer",
389
+ gdf,
390
+ pickable=True,
391
+ opacity=0.5,
392
+ stroked=True,
393
+ filled=True,
394
+ extruded=show_3d,
395
+ wireframe=True,
396
+ get_elevation=f"{selected_col}",
397
+ elevation_scale=elev_scale,
398
+ # get_fill_color="color",
399
+ get_fill_color=color_exp,
400
+ get_line_color=[0, 0, 0],
401
+ get_line_width=2,
402
+ line_width_min_pixels=1,
403
+ )
404
+
405
+ geojson_null = pdk.Layer(
406
+ "GeoJsonLayer",
407
+ gdf_null,
408
+ pickable=True,
409
+ opacity=0.2,
410
+ stroked=True,
411
+ filled=True,
412
+ extruded=False,
413
+ wireframe=True,
414
+ # get_elevation="properties.ALAND/100000",
415
+ # get_fill_color="color",
416
+ get_fill_color=[200, 200, 200],
417
+ get_line_color=[0, 0, 0],
418
+ get_line_width=2,
419
+ line_width_min_pixels=1,
420
+ )
421
+
422
+ # tooltip = {"text": "Name: {NAME}"}
423
+
424
+ # tooltip_value = f"<b>Value:</b> {median_listing_price}""
425
+ tooltip = {
426
+ "html": "<b>Name:</b> {NAME}<br><b>Value:</b> {"
427
+ + selected_col
428
+ + "}<br><b>Date:</b> "
429
+ + selected_period
430
+ + "",
431
+ "style": {"backgroundColor": "steelblue", "color": "white"},
432
+ }
433
+
434
+ layers = [geojson]
435
+ if show_nodata:
436
+ layers.append(geojson_null)
437
+
438
+ r = pdk.Deck(
439
+ layers=layers,
440
+ initial_view_state=initial_view_state,
441
+ map_style="light",
442
+ tooltip=tooltip,
443
+ )
444
+
445
+ row3_col1, row3_col2 = st.columns([6, 1])
446
+
447
+ with row3_col1:
448
+ st.pydeck_chart(r)
449
+ with row3_col2:
450
+ st.write(
451
+ cm.create_colormap(
452
+ palette,
453
+ label=selected_col.replace("_", " ").title(),
454
+ width=0.2,
455
+ height=3,
456
+ orientation="vertical",
457
+ vmin=min_value,
458
+ vmax=max_value,
459
+ font_size=10,
460
+ )
461
+ )
462
+ row4_col1, row4_col2, row4_col3 = st.columns([1, 2, 3])
463
+ with row4_col1:
464
+ show_data = st.checkbox("Show raw data")
465
+ with row4_col2:
466
+ show_cols = st.multiselect("Select columns", data_cols)
467
+ with row4_col3:
468
+ show_colormaps = st.checkbox("Preview all color palettes")
469
+ if show_colormaps:
470
+ st.write(cm.plot_colormaps(return_fig=True))
471
+ if show_data:
472
+ if scale == "National":
473
+ st.dataframe(gdf[["NAME", "GEOID"] + show_cols])
474
+ elif scale == "State":
475
+ st.dataframe(gdf[["NAME", "STUSPS"] + show_cols])
476
+ elif scale == "County":
477
+ st.dataframe(gdf[["NAME", "STATEFP", "COUNTYFP"] + show_cols])
478
+ elif scale == "Metro":
479
+ st.dataframe(gdf[["NAME", "CBSAFP"] + show_cols])
480
+ elif scale == "Zip":
481
+ st.dataframe(gdf[["GEOID10"] + show_cols])
482
+
483
+
484
+ app()
pages/3_πŸͺŸ_Split_Map.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+ st.title("Split-panel Map")
23
+
24
+ with st.expander("See source code"):
25
+ with st.echo():
26
+ m = leafmap.Map()
27
+ m.split_map(
28
+ left_layer='ESA WorldCover 2020 S2 FCC', right_layer='ESA WorldCover 2020'
29
+ )
30
+ m.add_legend(title='ESA Land Cover', builtin_legend='ESA_WorldCover')
31
+
32
+ m.to_streamlit(height=700)
pages/4_πŸ”₯_Heatmap.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+ st.title("Heatmap")
23
+
24
+ with st.expander("See source code"):
25
+ with st.echo():
26
+ filepath = "https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_cities.csv"
27
+ m = leafmap.Map(center=[40, -100], zoom=4, tiles="stamentoner")
28
+ m.add_heatmap(
29
+ filepath,
30
+ latitude="latitude",
31
+ longitude="longitude",
32
+ value="pop_max",
33
+ name="Heat map",
34
+ radius=20,
35
+ )
36
+ m.to_streamlit(height=700)
pages/5_πŸ“_Marker_Cluster.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+ st.title("Marker Cluster")
23
+
24
+ with st.expander("See source code"):
25
+ with st.echo():
26
+
27
+ m = leafmap.Map(center=[40, -100], zoom=4)
28
+ cities = 'https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_cities.csv'
29
+ regions = 'https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_regions.geojson'
30
+
31
+ m.add_geojson(regions, layer_name='US Regions')
32
+ m.add_points_from_xy(
33
+ cities,
34
+ x="longitude",
35
+ y="latitude",
36
+ color_column='region',
37
+ icon_names=['gear', 'map', 'leaf', 'globe'],
38
+ spin=True,
39
+ add_legend=True,
40
+ )
41
+
42
+ m.to_streamlit(height=700)
pages/6_πŸ—ΊοΈ_Basemaps.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import leafmap.foliumap as leafmap
3
+
4
+ st.set_page_config(layout="wide")
5
+
6
+ st.sidebar.title("About")
7
+ st.sidebar.info(
8
+ """
9
+ Web App URL: <https://geospatial.streamlitapp.com>
10
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
11
+ """
12
+ )
13
+
14
+ st.sidebar.title("Contact")
15
+ st.sidebar.info(
16
+ """
17
+ Qiusheng Wu: <https://wetlands.io>
18
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
19
+ """
20
+ )
21
+
22
+
23
+ def app():
24
+ st.title("Search Basemaps")
25
+ st.markdown(
26
+ """
27
+ This app is a demonstration of searching and loading basemaps from [xyzservices](https://github.com/geopandas/xyzservices) and [Quick Map Services (QMS)](https://github.com/nextgis/quickmapservices). Selecting from 1000+ basemaps with a few clicks.
28
+ """
29
+ )
30
+
31
+ with st.expander("See demo"):
32
+ st.image("https://i.imgur.com/0SkUhZh.gif")
33
+
34
+ row1_col1, row1_col2 = st.columns([3, 1])
35
+ width = 800
36
+ height = 600
37
+ tiles = None
38
+
39
+ with row1_col2:
40
+
41
+ checkbox = st.checkbox("Search Quick Map Services (QMS)")
42
+ keyword = st.text_input("Enter a keyword to search and press Enter:")
43
+ empty = st.empty()
44
+
45
+ if keyword:
46
+ options = leafmap.search_xyz_services(keyword=keyword)
47
+ if checkbox:
48
+ qms = leafmap.search_qms(keyword=keyword)
49
+ if qms is not None:
50
+ options = options + qms
51
+
52
+ tiles = empty.multiselect(
53
+ "Select XYZ tiles to add to the map:", options)
54
+
55
+ with row1_col1:
56
+ m = leafmap.Map()
57
+
58
+ if tiles is not None:
59
+ for tile in tiles:
60
+ m.add_xyz_service(tile)
61
+
62
+ m.to_streamlit(height=height)
63
+
64
+
65
+ app()
pages/7_πŸ“¦_Web_Map_Service.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import streamlit as st
3
+ import leafmap.foliumap as leafmap
4
+
5
+ st.set_page_config(layout="wide")
6
+
7
+ st.sidebar.title("About")
8
+ st.sidebar.info(
9
+ """
10
+ Web App URL: <https://geospatial.streamlitapp.com>
11
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
12
+ """
13
+ )
14
+
15
+ st.sidebar.title("Contact")
16
+ st.sidebar.info(
17
+ """
18
+ Qiusheng Wu: <https://wetlands.io>
19
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
20
+ """
21
+ )
22
+
23
+
24
+ @st.cache
25
+ def get_layers(url):
26
+ options = leafmap.get_wms_layers(url)
27
+ return options
28
+
29
+
30
+ def app():
31
+ st.title("Web Map Service (WMS)")
32
+ st.markdown(
33
+ """
34
+ This app is a demonstration of loading Web Map Service (WMS) layers. Simply enter the URL of the WMS service
35
+ in the text box below and press Enter to retrieve the layers. Go to https://apps.nationalmap.gov/services to find
36
+ some WMS URLs if needed.
37
+ """
38
+ )
39
+
40
+ row1_col1, row1_col2 = st.columns([3, 1.3])
41
+ width = 800
42
+ height = 600
43
+ layers = None
44
+
45
+ with row1_col2:
46
+
47
+ esa_landcover = "https://services.terrascope.be/wms/v2"
48
+ url = st.text_input(
49
+ "Enter a WMS URL:", value="https://services.terrascope.be/wms/v2"
50
+ )
51
+ empty = st.empty()
52
+
53
+ if url:
54
+ options = get_layers(url)
55
+
56
+ default = None
57
+ if url == esa_landcover:
58
+ default = "WORLDCOVER_2020_MAP"
59
+ layers = empty.multiselect(
60
+ "Select WMS layers to add to the map:", options, default=default
61
+ )
62
+ add_legend = st.checkbox("Add a legend to the map", value=True)
63
+ if default == "WORLDCOVER_2020_MAP":
64
+ legend = str(leafmap.builtin_legends["ESA_WorldCover"])
65
+ else:
66
+ legend = ""
67
+ if add_legend:
68
+ legend_text = st.text_area(
69
+ "Enter a legend as a dictionary {label: color}",
70
+ value=legend,
71
+ height=200,
72
+ )
73
+
74
+ with row1_col1:
75
+ m = leafmap.Map(center=(36.3, 0), zoom=2)
76
+
77
+ if layers is not None:
78
+ for layer in layers:
79
+ m.add_wms_layer(
80
+ url, layers=layer, name=layer, attribution=" ", transparent=True
81
+ )
82
+ if add_legend and legend_text:
83
+ legend_dict = ast.literal_eval(legend_text)
84
+ m.add_legend(legend_dict=legend_dict)
85
+
86
+ m.to_streamlit(height=height)
87
+
88
+
89
+ app()
pages/8_🏜️_Raster_Data_Visualization.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import leafmap.foliumap as leafmap
3
+ import leafmap.colormaps as cm
4
+ import streamlit as st
5
+
6
+ st.set_page_config(layout="wide")
7
+
8
+ st.sidebar.title("About")
9
+ st.sidebar.info(
10
+ """
11
+ Web App URL: <https://geospatial.streamlitapp.com>
12
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
13
+ """
14
+ )
15
+
16
+ st.sidebar.title("Contact")
17
+ st.sidebar.info(
18
+ """
19
+ Qiusheng Wu: <https://wetlands.io>
20
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
21
+ """
22
+ )
23
+
24
+
25
+ @st.cache
26
+ def load_cog_list():
27
+ print(os.getcwd())
28
+ in_txt = os.path.join(os.getcwd(), "data/cog_files.txt")
29
+ with open(in_txt) as f:
30
+ return [line.strip() for line in f.readlines()[1:]]
31
+
32
+
33
+ @st.cache
34
+ def get_palettes():
35
+ return list(cm.palettes.keys())
36
+ # palettes = dir(palettable.matplotlib)[:-16]
37
+ # return ["matplotlib." + p for p in palettes]
38
+
39
+
40
+ st.title("Visualize Raster Datasets")
41
+ st.markdown(
42
+ """
43
+ An interactive web app for visualizing local raster datasets and Cloud Optimized GeoTIFF ([COG](https://www.cogeo.org)). The app was built using [streamlit](https://streamlit.io), [leafmap](https://leafmap.org), and [Titiler](https://developmentseed.org/titiler/).
44
+
45
+
46
+ """
47
+ )
48
+
49
+ row1_col1, row1_col2 = st.columns([2, 1])
50
+
51
+ with row1_col1:
52
+ cog_list = load_cog_list()
53
+ cog = st.selectbox("Select a sample Cloud Opitmized GeoTIFF (COG)", cog_list)
54
+
55
+ with row1_col2:
56
+ empty = st.empty()
57
+
58
+ url = empty.text_input(
59
+ "Enter a HTTP URL to a Cloud Optimized GeoTIFF (COG)",
60
+ cog,
61
+ )
62
+
63
+ if url:
64
+ try:
65
+ options = leafmap.cog_bands(url)
66
+ except Exception as e:
67
+ st.error(e)
68
+ if len(options) > 3:
69
+ default = options[:3]
70
+ else:
71
+ default = options[0]
72
+ bands = st.multiselect("Select bands to display", options, default=options)
73
+
74
+ if len(bands) == 1 or len(bands) == 3:
75
+ pass
76
+ else:
77
+ st.error("Please select one or three bands")
78
+
79
+ add_params = st.checkbox("Add visualization parameters")
80
+ if add_params:
81
+ vis_params = st.text_area("Enter visualization parameters", "{}")
82
+ else:
83
+ vis_params = {}
84
+
85
+ if len(vis_params) > 0:
86
+ try:
87
+ vis_params = eval(vis_params)
88
+ except Exception as e:
89
+ st.error(
90
+ f"Invalid visualization parameters. It should be a dictionary. Error: {e}"
91
+ )
92
+ vis_params = {}
93
+
94
+ submit = st.button("Submit")
95
+
96
+ m = leafmap.Map(latlon_control=False)
97
+
98
+ if submit:
99
+ if url:
100
+ try:
101
+ m.add_cog_layer(url, bands=bands, **vis_params)
102
+ except Exception as e:
103
+ with row1_col2:
104
+ st.error(e)
105
+ st.error("Work in progress. Try it again later.")
106
+
107
+ with row1_col1:
108
+ m.to_streamlit()
pages/9_πŸ”²_Vector_Data_Visualization.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import fiona
3
+ import geopandas as gpd
4
+ import streamlit as st
5
+
6
+ st.set_page_config(layout="wide")
7
+
8
+ st.sidebar.title("About")
9
+ st.sidebar.info(
10
+ """
11
+ Web App URL: <https://geospatial.streamlitapp.com>
12
+ GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
13
+ """
14
+ )
15
+
16
+ st.sidebar.title("Contact")
17
+ st.sidebar.info(
18
+ """
19
+ Qiusheng Wu: <https://wetlands.io>
20
+ [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
21
+ """
22
+ )
23
+
24
+
25
+ def save_uploaded_file(file_content, file_name):
26
+ """
27
+ Save the uploaded file to a temporary directory
28
+ """
29
+ import tempfile
30
+ import os
31
+ import uuid
32
+
33
+ _, file_extension = os.path.splitext(file_name)
34
+ file_id = str(uuid.uuid4())
35
+ file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_extension}")
36
+
37
+ with open(file_path, "wb") as file:
38
+ file.write(file_content.getbuffer())
39
+
40
+ return file_path
41
+
42
+
43
+ def app():
44
+
45
+ st.title("Upload Vector Data")
46
+
47
+ row1_col1, row1_col2 = st.columns([2, 1])
48
+ width = 950
49
+ height = 600
50
+
51
+ with row1_col2:
52
+
53
+ backend = st.selectbox(
54
+ "Select a plotting backend", ["folium", "kepler.gl", "pydeck"], index=2
55
+ )
56
+
57
+ if backend == "folium":
58
+ import leafmap.foliumap as leafmap
59
+ elif backend == "kepler.gl":
60
+ import leafmap.kepler as leafmap
61
+ elif backend == "pydeck":
62
+ import leafmap.deck as leafmap
63
+
64
+ url = st.text_input(
65
+ "Enter a URL to a vector dataset",
66
+ "https://github.com/giswqs/streamlit-geospatial/raw/master/data/us_states.geojson",
67
+ )
68
+
69
+ data = st.file_uploader(
70
+ "Upload a vector dataset", type=["geojson", "kml", "zip", "tab"]
71
+ )
72
+
73
+ container = st.container()
74
+
75
+ if data or url:
76
+ if data:
77
+ file_path = save_uploaded_file(data, data.name)
78
+ layer_name = os.path.splitext(data.name)[0]
79
+ elif url:
80
+ file_path = url
81
+ layer_name = url.split("/")[-1].split(".")[0]
82
+
83
+ with row1_col1:
84
+ if file_path.lower().endswith(".kml"):
85
+ fiona.drvsupport.supported_drivers["KML"] = "rw"
86
+ gdf = gpd.read_file(file_path, driver="KML")
87
+ else:
88
+ gdf = gpd.read_file(file_path)
89
+ lon, lat = leafmap.gdf_centroid(gdf)
90
+ if backend == "pydeck":
91
+
92
+ column_names = gdf.columns.values.tolist()
93
+ random_column = None
94
+ with container:
95
+ random_color = st.checkbox("Apply random colors", True)
96
+ if random_color:
97
+ random_column = st.selectbox(
98
+ "Select a column to apply random colors", column_names
99
+ )
100
+
101
+ m = leafmap.Map(center=(lat, lon))
102
+ m.add_gdf(gdf, random_color_column=random_column)
103
+ st.pydeck_chart(m)
104
+
105
+ else:
106
+ m = leafmap.Map(center=(lat, lon), draw_export=True)
107
+ m.add_gdf(gdf, layer_name=layer_name)
108
+ # m.add_vector(file_path, layer_name=layer_name)
109
+ if backend == "folium":
110
+ m.zoom_to_gdf(gdf)
111
+ m.to_streamlit(width=width, height=height)
112
+
113
+ else:
114
+ with row1_col1:
115
+ m = leafmap.Map()
116
+ st.pydeck_chart(m)
117
+
118
+
119
+ app()
postBuild ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # enable nbserverproxy
2
+ jupyter serverextension enable --sys-prefix nbserverproxy
3
+ # streamlit launches at startup
4
+ mv streamlit_call.py ${NB_PYTHON_PREFIX}/lib/python*/site-packages/
5
+ # enable streamlit extension
6
+ jupyter serverextension enable --sys-prefix streamlit_call