Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

Open in app

Search

Get unlimited access to the best of Medium for less than $1/week. Become a member

BUILDING GEOSPATIAL WEB APPLICATIONS


IN PYTHON VIA DJANGO FRAMEWORK
LAWRENCE KIMUTAI · Follow
7 min read · Jun 22, 2023

Listen Share More

Django is a popular web framework written in Python that simplifies the


development of web applications. You can check out django documentation here
to get to understand the basic concepts and how it works here:

Django
The web framework for perfectionists with deadlines.
docs.djangoproject.com

For this tutorial, I will be using Atom IDE to create a simple geospatial application
together with Python and the django web framework. You can access and
download the application here (check their official website for newer versions):

Atom
Download the latest version of Atom for Windows. The
comprehensive text editor for programmers, created by GitHub…
atom.en.uptodown.com

1 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

The link to the github repository with the whole code and data for this tutorial
can be accessed at. You may clone and impliment your functionalities too:

GitHub - KimutaiLawrence/Geodjangoapp
Contribute to KimutaiLawrence/Geodjangoapp development by
creating an account on GitHub.
github.com

Let us now start!

Open your Anaconda prompt (terminal), go to where you want your project to be
created and install Django ,Folium and geopandas . This will first install the
necessary packages we will use. You then type “django-admin startproject geo”.
This will then start a project by creating a “geo” folder with all the necessary
things in it:

pip install django


pip install folium
pip install geopandas

django-admin startproject geo

2 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

installing Django and Folium

django-admin startproject geo

You can always check out what is contained within your directory by typing out
“dir” and we can see we have a geo folder created in our working directory:

geo folder

3 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

We then type “cd geo” to navigate into the geo folder:

cd geo

We then type the following command which will then create another “geoApp”
folder with some components/ files including a “migrations” folder among
others(In Django, migrations are a way to manage changes to your database
schema over time. They allow you to evolve your database structure as you make
changes to your models without manually modifying the database.):

python manage.py startapp geoApp

We then go ahead to create a new file called urls.py inside the geoApp and type
the following code:

from django.urls import path


from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
path('',views.home, name='home')
]

We then also go to the previous urls.py file in the main ‘geo’ folder and add the
following lines of code. Yes, there is some code in the file already provided for
you( NB: This is how weregister our “geoApp/urls.py” inside “geo/urls.py”):

from django.contrib import admin


from django.urls import path, include #added 'include' to include our geoApp url

urlpatterns = [

4 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

path("admin/", admin.site.urls),
path('', include('geoApp.urls')),#this line is what we add
]

We then create a templates folder inside the geoApp folder called “templates” and
another folder within the templates folder called “geoApp”, with where we will
place our html file.

We then go to the settings.py file, add some code and add some static files and
root as follows(note: there is already some code provided within the file):

import os

MEDIA_URL = "media/"

STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

We save and then add 2 new folders to the root “static” and “media”

5 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

Adding static and media folders

You then follow the following link to download important files with which you
will extract, then copy and paste boostrap and jquery folders into the static folder.
The files contain bootstrap and jquery files with which we will use :

geo.zip
Edit description
drive.google.com

or alternatively from the github repo

https://github.com/KimutaiLawrence/Geodjangoapp/blob/master/geo.zip

We then go to setting.py and add our app otherwise django won’t recognize our
app is in the project:

# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",

6 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"geoApp",
]

We then specify where templates will be located and be read:

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, 'geoApp', 'templates')
],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

We then go to view.py and write:

from django.shortcuts import render, redirect

# Create your views here.


def home(request):
context = {}
return render(request, 'geoApp/home.html', context)

We then go in the templates folder>geoApp> and now create a new file


“home.html” where you will then copy the following html code into it:

7 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no
<meta name="description" content="">
<meta name="author" content="">

<title>GeospatialIntelligence</title>

<!-- Bootstrap core CSS -->


<link rel="stylesheet" href="{% static '/bootstrap/css/bootstrap.min.css' %}"

<!-- Custom CSS -->


<style>
.navbar-brand .twitter-handle {
color: #1DA1F2; /* Twitter blue color */
margin-left: 5px;
}

.lead {
color: #FF3366; /* Custom color for lead text */
}
</style>

</head>

<body>

<!-- Navigation -->


<nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
<div class="container">
<a class="navbar-brand" href="https://twitter.com/lawrence_kim_">Geospatial Prim
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="">Welcome</a>
</li>
</ul>
</div>
</div>

8 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

</nav>

<!-- Page Content -->


<div class="container">
<div class="row">

<div class="col-lg-12 text-center">


<h1 class="mt-5">Geospatial Application</h1>
<p class="lead text-danger">You´ll be seeing shapefiles stored in the Database

<ul class="list-unstyled">
<li>Developed by Lawrence Kimutai</li>
<li>2023</li>
<li>Contact: +254759629059</li>
</ul>
</div>
</div>
</div>

<!-- Bootstrap core JavaScript -->


<script src="{% static '/jquery/jquery.slim.min.js' %}"></script>
<script src="{% static '/bootstrap/js/bootstrap.bundle.min.js' %}"></script>

</body>

</html>

We then run our app. We type the following into the terminal:

python manage.py runserver

NB: if you face a migartion error, you could solve it as follows:

9 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

Migration files

python manage.py migrate

On running the “python manage.py runserver” command you should see a link in
the terminal with which you can copy and paste on your browser from where you
can see your application:

10 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

skeleton application

We then go ahead and copy the and paste shapefile folder from the zipped folder i
shared into the media folder we had created.

We then modify views.py to be as follows:

from django.shortcuts import render, redirect


import os
import folium
import geopandas as gpd
from folium import GeoJson

# Create your views here.


def home(request):
shp_dir = os.path.join(os.getcwd(), 'media', 'shp')

