Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I try to use the following function to add polygons to my Leaflet map.

function polygon(geojson)
    alert(geojson); // alert for testing
    layer = L.geoJson(geojson);

When I call the above function with the GeoJSON string I fetched from a PostGIS table using ST_AsGeoJSON(), the following string is alterted.


But no polygon shows up on the map. As far as I can say, there is no error message. And I can definitely say that a polygon with the points 10 370, 20 380, 30 410, 10 395 shows up on the map, if I insert it using L.polygon.

What's wrong?

share|improve this question
up vote 3 down vote accepted

According to the docs, ST_AsGeoJSON() returns the geometry as a GeoJSON element. It does not return a whole GeoJSON object. Here is an example of a full GeoJSON object:

    "type": "Feature",
    "id": "OpenLayers.Feature.Vector_314",
    "properties": {},
    "geometry": {
        "type": "Point",
        "coordinates": [
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"

The .geoJson method expects GeoJSON whereas ST_AsGeoJSON() only returns the geometry element and not the whole GeoJSON, that's why the method fails and nothing is plotted.

share|improve this answer

Adding on what R.K. is saying, your best bet is to refine your postgis query to build the entire GeoJSON object.

This should explain how:

share|improve this answer
Thanks for your addition. – danijar May 10 '13 at 8:37

you can do it using this SQL code

SELECT row_to_json(fc)
 FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features
 FROM (SELECT 'Feature' As type, 
    ST_AsGeoJSON(lg.geom)::json As geometry, 
    select row_to_json(t) 
    from (select FIELD_1, FIELD_2, FIELD_N) t
    As properties
   FROM MY_TABLE_OR_VIEW As lg   ) As f )  As fc;

Easy and will work!!!

share|improve this answer

Your Answer


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.