Monday, April 15, 2013

Using the NetTopologySuite to read and write Shapefiles in C#

I was looking for a .NET library to use to read and write Shapefiles without using unmanaged dynamic link libraries. I found quite a few that could read but not write Shapefiles. In the end, I found the NetTopologySuite at http://code.google.com/p/nettopologysuite/ to suit my requirements the best.

The following code snippet show how to use the library's ShapefileDataReader to read a Shapefile. In the example, all the database records and the Shape geometries are read into a features collection.


using GisSharpBlog.NetTopologySuite.Features;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.IO;
using GeoAPI.Geometries;

...etc....

GeometryFactory factory = new GeometryFactory();
ShapefileDataReader shapeFileDataReader = new ShapefileDataReader(shpFilename, factory);
 
//Display the shapefile type
ShapefileHeader shpHeader = shapeFileDataReader.ShapeHeader;
Console.WriteLine(string.Format("Shape type: {0}", shpHeader.ShapeType));
 
//Display the min and max bounds of the shapefile
IEnvelope bounds = shpHeader.Bounds;
Console.WriteLine(string.Format("Min bounds: ({0},{1})", bounds.MinX, bounds.MinY));
Console.WriteLine(string.Format("Max bounds: ({0},{1})", bounds.MaxX, bounds.MaxY));
 
//Display summary information about the Dbase file
DbaseFileHeader header = shapeFileDataReader.DbaseHeader;
Console.WriteLine("Dbase info");
Console.WriteLine(string.Format("{0} Columns, {1} Records", header.Fields.Length, header.NumRecords));
for (int i = 0; i < header.NumFields; i++)
{
DbaseFieldDescriptor fldDescriptor = header.Fields[i];
Console.WriteLine(string.Format("   {0} {1}", fldDescriptor.Name, fldDescriptor.DbaseType));
}
 
//Reset the pointer to the start of the shapefile, just in case
//shapeFileDataReader.Reset();
 
//Read through all records of the shapefile (geometry and attributes) into a feature collection 
ArrayList features = new ArrayList();
while (shapeFileDataReader.Read())
{
Feature feature = new Feature();
AttributesTable attributesTable = new AttributesTable();
string[] keys = new string[header.NumFields];
IGeometry geometry = (Geometry)shapeFileDataReader.Geometry;
for (int i = 0; i < header.NumFields; i++)
{
DbaseFieldDescriptor fldDescriptor = header.Fields[i];
keys[i] = fldDescriptor.Name;
attributesTable.AddAttribute(fldDescriptor.Name, shapeFileDataReader.GetValue(i));
}
feature.Geometry = geometry;
feature.Attributes = attributesTable;
features.Add(feature);
}
//Close and free up any resources
shapeFileDataReader.Close();
shapeFileDataReader.Dispose();

It is important to free up any resources used by calling the Close and Dispose methods, especially if you want to apply any file based operations e.g. deleting or renaming onto the Shapefile.

The following screenshot shows an example output from the code snippet.


The ShapefileDataWriter class can be used to create a Shapefile. It seems that the class can only create new Shapefiles and there are no methods append to an existing Shapefile. The following code snippet shows how to write features with geometry and attributes into a Shapefile.



//Create a new shapefile from features
GeometryFactory outGeomFactory = new GeometryFactory();
//The constructor will append a ".shp" extension to the input filename so the 1st argument should not have an extension at all
string outShpFilenameNoExt = Path.Combine(Path.GetDirectoryName(outShpFilename), Path.GetFileNameWithoutExtension(outShpFilename));
ShapefileDataWriter writer = new ShapefileDataWriter(outShpFilenameNoExt, outGeomFactory);
DbaseFileHeader outDbaseHeader = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
writer.Header = outDbaseHeader;
writer.Write(features); 

Monday, April 8, 2013

Add text label as attribute to polygon in Global Mapper

