morgan herlocker

about work bsky github posts rss

Merging Polygons with node.js

Merging a set of polygons with turf is pretty straight forward.

  1. Get your polygon features into a feature collection like so:
  1. Load the file into memory with node's fs module:
var require('turf')

// load countries
t.load('./countries.geojson', function(err, countries){
  
})
  1. call turf's merge function:
t.merge(countries, function(err, world){

})
  1. Lastly, write the file to disc or display it somewhere. Here it is all together:
var t = require('turf'),
    fs = require('fs')

// load countries
t.load('./countries.geojson', function(err, countries){
  // merge the feature collection
  t.merge(countries, function(err, world){
    // write out the file
    fs.writeFile('./world.geojson', JSON.stringify(world), function(err){
      console.log('presto!')
    })
  })
})

And here is the result:

I packaged this all up into a github repo if you want to clone it an try it out. To test out the code do:

git clone https://github.com/morganherlocker/turf-world-merge.git
cd turf-world-merge
npm install
node index.js

1-30-14