Kaydet (Commit) b16b72d4 authored tarafından Claude Paroz's avatar Claude Paroz

Fixed #5472 --Added OpenLayers-based widgets in contrib.gis

Largely inspired from django-floppyforms. Designed to not depend
on OpenLayers at code level.
üst d4d11456
......@@ -44,6 +44,7 @@ class GeometryField(Field):
# The OpenGIS Geometry name.
geom_type = 'GEOMETRY'
form_class = forms.GeometryField
# Geodetic units.
geodetic_units = ('Decimal Degree', 'degree')
......@@ -201,11 +202,14 @@ class GeometryField(Field):
return connection.ops.geo_db_type(self)
def formfield(self, **kwargs):
defaults = {'form_class' : forms.GeometryField,
defaults = {'form_class' : self.form_class,
'geom_type' : self.geom_type,
'srid' : self.srid,
}
defaults.update(kwargs)
if (self.dim > 2 and not 'widget' in kwargs and
not getattr(defaults['form_class'].widget, 'supports_3d', False)):
defaults['widget'] = forms.Textarea
return super(GeometryField, self).formfield(**defaults)
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
......@@ -267,28 +271,35 @@ class GeometryField(Field):
# The OpenGIS Geometry Type Fields
class PointField(GeometryField):
geom_type = 'POINT'
form_class = forms.PointField
description = _("Point")
class LineStringField(GeometryField):
geom_type = 'LINESTRING'
form_class = forms.LineStringField
description = _("Line string")
class PolygonField(GeometryField):
geom_type = 'POLYGON'
form_class = forms.PolygonField
description = _("Polygon")
class MultiPointField(GeometryField):
geom_type = 'MULTIPOINT'
form_class = forms.MultiPointField
description = _("Multi-point")
class MultiLineStringField(GeometryField):
geom_type = 'MULTILINESTRING'
form_class = forms.MultiLineStringField
description = _("Multi-line string")
class MultiPolygonField(GeometryField):
geom_type = 'MULTIPOLYGON'
form_class = forms.MultiPolygonField
description = _("Multi polygon")
class GeometryCollectionField(GeometryField):
geom_type = 'GEOMETRYCOLLECTION'
form_class = forms.GeometryCollectionField
description = _("Geometry collection")
from django.forms import *
from django.contrib.gis.forms.fields import GeometryField
from .fields import (GeometryField, GeometryCollectionField, PointField,
MultiPointField, LineStringField, MultiLineStringField, PolygonField,
MultiPolygonField)
from .widgets import BaseGeometryWidget, OpenLayersWidget, OSMWidget
......@@ -9,6 +9,7 @@ from django.utils.translation import ugettext_lazy as _
# While this couples the geographic forms to the GEOS library,
# it decouples from database (by not importing SpatialBackend).
from django.contrib.gis.geos import GEOSException, GEOSGeometry, fromstr
from .widgets import OpenLayersWidget
class GeometryField(forms.Field):
......@@ -17,7 +18,8 @@ class GeometryField(forms.Field):
accepted by GEOSGeometry is accepted by this form. By default,
this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.
"""
widget = forms.Textarea
widget = OpenLayersWidget
geom_type = 'GEOMETRY'
default_error_messages = {
'required' : _('No geometry value provided.'),
......@@ -31,12 +33,13 @@ class GeometryField(forms.Field):
# Pop out attributes from the database field, or use sensible
# defaults (e.g., allow None).
self.srid = kwargs.pop('srid', None)
self.geom_type = kwargs.pop('geom_type', 'GEOMETRY')
self.geom_type = kwargs.pop('geom_type', self.geom_type)
if 'null' in kwargs:
kwargs.pop('null', True)
warnings.warn("Passing 'null' keyword argument to GeometryField is deprecated.",
DeprecationWarning, stacklevel=2)
super(GeometryField, self).__init__(**kwargs)
self.widget.attrs['geom_type'] = self.geom_type
def to_python(self, value):
"""
......@@ -98,3 +101,31 @@ class GeometryField(forms.Field):
else:
# Check for change of state of existence
return bool(initial) != bool(data)
class GeometryCollectionField(GeometryField):
geom_type = 'GEOMETRYCOLLECTION'
class PointField(GeometryField):
geom_type = 'POINT'
class MultiPointField(GeometryField):
geom_type = 'MULTIPOINT'
class LineStringField(GeometryField):
geom_type = 'LINESTRING'
class MultiLineStringField(GeometryField):
geom_type = 'MULTILINESTRING'
class PolygonField(GeometryField):
geom_type = 'POLYGON'
class MultiPolygonField(GeometryField):
geom_type = 'MULTIPOLYGON'
from __future__ import unicode_literals
import logging
from django.conf import settings
from django.contrib.gis import gdal
from django.contrib.gis.geos import GEOSGeometry, GEOSException
from django.forms.widgets import Widget
from django.template import loader
from django.utils import six
from django.utils import translation
logger = logging.getLogger('django.contrib.gis')
class BaseGeometryWidget(Widget):
"""
The base class for rich geometry widgets.
Renders a map using the WKT of the geometry.
"""
geom_type = 'GEOMETRY'
map_srid = 4326
map_width = 600
map_height = 400
display_wkt = False
supports_3d = False
template_name = '' # set on subclasses
def __init__(self, attrs=None):
self.attrs = {}
for key in ('geom_type', 'map_srid', 'map_width', 'map_height', 'display_wkt'):
self.attrs[key] = getattr(self, key)
if attrs:
self.attrs.update(attrs)
def render(self, name, value, attrs=None):
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
if isinstance(value, six.string_types):
try:
value = GEOSGeometry(value)
except (GEOSException, ValueError) as err:
logger.error(
"Error creating geometry from value '%s' (%s)" % (
value, err)
)
value = None
wkt = ''
if value:
# Check that srid of value and map match
if value.srid != self.map_srid:
try:
ogr = value.ogr
ogr.transform(self.map_srid)
wkt = ogr.wkt
except gdal.OGRException as err:
logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)" % (
value.srid, self.map_srid, err)
)
else:
wkt = value.wkt
context = self.build_attrs(attrs,
name=name,
module='geodjango_%s' % name.replace('-','_'), # JS-safe
wkt=wkt,
geom_type=gdal.OGRGeomType(self.attrs['geom_type']),
STATIC_URL=settings.STATIC_URL,
LANGUAGE_BIDI=translation.get_language_bidi(),
)
return loader.render_to_string(self.template_name, context)
class OpenLayersWidget(BaseGeometryWidget):
template_name = 'gis/openlayers.html'
class Media:
js = (
'http://openlayers.org/api/2.11/OpenLayers.js',
'gis/js/OLMapWidget.js',
)
class OSMWidget(BaseGeometryWidget):
"""
An OpenLayers/OpenStreetMap-based widget.
"""
template_name = 'gis/openlayers-osm.html'
default_lon = 5
default_lat = 47
class Media:
js = (
'http://openlayers.org/api/2.11/OpenLayers.js',
'http://www.openstreetmap.org/openlayers/OpenStreetMap.js',
'gis/js/OLMapWidget.js',
)
@property
def map_srid(self):
# Use the official spherical mercator projection SRID on versions
# of GDAL that support it; otherwise, fallback to 900913.
if gdal.HAS_GDAL and gdal.GDAL_VERSION >= (1, 7):
return 3857
else:
return 900913
def render(self, name, value, attrs=None):
return super(self, OSMWidget).render(name, value,
{'default_lon': self.default_lon, 'default_lat': self.default_lat})
This diff is collapsed.
{% extends "gis/openlayers.html" %}
{% load l10n %}
{% block map_options %}var map_options = {
maxExtend: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
maxResolution: 156543.0339,
numZoomLevels: 20,
units: 'm'
};{% endblock %}
{% block options %}{{ block.super }}
options['scale_text'] = true;
options['mouse_position'] = true;
options['default_lon'] = {{ default_lon|unlocalize }};
options['default_lat'] = {{ default_lat|unlocalize }};
options['base_layer'] = new OpenLayers.Layer.OSM.Mapnik("OpenStreetMap (Mapnik)");
{% endblock %}
<style type="text/css">{% block map_css %}
#{{ id }}_map { width: {{ map_width }}px; height: {{ map_height }}px; }
#{{ id }}_map .aligned label { float: inherit; }
#{{ id }}_div_map { position: relative; vertical-align: top; float: {{ LANGUAGE_BIDI|yesno:"right,left" }}; }
{% if not display_wkt %}#{{ id }} { display: none; }{% endif %}
.olControlEditingToolbar .olControlModifyFeatureItemActive {
background-image: url("{{ STATIC_URL }}admin/img/gis/move_vertex_on.png");
background-repeat: no-repeat;
}
.olControlEditingToolbar .olControlModifyFeatureItemInactive {
background-image: url("{{ STATIC_URL }}admin/img/gis/move_vertex_off.png");
background-repeat: no-repeat;
}{% endblock %}
</style>
<div id="{{ id }}_div_map">
<div id="{{ id }}_map"></div>
<span class="clear_features"><a href="javascript:{{ module }}.clearFeatures()">Delete all Features</a></span>
{% if display_wkt %}<p> WKT debugging window:</p>{% endif %}
<textarea id="{{ id }}" class="vWKTField required" cols="150" rows="10" name="{{ name }}">{{ wkt }}</textarea>
<script type="text/javascript">
{% block map_options %}var map_options = {};{% endblock %}
{% block options %}var options = {
geom_name: '{{ geom_type }}',
id: '{{ id }}',
map_id: '{{ id }}_map',
map_options: map_options,
map_srid: {{ map_srid }},
name: '{{ name }}'
};
{% endblock %}
var {{ module }} = new MapWidget(options);
</script>
</div>
.. _ref-gis-forms-api:
===================
GeoDjango Forms API
===================
.. module:: django.contrib.gis.forms
:synopsis: GeoDjango forms API.
.. versionadded:: 1.6
GeoDjango provides some specialized form fields and widgets in order to visually
display and edit geolocalized data on a map. By default, they use
`OpenLayers`_-powered maps, with a base WMS layer provided by `Metacarta`_.
.. _OpenLayers: http://openlayers.org/
.. _Metacarta: http://metacarta.com/
Field arguments
===============
In addition to the regular :ref:`form field arguments <core-field-arguments>`,
GeoDjango form fields take the following optional arguments.
``srid``
~~~~~~~~
.. attribute:: Field.srid
This is the SRID code that the field value should be transformed to. For
example, if the map widget SRID is different from the SRID more generally
used by your application or database, the field will automatically convert
input values into that SRID.
``geom_type``
~~~~~~~~~~~~~
.. attribute:: Field.geom_type
You generally shouldn't have to set or change that attribute which should
be setup depending on the field class. It matches the OpenGIS standard
geometry name.
Form field classes
==================
``GeometryField``
~~~~~~~~~~~~~~~~~
.. class:: GeometryField
``PointField``
~~~~~~~~~~~~~~
.. class:: PointField
``LineStringField``
~~~~~~~~~~~~~~~~~~~
.. class:: LineStringField
``PolygonField``
~~~~~~~~~~~~~~~~
.. class:: PolygonField
``MultiPointField``
~~~~~~~~~~~~~~~~~~~
.. class:: MultiPointField
``MultiLineStringField``
~~~~~~~~~~~~~~~~~~~~~~~~
.. class:: MultiLineStringField
``MultiPolygonField``
~~~~~~~~~~~~~~~~~~~~~
.. class:: MultiPolygonField
``GeometryCollectionField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. class:: GeometryCollectionField
Form widgets
============
.. module:: django.contrib.gis.widgets
:synopsis: GeoDjango widgets API.
GeoDjango form widgets allow you to display and edit geographic data on a
visual map.
Note that none of the currently available widgets supports 3D geometries, hence
geometry fields will fallback using a simple ``Textarea`` widget for such data.
Widget attributes
~~~~~~~~~~~~~~~~~
GeoDjango widgets are template-based, so their attributes are mostly different
from other Django widget attributes.
.. attribute:: BaseGeometryWidget.geom_type
The OpenGIS geometry type, generally set by the form field.
.. attribute:: BaseGeometryWidget.map_height
.. attribute:: BaseGeometryWidget.map_width
Height and width of the widget map (default is 400x600).
.. attribute:: BaseGeometryWidget.map_srid
SRID code used by the map (default is 4326).
.. attribute:: BaseGeometryWidget.display_wkt
Boolean value specifying if a textarea input showing the WKT representation
of the current geometry is visible, mainly for debugging purposes (default
is ``False``).
.. attribute:: BaseGeometryWidget.supports_3d
Indicates if the widget supports edition of 3D data (default is ``False``).
.. attribute:: BaseGeometryWidget.template_name
The template used to render the map widget.
You can pass widget attributes in the same manner that for any other Django
widget. For example::
from django.contrib.gis import forms
class MyGeoForm(forms.Form):
point = forms.PointField(widget=
forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}))
Widget classes
~~~~~~~~~~~~~~
``BaseGeometryWidget``
.. class:: BaseGeometryWidget
This is an abstract base widget containing the logic needed by subclasses.
You cannot directly use this widget for a geometry field.
Note that the rendering of GeoDjango widgets is based on a template,
identified by the :attr:`template_name` class attribute.
``OpenLayersWidget``
.. class:: OpenLayersWidget
This is the default widget used by all GeoDjango form fields.
``template_name`` is ``gis/openlayers.html``.
``OSMWidget``
.. class:: OSMWidget
This widget uses an OpenStreetMap base layer (Mapnik) to display geographic
objects on.
``template_name`` is ``gis/openlayers-osm.html``.
......@@ -18,6 +18,7 @@ of spatially enabled data.
install/index
model-api
db-api
forms-api
geoquerysets
measure
geos
......
......@@ -30,6 +30,8 @@ exception or returns the clean value::
...
ValidationError: [u'Enter a valid email address.']
.. _core-field-arguments:
Core field arguments
--------------------
......
......@@ -114,6 +114,13 @@ Django 1.6 adds support for savepoints in SQLite, with some :ref:`limitations
A new :class:`django.db.models.BinaryField` model field allows to store raw
binary data in the database.
GeoDjango form widgets
~~~~~~~~~~~~~~~~~~~~~~
GeoDjango now provides :ref:`form fields and widgets <ref-gis-forms-api>` for
its geo-specialized fields. They are OpenLayers-based by default, but they can
be customized to use any other JS framework.
Minor features
~~~~~~~~~~~~~~
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment