Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

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.

share|improve this answer
add comment

So depending on the size of your geometries, you may not want to fetch the entire polygon as part of the initial request. (Load times would get awful)

So create a view you can hit with ajax:

def get_location_polygons(request):
    response_data = {'data':None,}
    location = get_object_or_404(County, cd=request.GET['code'])

    # Build the polygons        
    response_data['data'] = {
        'polygons' : location.geom.geojson,
        'title' : location.cd
    }

    return HttpResponse(json.dumps(response_data), mimetype="application/json")

Then Call some JS to parse/display the polygon:

function fetch_polygons(code)
{       
    $.ajax({
        url : '/get-location-polygons/', // Whatever URL You decide for that AJAX request
        data : {'code': code},
        dataType : 'json',
        type : 'GET',
        success: function(data)
        {
                poly = JSON.parse(data.data['polygons'])
                var paths = coord_to_paths(poly.coordinates);
                polygon = new google.maps.Polygon({ 
                    paths : paths, 
                    strokeColor : "#CCC", 
                    strokeOpacity : .5, 
                    strokeWeight : 1, 
                    fillColor : "#CCC", 
                    fillOpacity : .5
                });

                polygon.setVisible(true)
                polygon.setMap(map); // Your map reference
                polygon.infoWindow = new google.maps.InfoWindow({
                    content: '<strong>' + data.data.title + '</strong>',
                }); 
        }
    });     
}

function coord_to_paths(coords)
{
    var paths = [];
    for (var i = 0; i < coords.length; i++)
    { 
        for (var j = 0; j < coords[i].length; j++)
        { 
            var path = []; 
            for (var k = 0; k < coords[i][j].length; k++)
            {
                path.push(ll); 
            } 
            paths.push(path); 
        } 
    }

    return paths;       
}

coord_to_paths is pretty important for making multipolygon abjects behave nicely in V2 of the gmaps api.

share|improve this answer
1  
This is a pared down example of what I'm doing here: gis.stackexchange.com/questions/27300/… –  Francis Yaconiello Sep 17 '12 at 19:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.