5

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 properties 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
 }
5

This function should work for you; just pass the result.rows object as the argument;

  toGeoJson: function(rows){
    var obj, i;

    obj = {
      type: "FeatureCollection",
      features: []
    };

    for (i = 0; i < rows.length; i++) {
      var item, feature, geometry;
      item = rows[i];

      geometry = JSON.parse(item.geometry);
      delete item.geometry;

      feature = {
        type: "Feature",
        properties: item,
        geometry: geometry
      }

      obj.features.push(feature);
    } 
    return obj;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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