Displaying objects on maps in the Django views and administration site.

Overview

DjangoAdminGeomap library

GitHub Workflow Status GitHub Workflow Status Codacy Badge Codacy Badge

The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django views and admin site.

objects on the map in the Django admin site

There is a full-fledged multifunctional GIS framework GeoDjango. When is used in the Django admin site, you can display objects on the map. However, GeoDjango has a large list of dependencies on various libraries and the specifics of installing these libraries on various platforms.

If you only need to display objects on the map in the Django admin site, then you can use the DjangoAdminGeomap library. It has no additional requirements for the names and data types of fields in the database tables, and there are no installation dependencies.

DjangoAdminGeomap uses the OpenLayers JavaScript framework to display map data. The source of the cartographic data is the data of the OpenStreetMap project.

Installation

pip install django-admin-geomap

After installation, you need to plug the library into your Django project by making changes to the settings.py file.

Changes to settings.py

To connect DjangoAdminGeomap to your project, you need to add to the file settings.py in the key TEMPLATES the path to the directory templates of the library.

TEMPLATES = [
  {
    'DIRS': ['path/to/installed/django_admin_geomap/templates'],
  },
]

An example of such a connection can be found in the file example/settings.py.

It is not necessary to include the library in the INSTALLED_APPS list in settings.py.

Initial data

Let's say we have a table in the database, the records of which contain data about coordinates.

# models.py
from django.db import models

class Location(models.Model):
    name = models.CharField(max_length=100)
    lon = models.FloatField()  # longitude
    lat = models.FloatField()  # latitude

On the main page of the site and when working with this table in the admin panel, we want to see a map with objects from this table located on it.

Main page with a list of objects on the map

To enable the display of Location objects on the map, you need to make changes to the model class in the models.py file.

Add the django_admin_geomap.GeoItem "mixin" class to the inheritance list of the Location class and define two properties: geomap_longitude and geomap_latitude. These properties should return the longitude and latitude of the object as a string.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_longitude(self):
        return '' if self.lon is None else str(self.lon)

    @property
    def geomap_latitude(self):
        return '' if self.lon is None else str(self.lat)

After making these changes to the definition of the model, you can display a map with objects from the Location table in an arbitrary view. To do this, you need to include the file geomap/common.html in the page template. For example, the site root page template home.html might look like this:

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

<head>
<title>DjangoAdminGeomap example</title>
</head>

<body>
Hello, OpenStreetMap!
<div>{% include "geomap/common.html" %}</div>
</body>

</html>

In the view function, you need to pass to this template the context formed by calling the geomap_context function. As a required argument to the function, you need to pass an iterable sequence of objects to display on the map. For example a list or Django QuerySet.

# views.py
from django.shortcuts import render
from django_admin_geomap import geomap_context

from .models import Location


def home(request):
    return render(request, 'home.html', geomap_context(Location.objects.all()))

On the root page of the site, a map with markers in the locations of these objects will be displayed.

The geomap_context function accepts additional named arguments to customize the properties of the map.

  • map_longitude: map center longitude, default is "0.0"
  • map_latitude: map center latitude, default is "0.0"
  • map_zoom: map zoom level, default is "1"
  • map_height: vertical map size, default is "500px"

List of objects on the map in the admin panel

To display a map with objects in the site admin panel in the admin settings file admin.py, when registering a model, you need to use the django_admin_geomap.ModelAdmin class.

# admin.py
from django.contrib import admin
from django_admin_geomap import ModelAdmin
from .models import Location

admin.site.register(Location, ModelAdmin)

After making these changes, in the admin panel on the page with a list of Location objects, a map with markers at the locations of these objects will be displayed under the table.

Displaying the object on the map in the edit form in the admin panel

To display an object on the map in the edit/view form, you must additionally specify the field IDs in the Django form, which contain the longitude and latitude values of the object.

For our Location class, the Django admin automatically assigns the IDs id_lon and id_lat to these form fields. The following changes need to be made to the admin.py file.

# admin.py
from django.contrib import admin
from django_admin_geomap import ModelAdmin
from .models import Location

class Admin(ModelAdmin):
    geomap_field_longitude = "id_lon"
    geomap_field_latitude = "id_lat"

