Crop a vector

This script is going to allow you to cut one or several vector files on the basis of a vector layer


Requirements : You need OrbisGIS 2.2.0 (or more) to run this script.


Script :

import org.gdms.data.DataSource;

import org.orbisgis.core.layerModel.MapContext;


/** Specify the name of the layer which will be the stencil. In this example, the stencil layer is called agglo_nantes */

zone = "agglo_nantes";

/** Specify here the suffix which will be generated at the end of each layer cut */

suffixe = "_agglo";


MapContext mc = mc;

print(mc.getLayerModel().getLayerCount());


for (int i = 0; i< mc.getLayerModel().getLayerCount(); i++){

print(mc.getLayerModel().getLayer(i).getName());

layerName = mc.getLayerModel().getLayer(i).getName();

layerNameOut = layerName + suffixe;

/** Instead of /tmp/, write the url of the destination folder (here, files will be in .shp) */

SQL("SELECT REGISTER('/tmp/"+ layerNameOut +".shp', '"+ layerNameOut+"');");

/** Here you write the SQL query, which crop the vector layer*/

SQL("CREATE TABLE " + layerNameOut + " as select st_intersection(a.the_geom,b.the_geom) as the_geom, a.*{except the_geom} from " + layerName + " a, " + zone + " b where st_intersects(a.the_geom, b.the_geom);");

}


Procedure :

1- Paste the script in the Beanshell console

2- In the Geocatalog, load all datas which you want to crop + the stencil layer (called "zone" in the script)

3- Drag & Drop layers you want to crop in the TOC --> the "stencil" layer must stay in the Geocatalog ... otherwise it will cut with itself

4- Modify "zone" and "suffixe" variables and the destination address of your layers and format

5- Run the script


Note: In this script, we use the SQL function Intesection which is based on an operator instersection. Consequently, all objects that intersect the stencil area will be preserved --> even those beyond the area.


Example of cutting some layers of the BD TOPO from IGN on the Nantes conurbation :


1- We put the layers in the TOC and we adapted the script to our data


2- We run the scipt (OrbisGIS is working)

3- Once processing is complete, we can compare the result with the original


Before

After


New layers are cut, renamed with the suffix and stored at the specified address.




Script's author : Erwan Bocher - IRSTV - Ecole Centrale de Nantes

Copyright - IRSTV - 2009 - www.orbisgis.org