I am trying to build a GeoJSON object from a SQL query to some GIS point data in a postgis postgresql database. A snippet of my node.js app.js is below.
As it stands I understand building the type and features, but don't know how to attach a properties array to each GeoJSON record (in the below, it all renders at the end, separate from (not collated with) the features).
THE QUESTION: What do I need to do so that the properties attach (collate) for each record in the loop that builds the GeoJSON So that it looks more like this http://www.geojson.org/geojson-spec.html#examples?
`function GrabData(bounds, res){
pg.connect(conn, function(err, client){
var moisql = 'SELECT ttl, (ST_AsGeoJSON(the_geom)) as locale from cpag;'
client.query(moisql, function(err, result){
var featureCollection = new FeatureCollection();
for(i=0; i<result.rows.length; i++){
featureCollection.features[i] = JSON.parse(result.rows[i].locale);
featureCollection.properties[i] = JSON.parse(result.rows[i].ttl); //this is wrong
}
res.send(featureCollection);
});
});
}
function FeatureCollection(){
this.type = 'FeatureCollection';
this.features = new Array();
this.properties = new Object; //this is wrong
}
`
This should do the job:
...
for(i=0; i<result.rows.length; i++){
var feature = new Feature();
feature.geometry = JSON.parse(result.rows[i].locale);
feature.properties = {"TTL", result.rows[i].ttl};
featureCollection.features.push(feature);
}
...
Using:
function FeatureCollection(){
this.type = 'FeatureCollection';
this.features = new Array();
}
function Feature(){
this.type = 'Feature';
this.geometry = new Object;
this.properties = new Object;
}
I recently wrote a little helper module for this purpose. It's very straightforward to use -
var postgeo = require("postgeo");
postgeo.connect("postgres://user@host:port/database");
postgeo.query("SELECT id, name ST_AsGeoJSON(geom) AS geometry FROM table", "geojson", function(data) {
console.log(data);
});
You can find the repo here - https://github.com/jczaplew/postgeo