admin.site.register(Location, Admin)

After making these changes, in the admin panel on the page for viewing/editing the Location object, a map with a marker at the location of the object will be displayed.

When editing, you can change the position of an object by dragging its icon across the map with the mouse (you need to move the mouse cursor over the bottom of the icon until a blue dot appears on it).

When adding a new object, its position can be set by clicking on the map. Further, the marker of the new object can be dragged, similar to editing.

Additional customization

The library allows you to customize the view of the map and objects by setting special properties for the model class and the django_admin_geomap.ModelAdmin class.

Object icon on the map

The geomap_icon property of the model class sets the path to the marker icon. You can use different icons depending on the state of a particular object.

The default is https://maps.google.com/mapfiles/ms/micons/red.png.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_icon(self):
        return self.default_icon

Text in a pop-up panel when you click on a marker on the map

When you click on a marker on the map, a pop-up panel is displayed. The HTML code used in this panel can be set by defining three properties on the model class.

  • geomap_popup_common displayed in regular views
  • geomap_popup_view displayed in the admin panel for a user without permission to edit the object
  • geomap_popup_edit displayed in the admin panel for a user who has permission to edit

By default, all these properties return the string representation of the object.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_popup_view(self):
        return "<strong>{}</strong>".format(str(self))

    @property
    def geomap_popup_edit(self):
        return self.geomap_popup_view

    @property
    def geomap_popup_common(self):
        return self.geomap_popup_view

New object icon

The geomap_new_feature_icon property of the django_admin_geomap.ModelAdmin class sets the path to the marker icon when adding a new object in the admin panel.

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_new_feature_icon = "/myicon.png"

Default map zoom level and center of the map when displaying a list of objects in the admin panel

You can change the zoom level and position of the center of the map by setting the properties geomap_default_longitude, geomap_default_latitude and geomap_default_zoom in the class django_admin_geomap.ModelAdmin.

By default, the center of the map is located at the point with coordinates "0.0", "0.0" and the scale is "1".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_default_longitude = "95.1849"
    geomap_default_latitude = "64.2637"
    geomap_default_zoom = "3"

Default map zoom level when editing/viewing an object in the admin panel

In object edit form the center of the map coincides with the location of the object. The zoom level of the map can be set by using the geomap_item_zoom property of the django_admin_geomap.ModelAdmin class.

The default is "13".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_item_zoom = "10"

Vertical map size in the admin panel

When displayed, the map occupies the maximum possible horizontal size. The vertical size can be set via the geomap_height property of the django_admin_geomap.ModelAdmin class. The value must be a string valid in the CSS style definition.

The default is "500px".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_height = "300px"
You might also like...
Store model history and view/revert changes from admin site.

django-simple-history django-simple-history stores Django model state on every create/update/delete. This app supports the following combinations of D

Store model history and view/revert changes from admin site.

django-simple-history django-simple-history stores Django model state on every create/update/delete. This app supports the following combinations of D

Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.

Django Activity Stream What is Django Activity Stream? Django Activity Stream is a way of creating activities generated by the actions on your site. I

Helps working with singletons - things like global settings that you want to edit from the admin site.
Helps working with singletons - things like global settings that you want to edit from the admin site.

Django Solo +---------------------------+ | | | | | \ | Django Solo helps

Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App 💛 We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django 🚀 Inspiration might be taken from @hotwired/hotwire-rails. We are sti

django-quill-editor makes Quill.js easy to use on Django Forms and admin sites
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

