{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", "
View source on GitHubNotebook Viewer Run in Google Colab
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Install Earth Engine API and geemap\n", "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n", "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Installs geemap package\n", "import subprocess\n", "\n", "try:\n", " import geemap\n", "except ImportError:\n", " print('geemap package not installed. Installing ...')\n", " subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap']) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ee\n", "import geemap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create an interactive map" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Map = geemap.Map(center=(40, -100), zoom=4)\n", "Map" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add Earth Engine Python script" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add Earth Engine dataset\n", "image = ee.Image('USGS/SRTMGL1_003')\n", "\n", "# Set visualization parameters.\n", "vis_params = {\n", " 'min': 0,\n", " 'max': 4000,\n", " 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}\n", "\n", "# Print the elevation of Mount Everest.\n", "xy = ee.Geometry.Point([86.9250, 27.9881])\n", "elev = image.sample(xy, 30).first().get('elevation').getInfo()\n", "print('Mount Everest elevation (m):', elev)\n", "\n", "# Add Earth Engine layers to Map\n", "Map.addLayer(image, vis_params, 'SRTM DEM', True, 0.5)\n", "Map.addLayer(xy, {'color': 'red'}, 'Mount Everest')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Change map positions\n", "\n", "For example, center the map on an Earth Engine object:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Map.centerObject(ee_object=xy, zoom=13)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Set the map center using coordinates (longitude, latitude)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Map.setCenter(lon=-100, lat=40, zoom=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extract information from Earth Engine data based on user inputs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ee\n", "import geemap\n", "from ipyleaflet import *\n", "from ipywidgets import Label\n", "\n", "try:\n", " ee.Initialize()\n", "except Exception as e:\n", " ee.Authenticate()\n", " ee.Initialize()\n", "\n", "Map = geemap.Map(center=(40, -100), zoom=4)\n", "Map.default_style = {'cursor': 'crosshair'}\n", "\n", "# Add Earth Engine dataset\n", "image = ee.Image('USGS/SRTMGL1_003')\n", "\n", "# Set visualization parameters.\n", "vis_params = {\n", " 'min': 0,\n", " 'max': 4000,\n", " 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}\n", "\n", "# Add Earth Eninge layers to Map\n", "Map.addLayer(image, vis_params, 'SRTM DEM', True, 0.5)\n", "\n", "latlon_label = Label()\n", "elev_label = Label()\n", "display(latlon_label)\n", "display(elev_label)\n", "coordinates = []\n", "markers = []\n", "marker_cluster = MarkerCluster(name=\"Marker Cluster\")\n", "Map.add_layer(marker_cluster)\n", "\n", "def handle_interaction(**kwargs):\n", " latlon = kwargs.get('coordinates')\n", " if kwargs.get('type') == 'mousemove':\n", " latlon_label.value = \"Coordinates: {}\".format(str(latlon))\n", " elif kwargs.get('type') == 'click':\n", " coordinates.append(latlon)\n", "# Map.add_layer(Marker(location=latlon))\n", " markers.append(Marker(location=latlon))\n", " marker_cluster.markers = markers\n", " xy = ee.Geometry.Point(latlon[::-1])\n", " elev = image.sample(xy, 30).first().get('elevation').getInfo()\n", " elev_label.value = \"Elevation of {}: {} m\".format(latlon, elev)\n", "Map.on_interaction(handle_interaction)\n", "\n", "Map" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ee\n", "import geemap\n", "from ipyleaflet import *\n", "from bqplot import pyplot as plt\n", "\n", "try:\n", " ee.Initialize()\n", "except Exception as e:\n", " ee.Authenticate()\n", " ee.Initialize()\n", "\n", "Map = geemap.Map(center=(40, -100), zoom=4)\n", "Map.default_style = {'cursor': 'crosshair'}\n", "\n", "# Compute the trend of nighttime lights from DMSP.\n", "# Add a band containing image date as years since 1990.\n", "def createTimeBand(img):\n", " year = img.date().difference(ee.Date('1991-01-01'), 'year')\n", " return ee.Image(year).float().addBands(img)\n", "\n", "NTL = ee.ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS') \\\n", " .select('stable_lights')\n", "\n", "# Fit a linear trend to the nighttime lights collection.\n", "collection = NTL.map(createTimeBand)\n", "fit = collection.reduce(ee.Reducer.linearFit())\n", "\n", "image = NTL.toBands()\n", "\n", "figure = plt.figure(1, title='Nighttime Light Trend', layout={'max_height': '250px', 'max_width': '400px'})\n", "count = collection.size().getInfo()\n", "start_year = 1992\n", "end_year = 2013\n", "x = range(1, count+1)\n", "\n", "coordinates = []\n", "markers = []\n", "marker_cluster = MarkerCluster(name=\"Marker Cluster\")\n", "Map.add_layer(marker_cluster)\n", "\n", "def handle_interaction(**kwargs):\n", " latlon = kwargs.get('coordinates')\n", " if kwargs.get('type') == 'click':\n", " coordinates.append(latlon)\n", " markers.append(Marker(location=latlon))\n", " marker_cluster.markers = markers\n", " xy = ee.Geometry.Point(latlon[::-1])\n", " y = image.sample(xy, 500).first().toDictionary().values().getInfo()\n", " plt.clear()\n", " plt.plot(x, y)\n", "# plt.xticks(range(start_year, end_year, 5))\n", "Map.on_interaction(handle_interaction)\n", "\n", "# Display a single image\n", "Map.addLayer(ee.Image(collection.select('stable_lights').first()), {'min': 0, 'max': 63}, 'First image')\n", "\n", "# Display trend in red/blue, brightness in green.\n", "Map.setCenter(30, 45, 4)\n", "Map.addLayer(fit,\n", " {'min': 0, 'max': [0.18, 20, -0.18], 'bands': ['scale', 'offset', 'scale']},\n", " 'stable lights trend')\n", "\n", "fig_control = WidgetControl(widget=figure, position='bottomright')\n", "Map.add_control(fig_control)\n", "\n", "Map" ] } ], "metadata": { "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" } }, "nbformat": 4, "nbformat_minor": 4 }