Py.Cafe

vedhavora/

earth-engine-folium-map

Earth Engine & Folium Interactive Map

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
import folium
import ee
import solara
from datetime import datetime
# Import the folium library.
import folium
from folium import plugins
import json


from google.auth import impersonated_credentials
from google.auth.transport.requests import Request
from google.oauth2 import service_account

# Initialize Earth Engine
def init():
    json_data = '''
    {
    "type": "service_account",
    "project_id": "ee-vedhavora",
    "private_key_id": "9e0b7461fa5701409a17ee79a01ebbcd9f9c31f2",
    "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC0Ur8QYMAnqEG2\nFYppJcFzWL24eBexNglFpAtuYqE+DWzUCmZLi00+j1Ui5r5ndEDXCM+B8odDeyac\nBxLC0IoEK8MbijUpNdvbSqnlWtxdt4SJot0LjDo/7IFr/upgjad4AR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fPXEus9awte6ctOMqCU2Ru28fPopbkxIZ1F3oPGxqRPlG00G0XwKBgBoD\nVkDuqvG84YwgCpdf4XwJFmsSDNGSaZdTdACBuRQhNZCsa9tb3A2KZzZPQrTABOfc\nWcLbSwoLv9Uiy9PGzckD4C8ZaqaIUvlD74OFm7hX7qy/aS+LsNGbjAK+g2MaEG1R\n6/amyRwS1F8afjZy/7unWjtkksEQKL6IXWiQQ4ZFAoGBAIrnuVkp0zXQdiNTKKK1\nuHViAamUgUkf0EpzfuinmrNBBjY4DaKBVFicwTJvXrPVvsuc0bTM9dbl44lbJdP7\n2lYOaLt+eLXDkgH1aQpgBr2WdK/9SBfzZxLtkdMmHHKSikgx1X/B5ORp1VMXmnD1\nWV4uQlDafUL6DMw6omrk94jZ\n-----END PRIVATE KEY-----\n",
    "client_email": "vedhavora@ee-vedhavora.iam.gserviceaccount.com",
    "client_id": "106372244789242444844",
    "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/vedhavora%40ee-vedhavora.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)

init()

# Create a folium map object.
my_map = folium.Map(location=[40.33, -99.42], zoom_start=4, height=500)

# Add custom basemaps to folium
basemaps = {
    'Google Maps': folium.TileLayer(
        tiles = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
        attr = 'Google',
        name = 'Google Maps',
        overlay = True,
        control = True
    ),
    'Google Satellite': folium.TileLayer(
        tiles = 'https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
        attr = 'Google',
        name = 'Google Satellite',
        overlay = True,
        control = True
    ),
    'Google Terrain': folium.TileLayer(
        tiles = 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',
        attr = 'Google',
        name = 'Google Terrain',
        overlay = True,
        control = True
    ),
    'Google Satellite Hybrid': folium.TileLayer(
        tiles = 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',
        attr = 'Google',
        name = 'Google Satellite',
        overlay = True,
        control = True
    ),
    'Esri Satellite': folium.TileLayer(
        tiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        attr = 'Esri',
        name = 'Esri Satellite',
        overlay = True,
        control = True
    )
}

# Define a method for displaying Earth Engine image tiles on a folium map.
def add_ee_layer(self, ee_object, vis_params, name):
    
    try:    
        # display ee.Image()
        if isinstance(ee_object, ee.image.Image):    
            map_id_dict = ee.Image(ee_object).getMapId(vis_params)
            folium.raster_layers.TileLayer(
            tiles = map_id_dict['tile_fetcher'].url_format,
            attr = 'Google Earth Engine',
            name = name,
            overlay = True,
            control = True
            ).add_to(self)
        # display ee.ImageCollection()
        elif isinstance(ee_object, ee.imagecollection.ImageCollection):    
            ee_object_new = ee_object.mosaic()
            map_id_dict = ee.Image(ee_object_new).getMapId(vis_params)
            folium.raster_layers.TileLayer(
            tiles = map_id_dict['tile_fetcher'].url_format,
            attr = 'Google Earth Engine',
            name = name,
            overlay = True,
            control = True
            ).add_to(self)
        # display ee.Geometry()
        elif isinstance(ee_object, ee.geometry.Geometry):    
            folium.GeoJson(
            data = ee_object.getInfo(),
            name = name,
            overlay = True,
            control = True
        ).add_to(self)
        # display ee.FeatureCollection()
        elif isinstance(ee_object, ee.featurecollection.FeatureCollection):  
            ee_object_new = ee.Image().paint(ee_object, 0, 2)
            map_id_dict = ee.Image(ee_object_new).getMapId(vis_params)
            folium.raster_layers.TileLayer(
            tiles = map_id_dict['tile_fetcher'].url_format,
            attr = 'Google Earth Engine',
            name = name,
            overlay = True,
            control = True
        ).add_to(self)
    
    except:
        print("Could not display {}".format(name))
    
# Add EE drawing method to folium.
folium.Map.add_ee_layer = add_ee_layer

def example_code():
    
    # Set visualization parameters.
    vis_params = {
    'min': 0,
    'max': 4000,
    'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}

    # Add custom basemaps
    basemaps['Google Maps'].add_to(my_map)
    basemaps['Google Satellite Hybrid'].add_to(my_map)

    # Add the elevation model to the map object.
    dem = ee.Image('USGS/SRTMGL1_003')
    my_map.add_ee_layer(dem.updateMask(dem.gt(0)), vis_params, 'DEM')

    # Display ee.Image
    dataset = ee.Image('JRC/GSW1_1/GlobalSurfaceWater')
    occurrence = dataset.select('occurrence');
    occurrenceVis = {'min': 0.0, 'max': 100.0, 'palette': ['ffffff', 'ffbbbb', '0000ff']}
    my_map.add_ee_layer(occurrence, occurrenceVis, 'JRC Surface Water')

    # Display ee.Geometry
    holePoly = ee.Geometry.Polygon(coords = [[[-35, -10], [-35, 10], [35, 10], [35, -10], [-35, -10]]],
                                proj= 'EPSG:4326',
                                geodesic = True,
                                maxError= 1.,
                                evenOdd = False)
    my_map.add_ee_layer(holePoly, {}, 'Polygon')

    # Display ee.FeatureCollection
    fc = ee.FeatureCollection('TIGER/2018/States')
    my_map.add_ee_layer(fc, {}, 'US States')

    # Add a layer control panel to the map.
    my_map.add_child(folium.LayerControl())
    plugins.Fullscreen().add_to(my_map)

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

    # Display ee.Image
    dataset = ee.ImageCollection('MODIS/061/MOD13A2')
    occurrence = dataset.select('NDVI');
    occurrenceVis = {
                        'min': 0, 
                        'max': 9000, 
                        'palette': [
                            'ffffff', 'ce7e45', 'df923d', 'f1b555', 'fcd163', '99b718', '74a901',
                            '66a000', '529400', '3e8601', '207401', '056201', '004c00', '023b01',
                            '012e01', '011d01', '011301'
                        ]
                     }
    filtered_dataset = dataset.filterDate('2015-01-01', '2015-01-31')
    print("filtered_dataset:", filtered_dataset)

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

    # my_map.add_ee_layer(occurrence, occurrenceVis, 'JRC Surface Water')
    my_map.add_ee_layer(ndvi, occurrenceVis, 'NDVI vegetation layer')
    
def add_evapotranspiration_layer():
    print("in add_evapotranspiration_layer")

    # 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
    evapotranspiration_viz_params = {
        'min': -2.33,
        'max': 2.33,
        'palette': [
            '8b1a1a', 'de2929', 'f3641d',
            'fdc404', '9afa94', '03f2fd',
            '12adf3', '1771de', '00008b',
        ]
    }
    my_map.add_ee_layer(spei24, evapotranspiration_viz_params, 'SPEI 24 month evapotranspiration layer')
    
def add_polygon_plugin_to_map():
    # Add the Draw plugin to the map with polygon drawing enabled
    plugins.Draw(
        draw_options={
            'polygon': True,
            'rectangle': False,
            'circle': False,
            'marker': False,
            'polyline': False
        },
        edit_options={'edit': True}
    ).add_to(my_map)

    # Add JavaScript to handle polygon draw and capture coordinates
    draw_script = """
    <script>
    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    var drawControl = new L.Control.Draw({
        draw: {
            polygon: true,
            rectangle: false,
            circle: false,
            marker: false,
            polyline: false
        },
        edit: {
            featureGroup: drawnItems,
        }
    });
    map.addControl(drawControl);

    map.on('draw:created', function (e) {
        var layer = e.layer;
        drawnItems.addLayer(layer);
        if (layer instanceof L.Polygon) {
            var latLngs = layer.getLatLngs();
            var coords = latLngs[0].map(latlng => [latlng.lat, latlng.lng]);
            alert('Polygon Coordinates: \n' + JSON.stringify(coords));
        }
    });
    </script>
    """
    my_map.get_root().html.add_child(folium.Element(draw_script))
                    
@solara.component
def Page():
    # example_code()
    add_vegetation_layer()
    add_evapotranspiration_layer()

    # Add a layer control panel to the map.
    my_map.add_child(folium.LayerControl())

    # Add fullscreen button
    # plugins.Fullscreen().add_to(my_map)
    
    add_polygon_plugin_to_map()
    solara.display(my_map)
    # my_map.save('map_with_polygon_drawing.html')


Page()