#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008 Étienne Loks # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # See the file COPYING for details. """ Extra widgets and fields """ from django import forms from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from chimere import settings from django.contrib.gis.db import models URL_OSM_JS = ["http://www.openlayers.org/api/OpenLayers.js", "http://www.openstreetmap.org/openlayers/OpenStreetMap.js"] def getMapJS(): '''Variable initialization for drawing the map ''' # projection, center and bounds definitions js = u"var epsg_display_projection = new OpenLayers.Projection('EPSG:%d')\ ;\n" % settings.EPSG_DISPLAY_PROJECTION js += u"var epsg_projection = new OpenLayers.Projection('EPSG:%d');\n" % \ settings.EPSG_PROJECTION js += u"var centerLonLat = new OpenLayers.LonLat(%f,\ %f).transform(epsg_display_projection, epsg_projection);\n" % \ settings.DEFAULT_CENTER js += u"var maxExtent = new OpenLayers.Bounds(%f, %f, %f, %f);\n" % \ settings.MAP_BOUNDS js += u"var media_path = '%s';\n" % settings.MEDIA_URL js = u""" """ % js return js class PointChooserWidget(forms.TextInput): """ Manage the edition of point on a map """ class Media: css = { "all": ("%sforms.css" % settings.MEDIA_URL,) } js = URL_OSM_JS + ["%sedit_map.js" % settings.MEDIA_URL] def render(self, name, value, attrs=None): ''' Render a map and latitude, longitude information field ''' val = '0' value_x, value_y = 0, 0 if value: val = str(value) if hasattr(value, 'x') and hasattr(value, 'y'): value_x, value_y = value.x, value.y elif isinstance(value, unicode) and value.startswith('POINT('): try: value_x, value_y = value.split('(')[1][:-1].split(' ') value_x, value_y = float(value_x), float(value_y) except: value = None else: value = None tpl = getMapJS() tpl += u'\n' % settings.MEDIA_URL tpl += u"""

\

""" % (_("Latitude"), value_y, _("Longitude"), value_x, name, name, val) tpl += """
""" return mark_safe(tpl) class PointField(models.PointField): ''' Set the widget for the form field ''' def formfield(self, **keys): defaults = {'widget': PointChooserWidget} keys.update(defaults) return super(PointField, self).formfield(**keys)