Interactive web mapping with Django and Google Earth Engine

Published on Jan 10, 2025 | Bikesh Bade | 84 Views

There are several ways to use GEE and each one has its advantages and disadvantages. In this example, GEE is used for web mapping with Python Django. Django is a fully-featured Python web framework that can be used to build complex web applications. There are endless web development frameworks out there, so why should you learn Django over any of the others? First of all, it’s written in Python, one of the most readable and beginner-friendly programming languages out there. The second reason Google Earth engine provides the Python API. The first step will be to set up Django:

 

Get Started With Django and continue following

To infuse the Django using Google Earth Engine Python API, first, you have to set up a Python environment on your local computer. 

 

Set up Python API for GEE and continue following 

The next requirement will be the Python Module Folium for Mapping, you have to set and get used to with the Folium 

 

Beginner Guide to Python Folium module to integrate Google Earth engine and continue following 

Create the first Django project

django-admin startproject DjangoGEE

 

This will create a new directory DjangoGEE. If you cd In this new directory, you’ll see another directory called DjangoGEE and a file called manage.py. Your directory structure should look something like this:

 DjangoGEE/
    ├── DjangoGEE/
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    │
    └── manage.py

 

Once your file structure is set up, Create a Django Application. To create the app, run the following command:

python manage.py startapp gee

 

This will create another directory called gee with several files:

  • __init__.py tells Python to treat the directory as a Python package.
  • admin.py contains settings for the Django admin pages.
  • apps.py contains settings for the application configuration.
  • models.py contains a series of classes that Django’s ORM converts to database tables.
  • tests.py contains test classes.
  • views.py contains functions and classes that handle what data is displayed in the HTML templates.

 

Once you’ve created the app, you need to install it in your project. In DjangoGEE/settings.py, add the following line of code under INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gee',
]

 

That line of code means that your project now knows that the app you just created exists. The next step is to create a view. Views in Django are a collection of functions or classes inside the views.py  file in your app directory. Each function or class handles the logic that gets processed each time a different URL is visited. Navigate to the views.py file in the gee directory. There’s already a line of code in there that imports render(). Add the following code:

 

from django.shortcuts import render
# generic base view
from django.views.generic import TemplateView 
#folium
import folium
from folium import plugins
#gee
import ee
ee.Initialize()
#home
class home(TemplateView):
    template_name = 'index.html'
    # Define a method for displaying Earth Engine image tiles on a folium map.
    def get_context_data(self, **kwargs):
        figure = folium.Figure()
        
        #create Folium Object
        m = folium.Map(
            location=[28.5973518, 83.54495724],
            zoom_start=8
        )
        #add map to figure
        m.add_to(figure)
        
        #select the Dataset Here's used the MODIS data
        dataset = (ee.ImageCollection('MODIS/006/MOD13Q1')
                  .filter(ee.Filter.date('2019-07-01', '2019-11-30'))
                  .first())
        modisndvi = dataset.select('NDVI')
        #Styling 
        vis_paramsNDVI = {
            'min': 0,
            'max': 9000,
            'palette': [ 'FE8374', 'C0E5DE', '3A837C','034B48',]}
        
        #add the map to the the folium map
        map_id_dict = ee.Image(modisndvi).getMapId(vis_paramsNDVI)
       
        #GEE raster data to TileLayer
        folium.raster_layers.TileLayer(
                    tiles = map_id_dict['tile_fetcher'].url_format,
                    attr = 'Google Earth Engine',
                    name = 'NDVI',
                    overlay = True,
                    control = True
                    ).add_to(m)
        
        #add Layer control
        m.add_child(folium.LayerControl())
       
        #figure 
        figure.render()
         
        #return map
        return {"map": figure}

In this piece of code, we have defined a view function called home(). When this function is called, it will render an HTML file called index.html. Now that we have created the view function, we need to create the HTML template to display to the user. render() looks for HTML templates inside a directory called templates inside your app directory. Create that directory and subsequently a file named index.html inside it:

 

gee/templates/index.html

 

Add the following lines of HTML to your file:

<html>
    <head>
      <title>Django and GEE</title>
      {{ map.header.render|safe }}
      
    </head>
<body>
      <div class="row">
        <div class="col-lg-12">
          {{map.html.render|safe}}
        </div>
      </div>
      <script>
      </script>
</body>
        

 

Now set the URL, when you run the server and visit localhost:8000, you should be able to see the HTML template you created:

 

 

 

Congratulations! You’ve created your  Django app and hooked it up to your GEE. Get all the code in the GitHub

Responses

Leave your comment