Monday, July 25, 2011

Simple gvSIG Jython Console script to list layers in a Map View

I have always wondered how to use the Jython Console in gvSIG. There isn't much published documentation on using it or perhaps I simply were not very good in finding it. In any case, I managed to figure out how to access and use the gvSIG objects from within the Console window. To illustrate, I wrote a simple Python script that simply gets a pointer to the active Map View window and then loop through the list of loaded layers and print out the name and number of records for each layer.

Below is the example code listing and saved to a script file

#import gvSIG library
from gvsiglib import *

#get the map view
mapview = gvSIG.getActiveDocument()
#get the map control
mapctrl = mapview.getMapControl()
#get the map context
mapctx = mapctrl.getMapContext()

#print the list of layers in the map view and the record count for each layer
for i in range(mapctx.getLayers().getLayersCount()):
    layer = mapctx.getLayers().getLayer(i)
    rs = layer.getRecordset()
    print "%s,%d records" % (layer.getName(), rs.getRowCount())

  1. Start up gvSIG OADE 2010. Open a Map View. Load in a couple of layers e.g. BLDG.shp and layer1.shp.

  2. Select File | Scripting | Jython Console.

    The Jython window appears.

  3. At the Jython prompt, type in: execfile ("c:/temp/").

    The script is loaded and executed listing out the layers and the number of records.
Instead of loading from a script file, the Jython Console can accept typing in the code line by line in the Console prompt. However, I find using a script file is more convenient. 

After the gvsiglib has been imported into the Console, it is possible to access the gvSIG objects and make use of the auto-completion capabilities of the Jython Console to explore the object methods and properties as shown in the screen shot below.

No comments: