Login

Map GPX files to 3D GeoDjango Models

Author:
jbronn
Posted:
November 16, 2009
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

GPXMapping is a subclass of LayerMapping that imports GPX files into 3D GeoDjango models (requires Django 1.2 or SVN r11742 and higher). Here's an example of GeoDjango models for GPX points and tracks, respectively:

from django.contrib.gis.db import models

class GPXPoint(models.Model):
    timestamp = models.DateTimeField()
    point = models.PointField(dim=3)
    objects = models.GeoManager()

    def __unicode__(self):
        return unicode(self.timestamp)

class GPXTrack(models.Model):
    track = models.MultiLineStringField(dim=3)
    objects = models.GeoManager()

Assuming the above models, then GPXMapping may be used to load GPX tracks and waypoints (including elevation Z values):

track_point_mapping = {'timestamp' : 'time',
                       'point' : 'POINT',
                      }

track_mapping = {'track' : 'MULTILINESTRING'}

gpx_file = '/path/to/file.gpx'

lm = GPXMapping(GPXPoint, gpx_file, track_point_mapping, layer='track_points')
lm.save(verbose=True)

lm = GPXMapping(GPXTrack, gpx_file, track_mapping, layer='tracks')
lm.save(verbose=True)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import os
from django.contrib.gis.utils import LayerMapping

class GPXMapping(LayerMapping):
    def __init__(self, *args, **kwargs):
        # Setting this environment variable tells OGR to use the elevation
        # attribute as the Z coordinate value on the geometries.  See:
        #  http://www.gdal.org/ogr/drv_gpx.html
        os.environ['GPX_ELE_AS_25D'] = 'YES'
        super(GPXMapping, self).__init__(*args, **kwargs)
        # Unset the environment variable, so it doesn't affect other
        # GPX DataSource objects.
        os.environ.pop('GPX_ELE_AS_25D')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

wilane (on December 12, 2009):

Great, thanks for this great recipe. Is there any way to plot it on a GoogleMap widget which seems to only accept LineStrings, or I'm overlooking something ?

Keep up the good work.

#

Please login first before commenting.