[GIS] Django PolygonField: how to display on map

geodjangopolygonweb-mapping

Extremely beginner question.

I have a GeoDjango model with a MultiPolygonField. How do I retrieve the value of this field and display it as a polygon on a map?

class county(models.Model):
    cd = models.CharField(max_length=10)
    geom = models.MultiPolygonField(srid=27700)
    objects = models.GeoManager()

def lsoa(request, code):
    county = get_object_or_404(county.objects, cd=code)
    return render_to_response('county.html', { 'county': county }, context_instance = RequestContext(request))

I know GeoJson is involved somewhere along the line, but I'm struggling with to get it out of Django, and with how to display it.

Best Answer

There's a few ways to do this. One is to simply put the geojson of the object into a javascript variable and then render the geometry of the geojson into your map. For example, in your header of county.html you can put something like:

var countyJson = {{county.geom.geojson|safe}};

You may also wish to transform the geometry into epsg:4326 before bringing it into the template so you get the standard lat/lng commonly used in most many frameworks. You can do this in your view:

county.geom.transform(4326)

If you are still stuck, info on what clientside mapping framework (eg Google Maps, OpenLayers, etc.) you are using since the syntax for displaying the polygon will vary.