├── .DS_Store ├── .gitignore ├── README.md ├── db.sqlite3 ├── distance_proj ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── settings.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── wsgi.cpython-38.pyc ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── measurements ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── forms.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ ├── utils.cpython-38.pyc │ └── views.cpython-38.pyc ├── admin.py ├── apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc ├── models.py ├── templates │ └── measurements │ │ └── main.html ├── tests.py ├── urls.py ├── utils.py └── views.py └── templates └── base.html /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | // geoIP with GeoLite2-City and GeoLite2-Country 2 | geoip/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django with GeoLocation 2 | GeoLocation and Folium Project with Django. 3 | 4 | Calculate and visualize the distance between the current location and the destination. 5 | 6 | ![alt text](http://blog.pyplane.com/static/assets/img/my_pics/geodjango.png) -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/db.sqlite3 -------------------------------------------------------------------------------- /distance_proj/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/distance_proj/__init__.py -------------------------------------------------------------------------------- /distance_proj/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/distance_proj/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /distance_proj/__pycache__/settings.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/distance_proj/__pycache__/settings.cpython-38.pyc -------------------------------------------------------------------------------- /distance_proj/__pycache__/urls.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/distance_proj/__pycache__/urls.cpython-38.pyc -------------------------------------------------------------------------------- /distance_proj/__pycache__/wsgi.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/distance_proj/__pycache__/wsgi.cpython-38.pyc -------------------------------------------------------------------------------- /distance_proj/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for distance_proj project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'distance_proj.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /distance_proj/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for distance_proj project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'n5et_btx&=x+fh3io3m)2^)npi^2@ih&_bmt&#p!d@66fm9a4o' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'measurements', 42 | 43 | 'crispy_forms' 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | ] 55 | 56 | ROOT_URLCONF = 'distance_proj.urls' 57 | 58 | TEMPLATES = [ 59 | { 60 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 61 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'distance_proj.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | CRISPY_TEMPLATE_PACK = 'bootstrap4' 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'en-us' 112 | 113 | TIME_ZONE = 'UTC' 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | GEOIP_PATH = os.path.join(BASE_DIR, 'geoip') 122 | 123 | # Static files (CSS, JavaScript, Images) 124 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 125 | 126 | STATIC_URL = '/static/' 127 | -------------------------------------------------------------------------------- /distance_proj/urls.py: -------------------------------------------------------------------------------- 1 | """distance_proj URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('', include('measurements.urls', namespace='measurements')), 22 | ] 23 | -------------------------------------------------------------------------------- /distance_proj/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for distance_proj project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'distance_proj.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'distance_proj.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /measurements/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'measurements.apps.MeasurementsConfig' -------------------------------------------------------------------------------- /measurements/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/admin.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/admin.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/apps.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/apps.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/forms.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/forms.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/models.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/models.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/urls.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/urls.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/utils.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/__pycache__/views.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/__pycache__/views.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Measurement 3 | # Register your models here. 4 | 5 | admin.site.register(Measurement) 6 | -------------------------------------------------------------------------------- /measurements/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MeasurementsConfig(AppConfig): 5 | name = 'measurements' 6 | verbose_name = 'Measurement between 2 locations' 7 | -------------------------------------------------------------------------------- /measurements/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from .models import Measurement 3 | 4 | class MeasurementModelForm(forms.ModelForm): 5 | class Meta: 6 | model = Measurement 7 | fields = ('destination',) -------------------------------------------------------------------------------- /measurements/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.7 on 2020-06-05 11:33 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Measurement', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('location', models.CharField(max_length=200)), 19 | ('destination', models.CharField(max_length=200)), 20 | ('distance', models.DecimalField(decimal_places=2, max_digits=10)), 21 | ('created', models.DateTimeField(auto_now_add=True)), 22 | ], 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /measurements/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/migrations/__init__.py -------------------------------------------------------------------------------- /measurements/migrations/__pycache__/0001_initial.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/migrations/__pycache__/0001_initial.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/migrations/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pyplane/Django-with-Geolocation/a30cd408a993812a6e18bf78f09a4905e8f75e01/measurements/migrations/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /measurements/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | 5 | class Measurement(models.Model): 6 | location = models.CharField(max_length=200) 7 | destination = models.CharField(max_length=200) 8 | distance = models.DecimalField(max_digits=10, decimal_places=2) 9 | created = models.DateTimeField(auto_now_add=True) 10 | 11 | def __str__(self): 12 | return f"Distance from {self.location} to {self.destination} is {self.distance} km" 13 | -------------------------------------------------------------------------------- /measurements/templates/measurements/main.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% load crispy_forms_tags %} 3 | 4 | {% block title %} 5 | calculate distance 6 | {% endblock title %} 7 | 8 | {% block content %} 9 | 10 | 11 | 26 | 27 | {{ map|safe }} 28 | 29 |
30 | {% csrf_token %} 31 | {{form|crispy}} 32 | 33 |
34 |
35 | This product includes GeoLite2 data created by MaxMind, available from 36 | https://www.maxmind.com. 37 | 38 | {% if request.POST and distance is not None %} 39 | 44 | {% endif %} 45 | 46 | {% endblock content %} -------------------------------------------------------------------------------- /measurements/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /measurements/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import calculate_distance_view 3 | 4 | app_name = 'measurements' 5 | 6 | urlpatterns = [ 7 | path('', calculate_distance_view, name='calaculate-view'), 8 | ] 9 | -------------------------------------------------------------------------------- /measurements/utils.py: -------------------------------------------------------------------------------- 1 | from django.contrib.gis.geoip2 import GeoIP2 2 | 3 | # Helper functions 4 | 5 | def get_ip_address(request): 6 | x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') 7 | if x_forwarded_for: 8 | ip = x_forwarded_for.split(',')[0] 9 | else: 10 | ip = request.META.get('REMOTE_ADDR') 11 | return ip 12 | 13 | def get_geo(ip): 14 | g = GeoIP2() 15 | country = g.country(ip) 16 | city = g.city(ip) 17 | lat, lon = g.lat_lon(ip) 18 | return country, city, lat, lon 19 | 20 | def get_center_coordinates(latA, longA, latB=None, longB=None): 21 | cord = (latA, longA) 22 | if latB: 23 | cord = [(latA+latB)/2, (longA+longB)/2] 24 | return cord 25 | 26 | def get_zoom(distance): 27 | if distance <=100: 28 | return 8 29 | elif distance > 100 and distance <= 5000: 30 | return 4 31 | else: 32 | return 2 -------------------------------------------------------------------------------- /measurements/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, get_object_or_404 2 | from .models import Measurement 3 | from .forms import MeasurementModelForm 4 | from geopy.geocoders import Nominatim 5 | from geopy.distance import geodesic 6 | from .utils import get_geo, get_center_coordinates, get_zoom 7 | import folium 8 | # Create your views here. 9 | 10 | def calculate_distance_view(request): 11 | # initial values 12 | distance = None 13 | destination = None 14 | 15 | obj = get_object_or_404(Measurement, id=1) 16 | form = MeasurementModelForm(request.POST or None) 17 | geolocator = Nominatim(user_agent='measurements') 18 | 19 | ip = '72.14.207.99' 20 | country, city, lat, lon = get_geo(ip) 21 | location = geolocator.geocode(city) 22 | 23 | # location coordinates 24 | l_lat = lat 25 | l_lon = lon 26 | pointA = (l_lat, l_lon) 27 | 28 | # initial folium map 29 | m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon), zoom_start=8) 30 | # location marker 31 | folium.Marker([l_lat, l_lon], tooltip='click here for more', popup=city['city'], 32 | icon=folium.Icon(color='purple')).add_to(m) 33 | 34 | if form.is_valid(): 35 | instance = form.save(commit=False) 36 | destination_ = form.cleaned_data.get('destination') 37 | destination = geolocator.geocode(destination_) 38 | 39 | # destination coordinates 40 | d_lat = destination.latitude 41 | d_lon = destination.longitude 42 | pointB = (d_lat, d_lon) 43 | # distance calculation 44 | distance = round(geodesic(pointA, pointB).km, 2) 45 | 46 | # folium map modification 47 | m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance)) 48 | # location marker 49 | folium.Marker([l_lat, l_lon], tooltip='click here for more', popup=city['city'], 50 | icon=folium.Icon(color='purple')).add_to(m) 51 | # destination marker 52 | folium.Marker([d_lat, d_lon], tooltip='click here for more', popup=destination, 53 | icon=folium.Icon(color='red', icon='cloud')).add_to(m) 54 | 55 | 56 | # draw the line between location and destination 57 | line = folium.PolyLine(locations=[pointA, pointB], weight=5, color='blue') 58 | m.add_child(line) 59 | 60 | instance.location = location 61 | instance.distance = distance 62 | instance.save() 63 | 64 | m = m._repr_html_() 65 | 66 | context = { 67 | 'distance' : distance, 68 | 'destination': destination, 69 | 'form': form, 70 | 'map': m, 71 | } 72 | 73 | return render(request, 'measurements/main.html', context) -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Geo django | {% block title %}{% endblock title %} 14 | 15 | 16 |
17 | {% block content %} 18 | {% endblock content %} 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | --------------------------------------------------------------------------------