It is useful to be able to copy the text label from points (so called area centroids) to the enclosing area polygons as attributes. This can be done using Global Mapper's Add Attributes to Selected Areas from Points command. If the text labels are not already point attributes, then there is a simple workaround that can be performed to convert them into point attributes. The following example illustrates the workaround by simply exporting out the points as a Shapefile and using the exported Shapefile for the source point attributes.

  1. In Global Mapper, create, load and display the area polygons and points with labels.


  2. Select File | Export Vector Format.

    The Select Export Format dialog box appears.

  3. Choose Shapefile. Click OK.

    The Shapefile Export Options appear.

  4. Toggle on Export Points. Specify the destination point Shapefile name and location, e.g. C:\Temp\centroid.shp.


  5. Click OK.

    The point Shapefile is created.
  6. Unload the original point layer.


  7. Drag and drop the exported point Shapefile, e.g. centroid.shp, onto the Global Mapper's map view.
  8. Press ALT+P. Click on one of the points.

    The Feature Information dialog box appears.

    Note: the text label is an attribute
    .
  9. Press ALT+D. Click and drag to select all the area polygons and points.


  10. Press right click on the mouse.

    A popup menu appears.


  11. Choose Attribute Functions | Add Attributes to Selected Areas from Points.

    A prompt appears.

  12. Click Yes.

    A message appears.

  13. Click OK.

    The text label is added to the area polygons as attributes.

Monday, April 1, 2013

Build libLAS for Windows 64 bit with GDAL and GeoTIFF support


In order to build 64 bit Windows binaries of liblas, the header files and 64 bit binaries for Boost must be accessible by Microsoft Visual Studio. The CMake utility from http://www.cmake.org needs to be used to configure and generate the Microsoft Visual Studio project files for liblas. The following illustrates how I build the liblas 64 bit binaries with GDAL and GeoTIFF support. Note that the 64-bit executables may not run successfully even though the compilation is successful depending on how the source code was written.
  1. Download the latest liblas source code from http://www.liblas.org/download.html. Extract the files to a folder e.g. E:\Work\src\liblas-1.7.0\.
  2. On the Windows Desktop, select Start | All Programs | CMake 2.8 | CMake (cmake-gui).

    The CMake application appears.
  3. In the Where is the source code field, click Browse Source.

    The Browse for Folder dialog box appears.
  4. Select the folder where the liblas archive was extracted, e.g. E:\Work\src\libLAS-1.7.0\. Click OK.
  5. In the Where to build the binaries field, click Browse Build.

    The Browse for Folder dialog box appears.
  6. Select or create the folder where the Microsoft Visual Studio solution project files will be created e.g. E:\Work\src\libLAS-1.7.0\bin\. Click OK.

  7. Click Configure.

    A prompt appears.
  8. In the combo box, choose a generator for this project e.g. Visual Studio 10 Win64. Click Finish.

    A Error message appears.
  9. Close the message.

  10. In the list box, select Boost_INCLUDE_DIR. Then click the browse [...] button.

    The Browse For Folder dialog box appears.
  11. Choose the root folder containing Boost e.g. E:\Work\src\boost_1_52_0\. Click OK.

    Note: the boost folder containing the header include files should be underneath the root folder.
  12. Click Configure again.

    The configuration files are created.
  13. Toggle on WITH_GDAL and WITH_GEOTIFF. Click Configure.

    An error message appears.
  14. Close the message. Select GDAL_INCLUDE_DIR. Click the browse [...] button.

    The Browse for Folder dialog box appears.
  15. Select the folder containing the GDAL header include files e.g. E:\Work\src\gdal-1.9.2\gcore\. Click OK.
  16. Select GDAL_LIBRARY. Click the browse [...] button.

    The Select File for GDAL_LIBRARY dialog box appears.
  17. Select the GDAL library e.g. E:\Work\src\gdal-1.9.2\gdal_i.lib. Click Open.
  18. Click GEOTIFF_INCLUDE_DIR. Click the browse [...] button.

    The Browse for Folder dialog box appears.
  19. Select the folder containing the libGeotiff header files e.g. E:\Work\src\libgeotiff-1.4.0\. Click OK.
  20. Select GEOTIFF_LIBRARY. Click the browse [...] button.

    The Select File for GEOTIFF_LIBRARY dialog box appears.
  21. Choose the GEOTIFF library file e.g. E:\Work\src\libgeotiff-1.4.0\geotiff_i.lib. Click Open.
  22. Click Generate.

    An error message appears.
  23. Close the message. Click TIFF_INCLUDE_DIR. Click the browse [...] button.

    The Browse for Folder dialog box appears.
  24. Select the folder containing the TIFF header files e.g. E:\Work\src\tiff-4.0.3\libtiff\. Click OK.
  25. Click TIFF_LIBRARY. Click the browse [...] button.

    The Select File for TIFF_LIBRARY dialog box appears.
  26. Select the TIFF library file e.g. E:\Work\src\tiff-4.0.3\libtiff\libtiff_i.lib. Click Open.
  27. Click Generate.

    The Microsoft Visual Studio project files are generated the specified destination build folder.
  28. Close CMake.
  29. Run Microsoft Visual Studio 2010. Open up the libLAS.sln file.
  30. Press F7 to build all the projects.

    Note: it might be necessary to add in the paths to the include files if the compiler cannot locate them in the build process.

    The 64 bit liblas binaries are generated.

