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.
 
 
 
 

64 lines
2.3 KiB

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