Py.Cafe

contact.nirav.v/

geemap-interactive-components-showcase

Geemap Interactive Components Showcase

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import streamlit as st
import numpy as np
import pandas as pd
import ee
import geemap.foliumap as geemap
from google.oauth2 import id_token
from google.auth.transport import requests
from google.auth import compute_engine
import json

st.set_page_config(layout="wide")

st.sidebar.info(
    """
    - Web App URL: <https://streamlit.geemap.org>
    - GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
    """
)

st.sidebar.title("Contact")
st.sidebar.info(
    """
    Qiusheng Wu: <https://wetlands.io>
    [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
    """
)

Map = geemap.Map()

# Define ROI (California coordinates: Latitude and longitude coordinates are: 36.778259, -119.417931.)
regionOfInterest = ee.Geometry.Point(-119.417931, 36.778259)

vegetation_image = None
evapotranspiration_image = None
composite_image = None


def app():
    st.title("Your Streamlit App - Composite - evapotranspiration_image first")


    # Data from the downloaded JSON file
    json_data = '''
    {
    "type": "service_account",
    "project_id": "contactniravv",
    "private_key_id": "2311ce3809826bb550cb098e057ee2e6068a40ff",
    "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfVeKcdOhL7NCQ\nA9mQiKjF5Ob0HcDk1fUIV+hUAqnQr2EK97kJ7q2sEs4FqhY38k0CBSo4NZybGJks\nI6caNfol7ob/fMnSZkOc0vXb4IWlK5wxsW0bA8eBd1OItB9ydhsP8OsZLexJdOX5\nUimwKgpm3nn0irEVA5Jx88omrtVTilOjeBj+IVSI49JLoI+69fXL01hCa5j3/DJH\nG5LyJ3/VwY9M9ajmQjxGyKCZrT2sQDa5f8XJ9jE/mmtHn68uWEELus81dqXj0Dm0\nB2NgDL7G7MNI8YFw4hP0zC26UHhs7R0kuP2dwwcYB82hQpRsCbwCfFuaLLJlIPuA\ni6u7dRqPAgMBAAECggEARKbfOHVgv5H+PQcDn3Rab8XUQvts6MxNQvaJemUZYPqn\nz+9zkVV/DASgMy2ZXCqwxn2ONuDWpLbhDHUiIzd9nAldrkhItzhrym7VExN20fdr\n2bduYLTsqZpN6jld0VYVC/XMfjFcvTu6eQXPQ4GhsLgMCPMXIIxE9YdKowcykEb7\n8YA4FagRDst7nidPWs4zaOXQEQ10HYopoCGaRXd5DoYl2NXD4NdzkamoS0+K5aKt\nAwx3Mgp1aHo+ymQvdSQAwFLz7eym9BDxVJHKIQlXrJb/ouvRmxC6KD8KXe7eVqRb\n7qiVPpSSnEFfxjK1F1X9KEtbz2P/EMklvu9dSw2z2QKBgQDO/pfVcqYKdzmUrWJG\nAMRcCeS0y/Gf+yyWXmPp9Yo3kDIlhZDnjrYLi298IDRJPeXZDQkZA8jzYXB4hGn3\ni4VCh20VDNhXJF+mE3RFrWKeP5QTwMMmroygQk6GWskW91qPZMtSXtW5m7sQDb6f\nV4TJzW6BSzgoiP0Dp+luf91apwKBgQDFDs0ceeo5Fc7KeFyi3zEBPXMGRh5SxI3e\nyTTkwzYHp3UE0g3bKS5q3Jmf3x3wlLlYFkbwvv/nPReVL9/npXnx3xH1IkMtfezw\nnLT654KiQ19yYyf2ePgTONngURIuvoPwT2R71XpZYIo5wIO258mDFCUAcldnN2IG\nO6/6AUIF2QKBgQCLVz00lbIKd4nOeQ0fnKKSZqKLxoJINJgmPTI7K2w4zRvEwG30\nQtBvYxTQVQl9iGpyu2C1cyPSGnTQ3CpNVqGFUI7wza3Qs46jyJLL2NT7PEddKLT2\nFChcNWaQ8QpPKIHQ54QrVeW/xYKeYvJAZ3TfOCg8ZztNpjHURTNRjEehHwKBgQCn\ndjKctoZzyLKZobunteChWyU6+a+fSuX9pCPNHI/35TkuxYt86fxGV/49vJBm+Ryh\nXR0gTlCOpH48DBlNdHSzNYy/M0S/jjojKCks6D09w9+DB/zYGmlHfJK7bGn1S3Y4\nbF/KVNrKxZ3yAkZs04GOYToorQLV9lzZSzP7U8JV0QKBgEUzZAy52HtD1fGaqFw7\nHA6DKkxIgSwsUKZT+l+C3gK/I7py1zEpp6BZnLunNLIqIdvr8v4Mg4wZwbKcEL3c\nkbSyy8UDIFMUCe19y1zPdxBe9PngJYIkKVxAr5xR1/zB0n6cPX0ZX1Jc9900DLlJ\nNrXJpx1EflUlNzxEOve2kKr2\n-----END PRIVATE KEY-----\n",
    "client_email": "contactniravv@contactniravv.iam.gserviceaccount.com",
    "client_id": "107657170325250962617",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/contactniravv%40contactniravv.iam.gserviceaccount.com",
    "universe_domain": "googleapis.com"
    }
    '''
    # Preparing values
    json_object = json.loads(json_data, strict=False)
    service_account = json_object['client_email']
    json_object = json.dumps(json_object)
    # Authorising the app
    credentials = ee.ServiceAccountCredentials(service_account, key_data=json_object)
    print("credentials = ", credentials)
    ee.Initialize(credentials)

    add_evapotranspiration_layer()
    add_vegetation_layer()

    # Create composite image with above layers
    concat_images()
    # combine_images_method_2()

