{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"Open\n", "\n", "Uncomment the following line to install [geemap](https://geemap.org) if needed." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# !pip install geemap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Using Earth Engine and geemap for mapping surface water dynamics\n", "\n", "**Steps to create Landsat timeseries:**\n", "\n", "1. Pan and zoom to your area of interest (AOI), and click on the map to select a polygon. Alternatively, you can enable `Use user-drawn AOI` and use the Drawing tools (e.g., rectange) to draw a shape on the map.\n", "2. Adjust the parameters (e.g., band combination, threshold, color, download chart data) if needed. \n", "3. Click the `Submit` button to create timeseries of Landsat imagery and normalized difference indices.\n", "\n", "**Web Apps:** https://gishub.org/water-app, https://gishub.org/water-ngrok\n", "\n", "**Contact:** Dr. Qiusheng Wu ([Website](https://wetlands.io/), [LinkedIn](https://www.linkedin.com/in/qiushengwu), [Twitter](https://twitter.com/giswqs), [YouTube](https://www.youtube.com/c/QiushengWu))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check geemap installation\n", "import subprocess\n", "\n", "try:\n", " import geemap\n", "except ImportError:\n", " print('geemap package is not installed. Installing ...')\n", " subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import libraries\n", "import os\n", "import ee\n", "import geemap\n", "import ipywidgets as widgets\n", "from bqplot import pyplot as plt\n", "from ipyleaflet import WidgetControl" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create an interactive map\n", "Map = geemap.Map(center=[40, -100], zoom=4, add_google_map=False)\n", "Map.add_basemap('HYBRID')\n", "Map.add_basemap('ROADMAP')\n", "\n", "# Add Earth Engine data\n", "fc = ee.FeatureCollection('TIGER/2018/Counties')\n", "Map.addLayer(fc, {}, 'US Counties')\n", "\n", "states = ee.FeatureCollection('TIGER/2018/States')\n", "# Map.addLayer(states, {}, 'US States')\n", "\n", "Map" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Designe interactive widgets\n", "\n", "style = {'description_width': 'initial'}\n", "\n", "output_widget = widgets.Output(layout={'border': '1px solid black'})\n", "output_control = WidgetControl(widget=output_widget, position='bottomright')\n", "Map.add_control(output_control)\n", "\n", "admin1_widget = widgets.Text(\n", " description='State:',\n", " value='Tennessee',\n", " width=200,\n", " style=style\n", ")\n", "\n", "admin2_widget = widgets.Text(\n", " description='County:',\n", " value='Knox',\n", " width=300,\n", " style=style\n", ")\n", "\n", "aoi_widget = widgets.Checkbox(\n", " value=False,\n", " description='Use user-drawn AOI',\n", " style=style\n", ")\n", "\n", "download_widget = widgets.Checkbox(\n", " value=False,\n", " description='Download chart data',\n", " style=style\n", ")\n", "\n", "def aoi_change(change):\n", " Map.layers = Map.layers[:4] \n", " Map.user_roi = None\n", " Map.user_rois = None\n", " Map.draw_count = 0\n", " admin1_widget.value = ''\n", " admin2_widget.value = ''\n", " output_widget.clear_output()\n", " \n", "aoi_widget.observe(aoi_change, names='value')\n", "\n", "band_combo = widgets.Dropdown(\n", " description='Band combo:',\n", " options=['Red/Green/Blue', 'NIR/Red/Green', 'SWIR2/SWIR1/NIR', 'NIR/SWIR1/Red','SWIR2/NIR/Red', \n", " 'SWIR2/SWIR1/Red', 'SWIR1/NIR/Blue', 'NIR/SWIR1/Blue', 'SWIR2/NIR/Green', 'SWIR1/NIR/Red'],\n", " value='NIR/Red/Green',\n", " style=style\n", ")\n", "\n", "year_widget = widgets.IntSlider(min=1984, max=2020, value=2010, description='Selected year:', width=400, style=style)\n", "\n", "fmask_widget = widgets.Checkbox(\n", " value=True,\n", " description='Apply fmask(remove cloud, shadow, snow)',\n", " style=style\n", ")\n", "\n", "\n", "# Normalized Satellite Indices: https://www.usna.edu/Users/oceano/pguth/md_help/html/norm_sat.htm\n", "\n", "nd_options = ['Vegetation Index (NDVI)', \n", " 'Water Index (NDWI)',\n", " 'Modified Water Index (MNDWI)',\n", " 'Snow Index (NDSI)',\n", " 'Soil Index (NDSI)',\n", " 'Burn Ratio (NBR)',\n", " 'Customized']\n", "nd_indices = widgets.Dropdown(options=nd_options, value='Modified Water Index (MNDWI)', description='Normalized Difference Indes:', style=style)\n", "\n", "first_band = widgets.Dropdown(\n", " description='1st band:',\n", " options=['Blue', 'Green','Red','NIR', 'SWIR1', 'SWIR2'],\n", " value='Green',\n", " style=style\n", ")\n", "\n", "second_band = widgets.Dropdown(\n", " description='2nd band:',\n", " options=['Blue', 'Green','Red','NIR', 'SWIR1', 'SWIR2'],\n", " value='SWIR1',\n", " style=style\n", ")\n", "\n", "nd_threshold = widgets.FloatSlider(\n", " value=0,\n", " min=-1,\n", " max=1,\n", " step=0.01,\n", " description='Threshold:',\n", " orientation='horizontal',\n", " style=style\n", ")\n", "\n", "nd_color = widgets.ColorPicker(\n", " concise=False,\n", " description='Color:',\n", " value='blue',\n", " style=style\n", ")\n", "\n", "def nd_index_change(change):\n", " if nd_indices.value == 'Vegetation Index (NDVI)':\n", " first_band.value = 'NIR'\n", " second_band.value = 'Red'\n", " elif nd_indices.value == 'Water Index (NDWI)':\n", " first_band.value = 'NIR'\n", " second_band.value = 'SWIR1' \n", " elif nd_indices.value == 'Modified Water Index (MNDWI)':\n", " first_band.value = 'Green'\n", " second_band.value = 'SWIR1' \n", " elif nd_indices.value == 'Snow Index (NDSI)':\n", " first_band.value = 'Green'\n", " second_band.value = 'SWIR1'\n", " elif nd_indices.value == 'Soil Index (NDSI)':\n", " first_band.value = 'SWIR1'\n", " second_band.value = 'NIR' \n", " elif nd_indices.value == 'Burn Ratio (NBR)':\n", " first_band.value = 'NIR'\n", " second_band.value = 'SWIR2'\n", " elif nd_indices.value == 'Customized':\n", " first_band.value = None\n", " second_band.value = None\n", " \n", "nd_indices.observe(nd_index_change, names='value')\n", "\n", "submit = widgets.Button(\n", " description='Submit',\n", " button_style='primary',\n", " tooltip='Click me',\n", " style=style\n", ")\n", "\n", "full_widget = widgets.VBox([\n", " widgets.HBox([admin1_widget, admin2_widget, aoi_widget, download_widget]),\n", " widgets.HBox([band_combo, year_widget, fmask_widget]),\n", " widgets.HBox([nd_indices, first_band, second_band, nd_threshold, nd_color]),\n", " submit\n", "])\n", "\n", "full_widget" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Capture user interaction with the map\n", "\n", "def handle_interaction(**kwargs):\n", " latlon = kwargs.get('coordinates')\n", " if kwargs.get('type') == 'click' and not aoi_widget.value:\n", " Map.default_style = {'cursor': 'wait'}\n", " xy = ee.Geometry.Point(latlon[::-1])\n", " selected_fc = fc.filterBounds(xy)\n", " \n", " with output_widget:\n", " output_widget.clear_output()\n", " \n", " try:\n", " feature = selected_fc.first()\n", " admin2_id = feature.get('NAME').getInfo()\n", " statefp = feature.get('STATEFP')\n", " admin1_fc = ee.Feature(states.filter(ee.Filter.eq('STATEFP', statefp)).first()) \n", " admin1_id = admin1_fc.get('NAME').getInfo()\n", " admin1_widget.value = admin1_id\n", " admin2_widget.value = admin2_id\n", " Map.layers = Map.layers[:4] \n", " geom = selected_fc.geometry()\n", " layer_name = admin1_id + '-' + admin2_id\n", " Map.addLayer(ee.Image().paint(geom, 0, 2), {'palette': 'red'}, layer_name) \n", " print(layer_name)\n", " except:\n", " print('No feature could be found')\n", " Map.layers = Map.layers[:4] \n", " \n", " Map.default_style = {'cursor': 'pointer'}\n", " else:\n", " Map.draw_count = 0\n", "\n", "Map.on_interaction(handle_interaction)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Click event handler\n", "\n", "def submit_clicked(b):\n", " \n", " with output_widget:\n", " output_widget.clear_output()\n", " print('Computing...')\n", " Map.default_style = {'cursor': 'wait'}\n", "\n", " try:\n", " admin1_id = admin1_widget.value\n", " admin2_id = admin2_widget.value\n", " band1 = first_band.value\n", " band2 = second_band.value\n", " selected_year = year_widget.value\n", " threshold = nd_threshold.value\n", " bands = band_combo.value.split('/')\n", " apply_fmask = fmask_widget.value\n", " palette = nd_color.value\n", " use_aoi = aoi_widget.value\n", " download = download_widget.value\n", " \n", " if use_aoi:\n", " if Map.user_roi is not None:\n", " roi = Map.user_roi\n", " layer_name = 'User drawn AOI'\n", " geom = roi\n", " else:\n", " output_widget.clear_output() \n", " print('No user AOI could be found.')\n", " return\n", " else:\n", " \n", " statefp = ee.Feature(states.filter(ee.Filter.eq('NAME', admin1_id)).first()).get('STATEFP')\n", " roi = fc.filter(ee.Filter.And(ee.Filter.eq('NAME', admin2_id), ee.Filter.eq('STATEFP', statefp)))\n", " layer_name = admin1_id + '-' + admin2_id\n", " geom = roi.geometry()\n", "\n", "\n", " Map.layers = Map.layers[:4] \n", " Map.addLayer(ee.Image().paint(geom, 0, 2), {'palette': 'red'}, layer_name) \n", " \n", " images = geemap.landsat_timeseries(roi=roi, start_year=1984, end_year=2020, start_date='01-01', end_date='12-31', apply_fmask=apply_fmask)\n", " nd_images = images.map(lambda img: img.normalizedDifference([band1, band2]))\n", " result_images = nd_images.map(lambda img: img.gt(threshold))\n", "\n", " selected_image = ee.Image(images.toList(images.size()).get(selected_year - 1984))\n", " selected_result_image = ee.Image(result_images.toList(result_images.size()).get(selected_year - 1984)).selfMask()\n", " \n", " vis_params = {\n", " 'bands': bands,\n", " 'min': 0,\n", " 'max': 3000\n", " }\n", " \n", " Map.addLayer(selected_image, vis_params, 'Landsat ' + str(selected_year))\n", " Map.addLayer(selected_result_image, {'palette': palette}, 'Result ' + str(selected_year))\n", "\n", " \n", " def cal_area(img):\n", " pixel_area = img.multiply(ee.Image.pixelArea()).divide(1e4)\n", " img_area = pixel_area.reduceRegion(**{\n", " 'geometry': geom,\n", " 'reducer': ee.Reducer.sum(),\n", " 'scale': 1000,\n", " 'maxPixels': 1e12,\n", " 'bestEffort': True\n", " })\n", " return img.set({'area': img_area})\n", " \n", " areas = result_images.map(cal_area)\n", " stats = areas.aggregate_array('area').getInfo()\n", " x = list(range(1984, 2021))\n", " y = [item.get('nd') for item in stats]\n", " \n", " fig = plt.figure(1)\n", " fig.layout.height = '270px'\n", " plt.clear()\n", " plt.plot(x, y)\n", " plt.title('Temporal trend (1984-2020)')\n", " plt.xlabel('Year')\n", " plt.ylabel('Area (ha)')\n", " \n", " output_widget.clear_output() \n", "\n", " plt.show()\n", " \n", " if download:\n", " out_dir = os.path.join(os.path.expanduser('~'), 'Downloads')\n", " out_name = 'chart_' + geemap.random_string() + '.csv'\n", " out_csv = os.path.join(out_dir, out_name)\n", " if not os.path.exists(out_dir):\n", " os.makedirs(out_dir)\n", " with open(out_csv, 'w') as f:\n", " f.write('year, area (ha)\\n')\n", " for index, item in enumerate(x):\n", " line = '{},{:.2f}\\n'.format(item, y[index])\n", " f.write(line) \n", " link = geemap.create_download_link(\n", " out_csv, title=\"Click here to download the chart data: \")\n", " display(link)\n", " \n", " except Exception as e:\n", " print(e)\n", " print('An error occurred during computation.') \n", "\n", " Map.default_style = {'cursor': 'default'}\n", "\n", "submit.on_click(submit_clicked)" ] } ], "metadata": { "gist": { "data": { "description": "notebooks/wetland_mapping.ipynb", "public": true }, "id": "" }, "hide_input": true, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Table of Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }