Serving KML from your Django webapp to feed Google-earth isn't that hard, it's just some fun with templates, plus some headers. But serving a compressed version of your KML needs a trick.
KMZ isn't just zipped KML. A good KMZ file is a zipped file that decompress to a file called 'doc.kml', which is a KML file.
So, I suppose 'http://yourdomain.com/kml/' points to a view generating a well-formed KML. I even suppose that 'http://yourdomain.com/kmz/' points to the same view, but it will serve KMZ instead that KML: no change needed in your code!
If your webapps serves more than one KML file you just need to append the new KMZ urls to your urls.py, pointing to the very same view serving the KML version. Then add that urls to the list in this middleware. As an example I included a 'http://yourdomain.com/kml/restricted/' to 'http://yourdomain.com/kmz/restricted/' conversion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from cStringIO import StringIO
import zipfile
class KMZMiddleware(object):
"""
Middleware for serving KML data or converting it to KMZ.
"""
def process_response(self, request, response):
if request.path in ('/kmz/', '/kmz/restricted/', ):
kmz = StringIO()
f = zipfile.ZipFile(kmz, 'w', zipfile.ZIP_DEFLATED)
f.writestr('doc.kml', response.content)
f.close()
response.content = kmz.getvalue()
kmz.close()
response['Content-Type'] = 'application/vnd.google-earth.kmz'
response['Content-Disposition'] = 'attachment; filename=foo.kmz'
response['Content-Description'] = 'some description'
response['Content-Length'] = str(len(response.content))
if request.path in ('/kml/', '/kml/restricted/', ):
response['Content-Type'] = 'application/vnd.google-earth.kml+xml'
response['Content-Disposition'] = 'attachment; filename=foo.kml'
response['Content-Description'] = 'some description'
response['Content-Length'] = str(len(response.content))
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
So, in other words, KMZ is just zipped KML.
#
to scottj: no it isn't try to zip KML data to a file: you won't get a working KMZ
#
Please login first before commenting.