def add_vegetation_layer():
    print("in add_vegetation_layer")
    global vegetation_image

    # Load the image collection
    dataset = ee.ImageCollection('MODIS/061/MOD13A2') \
        .filterDate('2015-01-01', '2015-01-31') \
        .mean()

    # Select the NDVI band
    ndvi = dataset.select('NDVI')

    # Visualization parameters
    ndviVis = {
        'min': 0,
        'max': 9000,
        'palette': [
            'ffffff', 'ce7e45', 'df923d', 'f1b555', 'fcd163', '99b718', '74a901',
            '66a000', '529400', '3e8601', '207401', '056201', '004c00', '023b01',
            '012e01', '011d01', '011301'
        ]
    }

    # Map = geemap.Map(center=(40.0,-100),zoom=4, width=150,height=500)
    # Map.add_basemap('NSV')
    # Set the map center
    # Map.setCenter(6.746, 46.529, 2)
    # Map.set_center(21.2, 22.2, 2)

    # Map = geemap.Map(center=[40, -100], zoom=4)
    vcolor = st.color_picker('Pick A Color', '#00f900')
    st.write('The current color is', vcolor)

    # st.write(Map)

    translate = {
        "image_collection": "ee.ImageCollection('",
        "image": "ee.Image('",
        "table": "ee.FeatureCollection('",
        "table_collection": "ee.FeatureCollection('",
    }
    ee_assets = geemap.search_ee_data('MODIS/061/MOD13A2')
    print(ee_assets)
    asset_titles = [x["title"] for x in ee_assets]
    print("asset title = ", asset_titles)
    asset_types = [x["type"] for x in ee_assets]
    print("asset type = ", asset_types)
    index = asset_titles.index(asset_titles[0])
    print("index = ", index)
    ee_id = ee_assets[index]["id"]
    print("ee_id = ", ee_id)
    uid = ee_assets[index]["uid"]
    print("uid = ", uid)

    ee_asset = f"{translate[asset_types[index]]}{ee_id}')"
    print("ee_asset = ", ee_asset)

    try:
        print("Adding NDVI vegetation layer/loading to streamlit")
        # Add the NDVI layer to the map
        # vegetation_image = ndvi.filterBounds(regionOfInterest).first()
        vegetation_image = ndvi
        print("vegetation_image:", vegetation_image.getInfo())

        # # Map.addLayer(ndvi, ndviVis, 'NDVI vegetation layer')
        ## Map.addLayer(vegetation_image, ndviVis, 'NDVI vegetation layer')
        # Map.addLayer(eval(ee_asset))
        # st.write(Map)
        # Map.to_streamlit()
    except Exception as e:
        st.error(f"Error adding NDVI vegetation layer/loading to streamlit: {e}")


    # width = 950
    # height = 600
    # row1_col1, row1_col2 = st.columns([3, 1])
    # with row1_col2: 
    #     Map.to_streamlit(width=width, height=height)

    # client_id = "882253985203-c0q9uq25mei210cddbu4r7s78kass0kh.apps.googleusercontent.com"  # Replace with your OAuth client ID
    # token = st.text_input("Enter your Google ID token", type="password")
    # if st.button("Authenticate"):
    #     try:
    #         idinfo = id_token.verify_oauth2_token(token, requests.Request(), client_id)
    #         if idinfo['aud'] != client_id:
    #             raise ValueError("Invalid client ID")
    #         st.success(f"Authentication successful: {idinfo['name']}")
    #         # Continue with the rest of your app logic here
    #     except ValueError as e:
    #         st.error("Authentication failed")
    #         st.error(e)

