Friday 16 February 2018

javascript - How to add a polygon from PostGIS ST_AsGeoJSON into Leaflet?


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);
layer.addTo(map);
}

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


{"type":"Polygon","coordinates":[[[10,370],[20,380],[30,410],[-10,395],[10,370]]]}

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?




Answer



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": [
97.03125,

39.7265625
]
},
"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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...