Comments
  • Ссылки на скрипты на работают

    Ссылки на скрипты на работают

    Подключил по инструкции, джанго никаких ошибок не выдает. В консоли браузера есть ошибки GEThttps://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/build/ol.js [HTTP/2 403 Forbidden 3289ms] GEThttps://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/css/ol.css [HTTP/2 403 Forbidden 4311ms]

    Скрипты из базового шаблона походу не доступны

    opened by hackoffme 9
  • Auto-zoom of Admin Map?

    Auto-zoom of Admin Map?

    First of all, thanks for such a great tool. I've got it hooked in to WhatThreeWords on my admin panel and it's working brilliantly!

    I've seen the docs about setting the admin zoom and I'm wondering if it's possible to have it "auto-zoom" based on the coordinates of the objects that are returned to it?

    For example, if I've only got objects that have locations in central London, is it possible to have it auto-zoom to a level where all the objects are displayed on the map at a sensible level?

    opened by proffalken 3
  • Template Directory

    Template Directory

    First, thanks for an excellent package! It was (fairly) easy to install, and bam! Instance maps! I would like to point out that adding django_admin_geomap to INSTALLED_APPS removes the need edit ``TEMPLATES```. I find this easier/robust because I was not able to add a template directory that supported both dev and deployment environments.

    Thanks again!

    opened by NadavK 2
  • Pop-up on Marker Click

    Pop-up on Marker Click

    The pop-up window is not visible when clicking on a marker. This is the HTML that changes when clicking an element:

    <div class="popover fade bs-popover-top show" role="tooltip" id="popover906644" x-placement="top" x-out-of-boundaries="" style="position: absolute; transform: translate3d(2128px, 4041px, 0px); top: 0px; left: 0px; will-change: transform;">
    <div class="arrow" style="left: 0px;">
    </div><h3 class="popover-header">
    </h3><div class="popover-body">ABCDEF</div></div>
    

    The left position (2128) is too far right. When I change it manually to something smaller, then the pop-up does appears. Looks like something is wrong with the pop-up position? BTW, the top position (4041) looks to be correct.

    opened by NadavK 2
Releases(v1.3)
  • v1.3(Sep 27, 2022)

    By default, this mode is disabled. You can enable autozoom mode when displaying objects on the map both in regular views and in the Django admin panel.

    The autozoom mode works differently depending on the number of objects that you want to display on the map.

    If the list of displayed objects is empty, the autozoom mode is disabled.

    If the list contains one object, then the map center is set to the coordinates of this object, and the map scale is set to the value of the autozoom parameter (10 for the examples above).

    If the list contains more than one object, the program determines the minimum rectangle that contains all the displayed objects. The center of the map is set to the coordinates of the center of this rectangle. The scale of the map is set in such a way as to contain the given rectangle with some indents along the edges.

    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Aug 24, 2022)

Owner
Vitaly Bogomolov
Vitaly Bogomolov
Super simple bar charts for django admin list views visualizing the number of objects based on date_hierarchy using Chart.js.

Super simple bar charts for django admin list views visualizing the number of objects based on date_hierarchy using Chart.js.

foorilla LLC 4 May 18, 2022
Get inside your stronghold and make all your Django views default login_required

Stronghold Get inside your stronghold and make all your Django views default login_required Stronghold is a very small and easy to use django app that

Mike Grouchy 384 Nov 23, 2022
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 4, 2023
Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

django-location-field Let users pick locations using a map widget and store its latitude and longitude. Stable version: django-location-field==2.1.0 D

Caio Ariede 481 Dec 29, 2022
This is a Django app that uses numerous Google APIs such as reCAPTURE, maps and waypoints

Django project that uses Googles APIs to auto populate fields, display maps and routes for multiple waypoints

Bobby Stearman 57 Dec 3, 2022
Simple yet powerful and really extendable application for managing a blog within your Django Web site.

Django Blog Zinnia Simple yet powerful and really extendable application for managing a blog within your Django Web site. Zinnia has been made for pub

Julien Fache 2.1k Dec 24, 2022
Utilities to make function-based views cleaner, more efficient, and better tasting.

django-fbv Utilities to make Django function-based views cleaner, more efficient, and better tasting. ?? ?? Complete documentation: https://django-fbv

Adam Hill 49 Dec 30, 2022
A Django app that allows visitors to interact with your site as a guest user without requiring registration.

django-guest-user A Django app that allows visitors to interact with your site as a guest user without requiring registration. Largely inspired by dja

Julian Wachholz 21 Dec 17, 2022
Coltrane - A simple content site framework that harnesses the power of Django without the hassle.

coltrane A simple content site framework that harnesses the power of Django without the hassle. Features Can be a standalone static site or added to I

Adam Hill 58 Jan 2, 2023
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021