Change the base map of geodjango forms

Hi everyone,
I would like to change the base map of the OSMWidget to a satellite image, in order to see the farm plot and allow them to add the field boundary.

I would like to see something like this

Someone know how to do so?

This is my forms.py

from django import forms
from django.contrib.gis import forms as geoforms
from .models import MultiPolygon

class MultiPolygonForm(forms.ModelForm):
    geom = geoforms.PolygonField(widget=geoforms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}))
    
    class Meta:
        model = MultiPolygon
        fields = ('name', "rotation", "crop", "geom")

Thanks

I never worked with gis, but a quick search on google led me to this article, hope it works.

1 Like

Thanks to report the article, but i would like to change directly the widget attributes of OSMWidget if it is possible to get as i said before a satellite image.

Hmm, that’s tricky. You’re going to need a few “here-and-there” knowledge to pull this off.
My shot on this is:

  • Create a custom template that inherits from gis/openlayers.html source code.
  • Redefine the block base_layer on your child template, and looking on the internet, you can set the layer to this reference, this will probably set the map to the satellite layer.
  • Create a widget that inherits from django.contrib.gis.forms.widgets.OpenLayersWidget source code and set the template_name to your custom template.
  • Use the widget you just created on the form.

Django provides NASA worldwide view in its default openlayer, So to get satellite view we need to change some things
Create a template to extend gis/openlayer.html and edit the base layer child template with
satellite map that is Esri’s (ArcGIS) World Imagery like so;
your_custom_template.html:

{% extends “gis/openlayers.html” %}
{% load i18n l10n %}
{% block base_layer %}
var base_layer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: ‘https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}’,
maxZoom: 19
})
});
{% endblock %}

Now import OpenLayersWidget in your forms.py ad use it:

from django.contrib.gis.forms.widgets import OSMWidget
class FarmLocationForm(forms.ModelForm):This text will be hidden
class meta:
model = your_model
fields = “yourformfields”
farm_loc_widget = OSMWidget(attrs={“display_raw”: False})
farm_loc_widget.template_name = “your_custom_template.html”
widgets = {
‘farm_loc’: farm_loc_widget,
}

and for admin site you can use GISModelAdmin along with your model when you register it.