Monday, March 25, 2013

Build the basic liblas for 64 bit Windows (no GDAL and GeoTIFF support)

In order to build 64 bit Windows binaries of liblas, the header files and 64 bit binaries for Boost must be accessible by Microsoft Visual Studio. The CMake utility from http://www.cmake.org needs to be used to configure and generate the Microsoft Visual Studio project files for liblas. The following illustrates how I build the basic liblas 64 bit binaries (no GDAL or GeoTIFF support). Note that the 64-bit executables may not run successfully even though the compilation is successful depending on how the source code was written.
  1. Download the latest liblas source code from http://www.liblas.org/download.html. Extract the files to a folder e.g. E:\Work\src\liblas-1.7.0\.
  2. On the Windows Desktop, select Start | All Programs | CMake 2.8 | CMake (cmake-gui).

    The CMake application appears.
  3. In the Where is the source code field, click Browse Source.

    The Browse for Folder dialog box appears.
  4. Select the folder where the liblas archive was extracted, e.g. E:\Work\src\libLAS-1.7.0\. Click OK.
  5. In the Where to build the binaries field, click Browse Build.

    The Browse for Folder dialog box appears.
  6. Select or create the folder where the Microsoft Visual Studio solution project files will be created e.g. E:\Work\src\libLAS-1.7.0\bin\. Click OK.

  7. Click Configure.

    A prompt appears.
  8. In the combo box, choose a generator for this project e.g. Visual Studio 10 Win64. Click Finish.

    A Error message appears.
  9. Close the message.

  10. In the list box, select Boost_INCLUDE_DIR. Then click the browse [...] button.

    The Browse For Folder dialog box appears.
  11. Choose the root folder containing Boost e.g. E:\Work\src\boost_1_52_0\. Click OK.

    Note: the boost folder containing the header include files should be underneath the root folder.
  12. Click Configure again.

    The configuration files are created.
  13. Click Generate.

    The Microsoft Visual Studio project files are generated the specified destination build folder.
  14. Close CMake.
  15. Run Microsoft Visual Studio 2010. Open up the libLAS.sln file.
  16. Press F7 to build all the projects.

    The 64 bit liblas binaries are generated.

Monday, March 18, 2013

Simple Android app for converting between GPS Week/Seconds Time and local date time

The date time used by the Global Positioning System (GPS) is normally expressed as a week number and a seconds-of-week number. This format is not as easy to work with as a normal calendar date time. I made this simple Android App for converting the GPS Time (in week and seconds-of-week format) and local calendar date time (in UTC+offset format), which is easier to work with. It has the option to choose which local UTC time zone to use for conversion. The app will automatically adjust the local time for GPS leap seconds.

Clicking on the buttons will bring up pickers for selecting the input values, as shown below. 

Get it on Google Play

Monday, March 11, 2013

Build 64 bit GDAL for Windows

In building libLAS from source, there is the option of linking it with GDAL. Since I was interested in making 64 bit Windows version of libLAS, I had to find or make my own 64 bit versions of GDAL. Eventually, I decided to build my own. The following are the steps I did to compile 64 bit GDAL on Microsoft Visual Studio 2010. Note that the 64 bit executables may not run successfully depending on the source code even if the compilation is successful.
  1. Download the latest GDAL source code from http://download.osgeo.org/gdal/. Extract the files into a folder e.g. C:\Work\src\gdal-1.9.2\.
  2. On the Windows Desktop, select Start | All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio x64 Win64 Command Prompt.

    The Visual Studio x64 Win64 Command Prompt appears.
  3. In the Command Prompt, change directory to the extracted GDAL source code root folder.

    C:\> cd \Work\src\gdal-1.9.2
  4. Build the GDAL 64 bit Windows binaries with the nmake command.

    C:\> nmake /f makefile.vc MSVC_VER=1600 WIN64=YES

    The binaries are generated.

Monday, March 4, 2013

How to build 64-bit versions of libgeotiff for Windows

