You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.apps import apps
  2. from django.contrib.gis.db.models.fields import GeometryField
  3. from django.contrib.gis.db.models.functions import AsKML, Transform
  4. from django.contrib.gis.shortcuts import render_to_kml, render_to_kmz
  5. from django.core.exceptions import FieldDoesNotExist
  6. from django.db import DEFAULT_DB_ALIAS, connections
  7. from django.http import Http404
  8. def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):
  9. """
  10. This view generates KML for the given app label, model, and field name.
  11. The field name must be that of a geographic field.
  12. """
  13. placemarks = []
  14. try:
  15. klass = apps.get_model(label, model)
  16. except LookupError:
  17. raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model))
  18. if field_name:
  19. try:
  20. field = klass._meta.get_field(field_name)
  21. if not isinstance(field, GeometryField):
  22. raise FieldDoesNotExist
  23. except FieldDoesNotExist:
  24. raise Http404('Invalid geometry field.')
  25. connection = connections[using]
  26. if connection.features.has_AsKML_function:
  27. # Database will take care of transformation.
  28. placemarks = klass._default_manager.using(using).annotate(kml=AsKML(field_name))
  29. else:
  30. # If the database offers no KML method, we use the `kml`
  31. # attribute of the lazy geometry instead.
  32. placemarks = []
  33. if connection.features.has_Transform_function:
  34. qs = klass._default_manager.using(using).annotate(
  35. **{'%s_4326' % field_name: Transform(field_name, 4326)})
  36. field_name += '_4326'
  37. else:
  38. qs = klass._default_manager.using(using).all()
  39. for mod in qs:
  40. mod.kml = getattr(mod, field_name).kml
  41. placemarks.append(mod)
  42. # Getting the render function and rendering to the correct.
  43. if compress:
  44. render = render_to_kmz
  45. else:
  46. render = render_to_kml
  47. return render('gis/kml/placemarks.kml', {'places': placemarks})
  48. def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS):
  49. """
  50. Return KMZ for the given app label, model, and field name.
  51. """
  52. return kml(request, label, model, field_name, compress=True, using=using)