How To: Write shapefiles with MapObjects-Java


Instructions provided describe the various methods for creating a shapefile using the MapObjects—Java API and the important details of each method.


Shapefiles can be created by three different levels of interaction. These are as follows:

  1. The highest level of interaction provides convenience methods that accept Layers and FeatureClasses. These methods create a shapefile that contains ALL of the features of the layer or feature class. There are two static methods at this level:



    It is also possible to use these methods with the MemoryFeatureClass and MemoryLayerSource objects, respectively. This allows a shapefile to be created from features held in memory.

  2. The medium level of interaction provides a series of methods to create a shapefile one feature at a time. This gives some flexibility when determining which features to output to the shapefile. The general sequence of method calls is as follows:

    ShapefileWriter sw = new ShapefileWriter(path,name,shapeType);


    sw.addFeature(feature); // Repeat for each feature.


    Keep in mind that the shapeType argument is NOT the same as the feature class type. For instance, a feature class type may be MapDataset.POLYGON, but the shape type could be ShapeTypes.POLYGON, ShapeTypes.POLYGONM, or ShapeTypes.POLYGONZ. A static function has been provided that returns the shape type for a given feature class:


    This middle level of access gives the greatest amount of flexibility. For instance, the features written out to the file may be the result of a search or selection made on a feature class or layer. In addition, a layer's current selection set of features may be written out as well. The only precaution is to make sure that all of the features added to the shapefile are of the same type. For example, it is not possible to add point features to a polyline shapefile.

    Refer to Sample 6.2 - 'Create a Shapefile' in the Tutorial sample application for an example using this level of interaction.

  3. The lowest level of access allows the shapefile to be created directly using the corresponding shapes. This level is best used by those who are converting geometry from one primitive source to another. However, a distinct advantage of the other two levels over this one is that the conversion from FeatureGeometry to ShpGeometry is automatically handled. At this level, FeatureGeometry objects will have to explicitly be converted to ShpGeometry.
    // Convert polygon feature to polygon shape.
    polyFeature = (Polygon)featureGeometry;
    polyShape = new PolygonShp();
    rings = polyFeature.getRings();
    for (i=0; i<rings.length; i++) {
    pc = rings[i].getPoints();