I could not find 64-bit binaries of the open-source libGeotiff library so I decided to download the most recent source code from http://trac.osgeo.org/geotiff/ so that I could use Microsoft Visual Studio 2010 to compile make my own. Other libraries are also required so I downloaded the latest source code for libTiff from http://download.osgeo.org/libtiff/ and Proj4 from http://trac.osgeo.org/proj/. I have no problems compiling libTiff and Proj4 as is but I had to modify the libGeotiff's makefile.vc file to make it compile successfully. Note that successful compilation does not necessarily mean the 64 bit executables will run successfully.



Compile 64 bit version of Proj4
  1. Extract the Proj4 source code into a folder e.g. C:\Work\src\proj-4.8.0\
  2. Select Start | All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio x64 Win64 Command Prompt.

    The Win64 Command Prompt appears.
  3. In the Command Prompt, type in and enter the following:

    C:\> cd \Work\src\proj-4.8.0
  4. Run the nmake build command in the Command Prompt:

    C:\> nmake /f makefile.vc

    The 64 bit version of Proj4 is created.
Compile 64 bit version of libTiff
  1. Extract the libTiff source code into a folder e.g. C:\Work\src\tiff-4.0.3\.
  2. Open up the Win64 Command Prompt if it is not  already on the screen.
  3. In the Command Prompt, type in the following command.

    C:\> cd \Work\src\tiff-4.0.3\
  4. Run the nmake build command in the Command Prompt.

    C:\> nmake /f makefile.vc

    The 64 bit version of libTiff is created.