m = folium.Map(location=[0.0236, 37.9062], zoom_start=6)

style_Kenya_county_dd = {'fillColor': '#228B22', 'color': '#228B22'}


style_kenya_wetlands = {'color': 'blue'}
style_kenya_all_towns = {'color': 'red'}
style_kenya_highland_roads = {'color': 'yellow'}
style_kenya_forestranges = {'color': 'green'}

Kenya_county_dd = gpd.read_file(os.path.join(shp_dir, 'Kenya_county_dd.shp'

11 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

Kenya_county_dd_geojson = Kenya_county_dd.to_crs("EPSG:4326").to_json()

kenya_wetlands = gpd.read_file(os.path.join(shp_dir, 'kenya_wetlands.shp'


kenya_wetlands_geojson = kenya_wetlands.to_crs("EPSG:4326").to_json()

kenya_all_towns = gpd.read_file(os.path.join(shp_dir, 'kenya_all_towns.shp'


kenya_all_towns_geojson = kenya_all_towns.to_crs("EPSG:4326").to_json()

kenya_highland_roads = gpd.read_file(os.path.join(shp_dir, 'kenya_highland_roads.s


kenya_highland_roads_geojson = kenya_highland_roads.to_crs("EPSG:4326").to_json()

kenya_forestranges = gpd.read_file(os.path.join(shp_dir, 'kenya_forestranges.shp'


kenya_forestranges_geojson = kenya_forestranges.to_crs("EPSG:4326").to_json()

GeoJson(Kenya_county_dd_geojson, name='Kenya_counties', style_function=lambda


GeoJson(kenya_wetlands_geojson, name='kenya_wetlands', style_function=lambda

# Create a feature group for kenya_all_towns layer


kenya_all_towns_fg = folium.FeatureGroup(name='kenya_all_towns')
# Iterate over the points and add colored circles to the feature group
for _, row in kenya_all_towns.iterrows():
folium.CircleMarker(location=[row['geometry'].y, row['geometry'].x], radius=
kenya_all_towns_fg.add_to(m)

GeoJson(kenya_highland_roads_geojson, name='kenya_highland_roads', style_function=


GeoJson(kenya_forestranges_geojson, name='kenya_forestranges', style_function=

folium.LayerControl().add_to(m)

m = m._repr_html_()
context = {'my_map': m}
return render(request, 'geoApp/home.html', context)

And add the following line to your html code:

{{ my_map|safe }}

So, now the html file will be:

{% load static %}

<!DOCTYPE html>
<html lang="en">

12 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no
<meta name="description" content="">
<meta name="author" content="">

<title>GeoGida</title>

<!-- Bootstrap core CSS -->


<link rel="stylesheet" href="{% static '/bootstrap/css/bootstrap.min.css' %}"

<!-- Custom CSS -->


<style>
.navbar-brand .twitter-handle {
color: #1DA1F2; /* Twitter blue color */
margin-left: 5px;
}

.lead {
color: #FF3366; /* Custom color for lead text */
}
</style>

</head>

<body>

<!-- Navigation -->


<nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
<div class="container">
<a class="navbar-brand" href="https://twitter.com/lawrence_kim_">Geospatial Prim
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="">Welcome</a>
</li>
</ul>
</div>
</div>
</nav>

<!-- Page Content -->


<div class="container">
<div class="row">

<div class="col-lg-12 text-center">

13 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

<h1 class="mt-5">Geospatial Application</h1>


<p class="lead text-danger">You´ll be seeing shapefiles stored in the Database

{{ my_map|safe }}

<ul class="list-unstyled">
<li>Developed by Lawrence Kimutai</li>
<li>2023</li>
<li>Contact: +254759629059</li>
</ul>
</div>
</div>
</div>

<!-- Bootstrap core JavaScript -->


<script src="{% static '/jquery/jquery.slim.min.js' %}"></script>
<script src="{% static '/bootstrap/js/bootstrap.bundle.min.js' %}"></script>

</body>

</html>

On relaoding the web site “http://localhost:8000/” depending on the server you


were using, you should now see something like this with all the layers we just
added and you can toggle the layers on and off:

Geospatial Application with Python and Django framework

14 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

And there we have our Geo App with Kenya data(shapefiles) overlaid!

This can be a foundation to many other geospatial applications you may think of.
Just impliment the functionalities and how you envision it to be!

Thank you!

You can also follow the following link to try and understand where you have any
issue:

BUILDING GEOSPATIAL WEB APPLICATIONS IN PYTHON VIA DJANGO…

Youtube @geospatialprimetech997

My contacts:
Twitter: https://twitter.com/lawrence_kim_?t=IgTw9ewUp1oQoKdcEirS5Q&s=09

LinkedIn: https://www.linkedin.com/in/lawrence-kimutai-6184541ba

My Github: https://github.com/KimutaiLawrence

Fiverr: https://www.fiverr.com/s/3E14NB

15 de 23 6/06/24, 17:35
BUILDING GEOSPATIAL WEB APPLICATIONS IN P... https://medium.com/@kimutai.lawrence19/building-g...

Upwork: https://www.upwork.com/freelancers/~01e0e9da97646e56f2

People per hour: https://www.peopleperhour.com/freelancer/lawrence-kimutai-


geospatial-developer-mwjzyjx

Whatsapp Contact: +254759629059

Email: geospatialprime@gmail.com

Geodjango Django Geospatial Web Development Python

Follow

Written by LAWRENCE KIMUTAI


286 Followers

Geospatial Data Science, Python, Java, AI, ML, GIS. Email: geospatialprime@gmail.com and my Portfolio
Website: https://lawrence65.carrd.co/com +254759629059

More from LAWRENCE KIMUTAI

16 de 23 6/06/24, 17:35

You might also like