def add_evapotranspiration_layer():
    print("in add_evapotranspiration_layer")
    global evapotranspiration_image

    # Load the image collection
    dataset = ee.ImageCollection("CSIC/SPEI/2_9") \
        .filterDate('2015-01-01', '2015-01-31') \
        .mean()

    # Select the 24-month analysis
    spei24 = dataset.select('SPEI_24_month')

    # Set the visualization parameters
    visParams = {
        'min': -2.33,
        'max': 2.33,
        'palette': [
            '8b1a1a', 'de2929', 'f3641d',
            'fdc404', '9afa94', '03f2fd',
            '12adf3', '1771de', '00008b',
        ]
    }

    try:
        # Display the SPEI 24-month layer
        print("Adding SPEI 24-month evapotranspiration layer/loading to streamlit")
        # evapotranspiration_image = spei24.filterBounds(regionOfInterest).first()
        evapotranspiration_image = spei24
        print("evapotranspiration_image:", evapotranspiration_image.getInfo())

        # Map.addLayer(spei24, visParams, 'SPEI 24 month evapotranspiration layer')
        ##Map.addLayer(evapotranspiration_image, visParams, 'SPEI 24 month evapotranspiration layer')
        # Map.to_streamlit()
    except Exception as e:
        st.error(f"Error adding SPEI 24-month evapotranspiration layer/loading to streamlit: {e}")

def concat_images():
    print("in concat_images")
    global vegetation_image
    global evapotranspiration_image

    try:
        # Create a concat image with vegetation_image and evapotranspiration_image
        composite_image = ee.Image.cat([evapotranspiration_image, vegetation_image])
        print("composite_image =", composite_image)
        Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI'], 'min': -1, 'max': 1}, 'Composite Image')
        #Map.addLayer(composite_image, name='Concat Image')

        evapotranspiration_viz_params = {
            'bands': ['SPEI_24_month', 'NDVI'],
            'min': -1,
            'max': 1
            # 'palette': [
            #     '8b1a1a', 'de2929', 'f3641d',
            #     'fdc404', '9afa94', '03f2fd',
            #     '12adf3', '1771de', '00008b',
            # ]
        }

        #Map.addLayer(composite_image, name='Concat Image', viz_params=evapotranspiration_viz_params)        

        Map.to_streamlit()
    except Exception as e:
        st.error(f"Error creating concat image: {e}")

def combine_images():
    print("in combine_images")
    global vegetation_image
    global evapotranspiration_image
    # try:
    # Method 1
    # Create a combined image with vegetation_image and evapotranspiration_image
    composite_image = ee.Image.combine_([evapotranspiration_image, vegetation_image])
    print("Combined image:", composite_image.getInfo())
    # Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI']}, name='Composite Image')
    Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI'], 'min': -1, 'max': 1}, 'Composite Image')

    # Map.addLayer(composite_image, name='Combined Image')

    Map.to_streamlit()
    # except Exception as e:
    #     st.error(f"Error creating combined image: {e}")

    # Method 2
    # Create a combined image with vegetation_image and evapotranspiration_image
    # print("evapotranspiration_image image:", evapotranspiration_image)
    # print("vegetation_image image:", vegetation_image.getInfo())
    # composite_image = evapotranspiration_image.addBands(vegetation_image)
    # print("Combined image:", composite_image.getInfo())

    # Map.addLayer(composite_image, name='Combined Image')
    # Map.to_streamlit()

def combine_images_method_2():
    print("in combine_images_method_2")
    global vegetation_image
    global evapotranspiration_image
    # try:
    # Method 2
    # try:
    # Create a combined image with vegetation_image and evapotranspiration_image
    print("evapotranspiration_image image:", evapotranspiration_image)
    print("vegetation_image image:", vegetation_image.getInfo())
    # composite_image = evapotranspiration_image.addBands(vegetation_image)
    composite_image = vegetation_image.addBands(evapotranspiration_image)
    # print("Combined image:", composite_image.getInfo())

    viz_params = {
        'bands': ['SPEI_24_month', 'NDVI'],
        'min': -1,
        'max': 1,
        'gamma': [1, 1, 1]  # Adjust gamma if needed
    }

    evapotranspiration_viz_params = {
        'min': -2.33,
        'max': 2.33,
        'palette': [
            '8b1a1a', 'de2929', 'f3641d',
            'fdc404', '9afa94', '03f2fd',
            '12adf3', '1771de', '00008b',
        ]
    }

    Map.addLayer(composite_image, name='Combined Image', viz_params=evapotranspiration_viz_params)
    Map.to_streamlit()
    # except Exception as e:
    #     st.error(f"Error creating combined image: {e}")

app()