Skip to content

Commit

Permalink
Add GEE functions
Browse files Browse the repository at this point in the history
  • Loading branch information
giswqs committed Mar 8, 2020
1 parent 84d9e71 commit 224be18
Show file tree
Hide file tree
Showing 3 changed files with 329 additions and 0 deletions.
164 changes: 164 additions & 0 deletions examples/template.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import geemap\n",
"import ee\n",
"\n",
"try:\n",
" ee.Initialize()\n",
"except Exception as e:\n",
" ee.Authenticate()\n",
" ee.Initialize()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"Map = geemap.Map()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mount Everest elevation (m): 8729\n"
]
}
],
"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 Eninge layers to Map\n",
"Map.addLayer(image, vis_params, 'DEM', True, 0.5)\n",
"Map.addLayer(xy, {'color': 'red'}, 'Mount Everest')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"Map.centerObject(xy, 13)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"Map.setCenter(-100, 40, 8)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"url = 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer?'\n",
"Map.addWmsTileLayer(url=url, layers='0', name='NAIP')"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"url = 'https://elevation.nationalmap.gov/arcgis/services/3DEPElevation/ImageServer/WMSServer?'\n",
"Map.addWmsTileLayer(url=url, layers='3DEPElevation:None')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"Map.addTileLayer(name=\"OSM\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"url = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}'\n",
"Map.addTileLayer(url, name='Google Map', attribution='Google')"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7cd01a48600c4f339b673ed5511e3b30",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Map(center=[40, -100], controls=(ZoomControl(options=['position', 'zoom_in_text', 'zoom_in_title', 'zoom_out_t…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"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.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
2 changes: 2 additions & 0 deletions geemap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
__author__ = """Qiusheng Wu"""
__email__ = 'giswqs@gmail.com'
__version__ = '0.1.0'

from .geemap import *
163 changes: 163 additions & 0 deletions geemap/geemap.py
Original file line number Diff line number Diff line change
@@ -1 +1,164 @@
"""Main module."""

import os
import ee
import ipyleaflet
from ipyleaflet import *

# Create an ipyleaflet map instance
def Map(center=(40, -100), zoom=4, layers=None):
m = ipyleaflet.Map(center=center, zoom=zoom)

m.add_control(LayersControl(position='topright'))
m.add_control(ScaleControl(position='bottomleft'))
m.add_control(FullScreenControl())
m.add_control(DrawControl())

measure = MeasureControl(
position='bottomleft',
active_color = 'orange',
primary_length_unit = 'kilometers'
)
m.add_control(measure)

if layers is None:
tile_layer = ipyleaflet.TileLayer(
url='https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',
attribution='Google',
name='Google Satellite'
)
m.add_layer(tile_layer)
else:
m.add_layer(layers)

return m


# Add Earth Engine layer to map
def addLayer(self, ee_object, vis_params={}, name='Layer untitled', shown=True, opacity=1):

image = None

if not isinstance(ee_object, ee.Image) and not isinstance(ee_object, ee.ImageCollection) and not isinstance(ee_object, ee.FeatureCollection) and not isinstance(ee_object, ee.Feature) and not isinstance(ee_object, ee.Geometry):
err_str = "\n\nThe image argument in 'addLayer' function must be an instace of one of ee.Image, ee.Geometry, ee.Feature or ee.FeatureCollection."
raise AttributeError(err_str)

if isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature) or isinstance(ee_object, ee.featurecollection.FeatureCollection):
features = ee.FeatureCollection(ee_object)

width = 2

if 'width' in vis_params:
width = vis_params['width']

color = '000000'

if 'color' in vis_params:
color = vis_params['color']

image_fill = features.style(
**{'fillColor': color}).updateMask(ee.Image.constant(0.5))
image_outline = features.style(
**{'color': color, 'fillColor': '00000000', 'width': width})

image = image_fill.blend(image_outline)
elif isinstance(ee_object, ee.image.Image):
image = ee_object
elif isinstance(ee_object, ee.imagecollection.ImageCollection):
image = ee_object.median()

map_id_dict = ee.Image(image).getMapId(vis_params)
tile_layer = ipyleaflet.TileLayer(
url=map_id_dict['tile_fetcher'].url_format,
attribution='Google Earth Engine',
name=name,
opacity=opacity,
# visible=shown
)
self.add_layer(tile_layer)

ipyleaflet.Map.addLayer = addLayer


# Set map center
def setCenter(self, lon, lat, zoom=None):
self.center = (lat, lon)
if zoom is not None:
self.zoom = zoom

ipyleaflet.Map.setCenter = setCenter


# Center the map based on an object
def centerObject(self, ee_object, zoom=None):

lat = 0
lon = 0
bounds = [[lat, lon], [lat, lon]]
if isinstance(ee_object, ee.geometry.Geometry):
centroid = ee_object.centroid()
lon, lat = centroid.getInfo()['coordinates']
bounds = [[lat, lon], [lat, lon]]
elif isinstance(ee_object, ee.featurecollection.FeatureCollection):
centroid = ee_object.geometry().centroid()
lon, lat = centroid.getInfo()['coordinates']
bounds = [[lat, lon], [lat, lon]]
elif isinstance(ee_object, ee.image.Image):
geometry = ee_object.geometry()
coordinates = geometry.getInfo()['coordinates'][0]
bounds = [coordinates[0][::-1], coordinates[2][::-1]]
elif isinstance(ee_object, ee.imagecollection.ImageCollection):
geometry = ee_object.geometry()
coordinates = geometry.getInfo()['coordinates'][0]
bounds = [coordinates[0][::-1], coordinates[2][::-1]]
else:
bounds = [[0, 0], [0, 0]]

self.setCenter(lon, lat, zoom)

ipyleaflet.Map.centerObject = centerObject


# Add custom WMS tile layer to map
def addWmsTileLayer(self, url, layers, name=None, attribution='', format='image/jpeg', transparent=False, opacity=1.0):

if name is None:
name = str(layers)

try:
wms_layer = ipyleaflet.WMSLayer(
url=url,
layers=layers,
name=name,
attribution=attribution,
format=format,
transparent =transparent,
opacity=opacity
)
self.add_layer(wms_layer)
except:
print("Failed to add the specified WMS TileLayer.")

ipyleaflet.Map.addWmsTileLayer = addWmsTileLayer


# Add custom tile layer to map
def addTileLayer(self, url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', name=None, attribution='', opacity=1):
try:
tile_lyaer = ipyleaflet.TileLayer(
url=url,
name=name,
attribution=attribution,
opacity=opacity
)
self.add_layer(tile_lyaer)
except:
print("Failed to add the specified TileLayer.")

ipyleaflet.Map.addTileLayer = addTileLayer


if __name__ == '__main__':

map = Map()
map

0 comments on commit 224be18

Please sign in to comment.