Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default zoom level of a map in Geodjango's admin?

I've been looking into GeoDjango recently, I'm struggling to customize the default zoom level of the openstreet map displaying in my admin section. Below is what I have tried but with no effect, please assist.

from django.contrib.gis import admin

class LocationAdmin(admin.OSMGeoAdmin):
    default_zoom = 5

admin_site.register(ReferenceSpaceLocation, LocationAdmin)
  • My model

    class ReferenceSpaceLocation(models.Model):
    
        geometry = models.GeometryField()
    

enter image description here

like image 746
christian nyembo Avatar asked May 05 '20 10:05

christian nyembo


1 Answers

Your specific case

The default value for point_zoom with OSMGeoAdmin is 14 which is what your's seems to be at the moment. Try overwriting point_zoom in LocationAdmin. As is explained below, this should work if you are using PointField or MultiPointField.

How the zoom level will be determined:

The default zoom level will depend upon a few different things:

  • If there is no data to display (e.g. you're looking at a new instance), the default_zoom will be used. This can be set as follows:
class LocationAdmin(admin.OSMGeoAdmin):
    default_zoom = 5
  • If we are using the fields PointField or MultiPointField then then it looks like the point_zoom value will be used instead of the default_zoom. This can be set as follows:
class LocationAdmin(admin.OSMGeoAdmin):
    point_zoom = 10
  • Otherwise, the zoom level will be set automatically based on the bounds of the data.

Why is this the case?

If you look in the source code, you'll see the following in the js file that run's that admin view:

// django/contrib/gis/templates/gis/admin/openlayers.js

    var wkt = document.getElementById('{{ id }}').value;
    if (wkt){
        ...

        // Zooming to the bounds.
        {{ module }}.map.zoomToExtent(admin_geom.geometry.getBounds());
        if ({{ module }}.is_point){
            {{ module }}.map.zoomTo({{ point_zoom }});
        }
    } else {
        {% localize off %}
        {{ module }}.map.setCenter(new OpenLayers.LonLat({{ default_lon }}, {{ default_lat }}), {{ default_zoom }});
        {% endlocalize %}
    }

This means that:

  • if we are dealing with no data, then we are in the else clause of the above code. Right at the end of the line, it can be seen default_zoom is used.
  • If we are using the fields PointField or MultiPointField then {{module}}.is_point is true, and as can be seen point_zoom is used.
  • If neither of the above is the case, we can see the following is executed: zoomToExtent(admin_geom.geometry.getBounds()).
like image 116
tim-mccurrach Avatar answered Oct 08 '22 19:10

tim-mccurrach