Compile 64-bit version of libGeotiff
  1. Extract the libGeotiff source code into a folder e.g. C:\Work\src\libgeotiff-1.4.0\.
  2. Use a text editor to open up the header file geo_config.h. Add in the line #define BUILD_AS_DLL 1 as shown in red below.

    /* geo_config.h.  Generated from geo_config.h.in by configure.  */
    #ifndef GEO_CONFIG_H
    #define GEO_CONFIG_H
    
    #define BUILD_AS_DLL 1
    
    /* Define if you have the ANSI C header files.  */
    #define STDC_HEADERS 1
    
    /* Define if you have the <stdlib.h> header file.  */
    #define HAVE_STDLIB_H 1
    
    /* Define if you have the <string.h> header file.  */
    #define HAVE_STRING_H 1
    
    /* Define if you have the <strings.h> header file.  */
    #define HAVE_STRINGS_H 1
    
    #define HAVE_LIBPROJ 1
    /* #undef HAVE_PROJECTS_H */
    
    #endif /* ndef GEO_CONFIG_H */
    

  3. Use a text editor to open up the libGeotiff's makefile.vc file.
  4. Replace the contents of makefile.vc with the contents below.

    Note: the parts that were modified are colored in red.

    #
    # Typically the only thing that needs to be changed are the paths to the
    # TIFF tree.  Note that we expect an existing build tree, in part because we
    # need private include files from libtiff, but also we need access to getopt.h.
    # in the ports directory.
    #
    # You may want to add optimization options to the CFLAGS macro as well. 
    #
    
    TIFF = C:\Work\src\tiff-4.0.3
    PROJ4 = C:\Work\proj-4.8.0
    
    TIFF_INC = -I$(TIFF)\libtiff
    TIFF_LIB = $(TIFF)\libtiff\libtiff.lib
    TIFF_LIB_DLL = $(TIFF)\libtiff\libtiff_i.lib
    PROJ4_INC = -I$(PROJ4)\src
    PROJ_LIB = $(PROJ4)\src\proj.lib
    PROJ4_LIB_DLL = $(PROJ4)\src\proj_i.lib
    
    # Installation locations (with install, or devinstall targets)
    PREFIX =    release    
    BINDIR =    $(PREFIX)\bin
    LIBDIR =    $(PREFIX)\lib
    INCDIR =    $(PREFIX)\include
    DATADIR =    $(PREFIX)\share\epsg_csv
    
    #
    CC      = cl
    INCL    = -I. -Ilibxtiff $(TIFF_INC) $(PROJ4_INC)
    
    
    # Pick the first LIBS definition for a static libtiff.lib or the second
    # to link against the libtiff DLL.
    
    #LIBS    = geotiff.lib $(TIFF_LIB) $(PROJ4_LIB)
    LIBS    = geotiff_i.lib $(TIFF_LIB_DLL) $(PROJ4_LIB_DLL)
    
    DLLNAME = geotiff.dll
    
    # Set optimization or debug flags here.
    CFLAGS  = $(INCL) /MD /Ox /nologo
    #CFLAGS  = $(INCL) /MD /Zi /nologo
    
    #
    OBJS    = \
        xtiff.obj \
        geo_free.obj \
        geo_get.obj \
        geo_names.obj \
        geo_new.obj \
        geo_print.obj \
        geo_set.obj \
        geo_tiffp.obj \
        geo_write.obj \
        geo_extra.obj \
        geo_trans.obj \
        geo_normalize.obj \
        geotiff_proj4.obj \
        geo_simpletags.obj \
        cpl_csv.obj \
        cpl_serv.obj
    
    all:    geo_config.h geotiff.lib $(DLLNAME) listgeo.exe geotifcp.exe
    
    listgeo.exe:    bin\listgeo.c geotiff.lib
        $(CC) $(CFLAGS) bin\listgeo.c $(LIBS)
        
    geotifcp.exe:    bin\geotifcp.c geotiff.lib
        $(CC) $(CFLAGS) bin\geotifcp.c bin\getopt.c $(LIBS)
        
    gt_update.exe:    bin\gt_update.c geotiff.lib
        $(CC) $(CFLAGS) bin\gt_update.c bin\getopt.c geotiff.lib $(LIBS)
        
    geotiff.lib:    $(OBJS)
        lib /out:geotiff.lib $(OBJS)
    
    #
    $(DLLNAME):    $(OBJS)
        link /dll /out:$(DLLNAME) /implib:geotiff_i.lib $(OBJS) $(TIFF_LIB_DLL) $(PROJ4_LIB_DLL)
        if exist $(DLLNAME).manifest mt -manifest $(DLLNAME).manifest -outputresource:$(DLLNAME);2
    
    geo_config.h:    geo_config.h.vc
        copy geo_config.h.vc geo_config.h
    
    xtiff.obj: libxtiff\xtiff.c
        $(CC) -c $(CFLAGS) libxtiff\xtiff.c
    
    geo_free.obj: geo_free.c
        $(CC) -c $(CFLAGS) geo_free.c
    
    geo_get.obj: geo_get.c
        $(CC) -c $(CFLAGS) geo_get.c
    
    geo_names.obj: geo_names.c
        $(CC) -c $(CFLAGS) geo_names.c
    
    geo_new.obj: geo_new.c
        $(CC) -c $(CFLAGS) geo_new.c
    
    geo_print.obj: geo_print.c
        $(CC) -c $(CFLAGS) geo_print.c
    
    geo_set.obj: geo_set.c
        $(CC) -c $(CFLAGS) geo_set.c
    
    geo_tiffp.obj: geo_tiffp.c
        $(CC) -c $(CFLAGS) geo_tiffp.c
    
    geo_write.obj: geo_write.c
        $(CC) -c $(CFLAGS) geo_write.c
    
    geo_trans.obj: geo_trans.c
        $(CC) -c $(CFLAGS) geo_trans.c
    
    geo_extra.obj: geo_extra.c
        $(CC) -c $(CFLAGS) geo_extra.c
    
    geo_normalize.obj: geo_normalize.c
        $(CC) -c $(CFLAGS) geo_normalize.c
    
    geotiff_proj4.obj: geotiff_proj4.c
        $(CC) -c $(CFLAGS) geotiff_proj4.c
    
    cpl_csv.obj: cpl_csv.c
        $(CC) -c $(CFLAGS) cpl_csv.c
    
    cpl_serv.obj: cpl_serv.c
        $(CC) -c $(CFLAGS) cpl_serv.c
    
    clean:
        -del *.obj
        -del *.exe
        -del *.lib
        -del *.dll
        -del *.manifest
    
    install:    all
        -mkdir $(PREFIX)
        -mkdir $(BINDIR)
        -mkdir $(DATADIR)
        copy *.dll $(BINDIR)
        copy *.exe $(BINDIR)
        -copy csv\*.csv $(DATADIR)    
    
    devinstall:    install
        -mkdir $(INCDIR)
        -mkdir $(LIBDIR)
        copy *.lib $(LIBDIR)
        copy *.h $(INCDIR)
        copy libxtiff\*.h $(INCDIR)
        copy *.inc $(INCDIR)
        
    

  5. Save and close the text editor.

  6. Open up the Win64 Command Prompt if it is not on the screen.
  7. In the Command Prompt, type in the following.

    C:\> cd \Work\src\libgeotiff-1.4.0\
  8. Run the nmake build command in the Command Prompt.

    C:\> nmake /f makefile.vc
    The 64 bit libgeotiff files are created.