### Set Installation Directories Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Defines standard installation paths for binaries, libraries, headers, and CMake configuration files. ```cmake set(PACKAGE shp) # Set up install locations. set( CMAKE_INSTALL_BINDIR bin CACHE PATH "install location for user executables" ) set( CMAKE_INSTALL_LIBDIR lib CACHE PATH "install location for object code libraries" ) set( CMAKE_INSTALL_INCLUDEDIR include CACHE PATH "install location for C header files" ) set( CMAKE_INSTALL_CMAKEDIR share/${PROJECT_NAME} CACHE PATH "install location for read-only architecture-independent shp data" ) file (RELATIVE_PATH RELATIVE_LIBDIR ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR} ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}) message (STATUS "CMAKE_INSTALL_LIBDIR ${CMAKE_INSTALL_LIBDIR}") ``` -------------------------------- ### Install Executables and Headers Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Installs the built executables to the binary directory and the 'shapefil.h' header file to the include directory. It also installs the header to a subdirectory for compatibility. ```cmake install(TARGETS ${executables} EXPORT targets DESTINATION ${CMAKE_INSTALL_BINDIR}) # Install header install(FILES shapefil.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) # For compatibility with older installation install(FILES shapefil.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/shapelib) ``` -------------------------------- ### Initialize and Start Timer Source: https://github.com/mapwindow/mapwingis/blob/develop/src/OptimizeTestCode.txt Initializes and starts a timer for performance measurement. Includes user feedback via AfxMessageBox and prepares to log results to a file. Ensure 'Timer.h' is included and the output file stream is opened in append mode. ```cpp # include "Timer.h" AfxMessageBox("Starting timer"); ofstream out("C:\\profile.txt",ios::app); Init_Timer(); Start_Timer(); ``` -------------------------------- ### Create New SHP and SHX Files Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/manifest.html Example program for creating a new .shp and .shx file. Requires the shapefile C library. ```c #include #include #include #include "shapefil.h" int main( int argc, char **argv ) { SHPHandle hSHP; int i; int nShapeType; double adfMinBound[4]; double adfMaxBound[4]; // Create a new shapefile nShapeType = SHP_POINT; hSHP = SHPCreate( "test.shp", nShapeType ); if( hSHP == NULL ) { fprintf( stderr, "Failed to create test.shp!\n" ); return 1; } // Set the bounds of the shapefile adfMinBound[0] = 0.0; adfMinBound[1] = 0.0; adfMinBound[2] = 0.0; adfMinBound[3] = 0.0; adfMaxBound[0] = 100.0; adfMaxBound[1] = 100.0; adfMaxBound[2] = 0.0; adfMaxBound[3] = 0.0; SHPSetBounds( hSHP, adfMinBound, adfMaxBound ); // Add shapes to the shapefile for( i = 0; i < 10; i++ ) { int nNewShapeID; double x = (double)i; double y = (double)i * 2.0; // Create a new point shape nNewShapeID = SHPCreateObject( hSHP, -1, 0, NULL, NULL, 1, &x, &y, NULL, NULL, NULL, NULL ); if( nNewShapeID < 0 ) { fprintf( stderr, "Failed to create shape %d!\n", i ); SHPClose( hSHP ); return 1; } } // Close the shapefile SHPClose( hSHP ); printf( "Successfully created and wrote to test.shp\n" ); return 0; } ``` -------------------------------- ### Create New DBF File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/manifest.html Example program for creating a new .dbf file. Requires the shapefile C library. ```c #include #include #include #include "shapefil.h" int main( int argc, char **argv ) { DBFHandle hDBF; int i; int j; int nFields; char **apszFieldNames; DBFFieldType *panFieldType; int *pnFieldWidth; int *pnFieldDec; // Create a new DBF file hDBF = DBFCreate( "test.dbf" ); if( hDBF == NULL ) { fprintf( stderr, "Failed to create test.dbf!\n" ); return 1; } // Add fields to the DBF file DBFAddField( hDBF, "Name", FTString, 20, 0 ); DBFAddField( hDBF, "Value", FTInteger, 10, 0 ); DBFAddField( hDBF, "Float", FTDouble, 15, 5 ); // Get field information nFields = DBFGetFieldCount( hDBF ); apszFieldNames = (char **) malloc( sizeof(char *) * nFields ); panFieldType = (DBFFieldType *) malloc( sizeof(DBFFieldType) * nFields ); pnFieldWidth = (int *) malloc( sizeof(int) * nFields ); pnFieldDec = (int *) malloc( sizeof(int) * nFields ); for( i = 0; i < nFields; i++ ) { DBFGetFieldInfo( hDBF, i, apszFieldNames[i], &panFieldType[i], &pnFieldWidth[i], &pnFieldDec[i] ); } // Add a record to the DBF file DBFAddAutoIncrement( hDBF, "ID", 1, 1 ); DBFWriteRecord( hDBF, 100.0, "Test String", 123.456789 ); // Write some more records DBFWriteRecord( hDBF, 200.0, "Another String", 987.654321 ); DBFWriteRecord( hDBF, 300.0, "Final String", 111.222333 ); // Close the DBF file DBFClose( hDBF ); printf( "Successfully created and wrote to test.dbf\n" ); // Cleanup for( j = 0; j < nFields; j++ ) { free( apszFieldNames[j] ); } free( apszFieldNames ); free( panFieldType ); free( pnFieldWidth ); free( pnFieldDec ); return 0; } ``` -------------------------------- ### Calculate Project Root and Configure Files Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/cmake/CMakeLists.txt Determines the relative project root directory and generates configuration files for installation. ```cmake # Find root of install tree relative to CMAKE_INSTALL_CMAKEDIR file (RELATIVE_PATH PROJECT_ROOT_DIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_CMAKEDIR}" "${CMAKE_INSTALL_PREFIX}") # strip trailing slash get_filename_component (PROJECT_ROOT_DIR "${PROJECT_ROOT_DIR}/." PATH) configure_file (project-config.cmake.in project-config.cmake @ONLY) configure_file (project-config-version.cmake.in project-config-version.cmake @ONLY) install (FILES "${CMAKE_CURRENT_BINARY_DIR}/project-config.cmake" DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" RENAME "${PROJECT_NAME}-config.cmake") install (FILES "${CMAKE_CURRENT_BINARY_DIR}/project-config-version.cmake" DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" RENAME "${PROJECT_NAME}-config-version.cmake") ``` -------------------------------- ### Add Record to DBF File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/manifest.html Example program for adding a record to an existing .dbf file. Requires the shapefile C library. ```c #include #include #include #include "shapefil.h" int main( int argc, char **argv ) { DBFHandle hDBF; int i; int nRecord; // Open an existing DBF file hDBF = DBFOpen( "test.dbf", "rb+" ); if( hDBF == NULL ) { fprintf( stderr, "Failed to open test.dbf!\n" ); return 1; } // Add a new record nRecord = DBFWriteRecord( hDBF, 400.0, "New Record", 444.555666 ); if( nRecord < 0 ) { fprintf( stderr, "Failed to write record to test.dbf!\n" ); DBFClose( hDBF ); return 1; } printf( "Successfully added record %d to test.dbf\n", nRecord ); // Close the DBF file DBFClose( hDBF ); return 0; } ``` -------------------------------- ### Dump Contents of DBF File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/manifest.html Example program for displaying the contents of a .dbf file. Requires the shapefile C library. ```c #include #include #include #include "shapefil.h" int main( int argc, char **argv ) { DBFHandle hDBF; int i, j; int nFields; int nRecords; char szValue[ 512 ]; // Open the DBF file for reading hDBF = DBFOpen( "test.dbf", "rb" ); if( hDBF == NULL ) { fprintf( stderr, "Failed to open test.dbf!\n" ); return 1; } // Get the number of fields and records nFields = DBFGetFieldCount( hDBF ); nRecords = DBFGetRecordCount( hDBF ); printf( "DBF File: test.dbf\n" ); printf( "Number of Fields: %d\n", nFields ); printf( "Number of Records: %d\n\n", nRecords ); // Print header information (field names) for( i = 0; i < nFields; i++ ) { char szFieldName[ 12 ]; DBFFieldType fieldType; int fieldWidth; int fieldDec; DBFGetFieldInfo( hDBF, i, szFieldName, &fieldType, &fieldWidth, &fieldDec ); printf( "%-11s ", szFieldName ); } printf( "\n--------------------------------------------------\n" ); // Print each record for( i = 0; i < nRecords; i++ ) { for( j = 0; j < nFields; j++ ) { DBFGetValueAsString( hDBF, i, j, szValue ); printf( "%-11s ", szValue ); } printf( "\n" ); } // Close the DBF file DBFClose( hDBF ); return 0; } ``` -------------------------------- ### Define Library Build and Properties Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Defines source files, compiler definitions, target properties, and installation rules for the shapelib library. ```cmake if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE) # Set a default build type for single-configuration cmake generators # if no build type is set. set (CMAKE_BUILD_TYPE Release) endif () # Export build information to help other projects link installed # shapelib software. Only one of these signatures is required # for the export_shp name. install(EXPORT targets NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_CMAKEDIR} FILE "${PROJECT_NAME}-targets.cmake") # Initial boilerplate done, now build library and executables. set(lib_SRC shpopen.c dbfopen.c safileio.c shptree.c sbnsearch.c ) option(SHP_DROP_UNABLE_TO_OPEN_MSG "Drop \"unable to open\" error messages" ON) if(SHP_DROP_UNABLE_TO_OPEN_MSG) #define the SHP_DROP_UNABLE_TO_OPEN_MSG C macro for this source file. set_source_files_properties(shpopen.c PROPERTIES COMPILE_DEFINITIONS SHP_DROP_UNABLE_TO_OPEN_MSG ) endif(SHP_DROP_UNABLE_TO_OPEN_MSG) add_library(${PACKAGE} ${lib_SRC}) target_include_directories (${PACKAGE} INTERFACE $) if(WIN32 AND NOT CYGWIN) set_target_properties(${PACKAGE} PROPERTIES COMPILE_DEFINITIONS SHAPELIB_DLLEXPORT ) endif(WIN32 AND NOT CYGWIN) if(UNIX) find_library(M_LIB m) if(M_LIB) TARGET_LINK_LIBRARIES(${PACKAGE} -lm) endif() endif(UNIX) set(shp_SOVERSION 1) set(shp_VERSION ${PROJECT_VERSION}) set_target_properties(${PACKAGE} PROPERTIES SOVERSION ${shp_SOVERSION} VERSION ${shp_VERSION} INSTALL_NAME_DIR "${CMAKE_INSTALL_LIBDIR}" ) if(USE_RPATH) set_target_properties(${PACKAGE} PROPERTIES INSTALL_RPATH "${CMAKE_INSTALL_LIBDIR}" ) endif(USE_RPATH) install(TARGETS ${PACKAGE} EXPORT targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) ``` -------------------------------- ### Configure Install RPATH for Shared Libraries Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Sets the installation runtime path (RPATH) for shared libraries on non-Windows systems. It uses a relative path for relocatability, with a specific setting for macOS. ```cmake if (NOT MSVC) # Set the run time path for shared libraries for non-Windows machines. set (CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) if (CMAKE_SYSTEM_NAME STREQUAL "Darwin") # See also INSTALL_RPATH property on the tools. set (CMAKE_MACOSX_RPATH ON) else () # Use relative path so that package is relocatable set (CMAKE_INSTALL_RPATH "$ORIGIN/${RELATIVE_LIBDIR}") endif () endif () ``` -------------------------------- ### Prepare Sed Script for Test Data Substitution Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Writes a sed script to substitute placeholder paths with the actual path to the example data directory (EG_DATA). If EG_DATA is not set, a warning is issued, and an empty substitution is written. ```cmake if(BUILD_TEST) if(EG_DATA) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/script.sed "s?/u/www/projects/shapelib/eg_data?${EG_DATA}?\n") else(EG_DATA) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/script.sed "") message(STATUS "WARNING: EG_DATA:PATH not set to point to downloaded eg_data directory so the eg_data part of testing will be ignored.") endif(EG_DATA) endif(BUILD_TEST) ``` -------------------------------- ### Get Shapefile Information Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shp_api.html Retrieves metadata and bounds for the entire shapefile. ```c void SHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType, double * padfMinBound, double * padfMaxBound ); ``` -------------------------------- ### Define Executable Targets Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Lists the executables to be built and installed by the project. These are typically command-line utilities related to shapefile manipulation. ```cmake set( executables shpcreate shpadd shpdump shprewind dbfcreate dbfadd dbfdump shptreedump ) ``` -------------------------------- ### Add Shape to Existing Shape File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/manifest.html Example program for adding a shape to an existing shape file. Requires the shapefile C library. ```c #include #include #include #include "shapefil.h" int main( int argc, char **argv ) { SHPHandle hSHP; int i; int nShapeType; double adfMinBound[4]; double adfMaxBound[4]; // Open an existing shapefile for writing hSHP = SHPENvelope( "test.shp", "rb+" ); if( hSHP == NULL ) { fprintf( stderr, "Failed to open test.shp for writing!\n" ); return 1; } // Add a new shape nShapeType = SHP_POINT; for( i = 0; i < 5; i++ ) { int nNewShapeID; double x = (double)i + 10.0; double y = (double)i * 3.0; // Create a new point shape nNewShapeID = SHPCreateObject( hSHP, -1, 0, NULL, NULL, 1, &x, &y, NULL, NULL, NULL, NULL ); if( nNewShapeID < 0 ) { fprintf( stderr, "Failed to create shape %d!\n", i ); SHPClose( hSHP ); return 1; } } // Close the shapefile SHPClose( hSHP ); printf( "Successfully added shapes to test.shp\n" ); return 0; } ``` -------------------------------- ### Clip Polygons with Polygons Source: https://github.com/mapwindow/mapwingis/blob/develop/test/TestApplication/data/clipping.txt This example demonstrates clipping polygon shapefiles with other polygon shapefiles. Ensure the MW_SAMPLEDATA environment variable is set for correct path resolution. ```bash %MW_SAMPLEDATA%\MapWindow-Projects\UnitedStates\Shapefiles\states.shp %MW_SAMPLEDATA%\Shapefiles\LargePolygon.shp ``` -------------------------------- ### Extracting File Name from Path Source: https://github.com/mapwindow/mapwingis/blob/develop/MapWinGisTests-net6/clang-changes.txt Get the base name of a file from its full path. ```cpp const string baseName = GetFileNameFromPath(_shpfileName); ``` -------------------------------- ### Unit Test: Reading GDAL Version Source: https://github.com/mapwindow/mapwingis/blob/develop/MapWinGisTests-net6/clang-changes.txt Read and assert the GDAL version string. This test verifies that the GDAL version starts with 'GDAL 3.4'. ```csharp // Read: var gdalVersion = _gs.GdalVersion; _testOutputHelper.WriteLine(gdalVersion); gdalVersion.ShouldNotBeNullOrEmpty("GdalVersion is not set"); gdalVersion.StartsWith("GDAL 3.4").ShouldBeTrue(); // Change: // GdalVersion is read-only ``` -------------------------------- ### Get and Export Layer Data Source: https://context7.com/mapwindow/mapwingis/llms.txt Retrieves a specific layer by name from an OGR datasource, gets its data as a shapefile buffer in memory, and saves it to a local shapefile. This is useful for exporting subsets of data. ```csharp // Get a specific layer by name var parcelLayer = ds.GetLayerByName("parcels"); if (parcelLayer != null) { Console.WriteLine($"Parcel layer has {parcelLayer.FeatureCount} features"); // Get layer data as shapefile buffer (in-memory) var sf = parcelLayer.GetBuffer(); Console.WriteLine($"Loaded {sf.NumShapes} shapes into memory"); // Save to local shapefile sf.SaveAs(@"C:\output\parcels_export.shp"); sf.Close(); parcelLayer.Close(); } ``` -------------------------------- ### PostGIS Database Initialization Script Source: https://github.com/mapwindow/mapwingis/blob/develop/test/TestApplication/data/PostGISDatabaseSettings.txt Use this script to configure a PostgreSQL database for PostGIS support and set up required schemas and permissions. ```sql # This script will change the database created in 'PostGISCreateDatabase.txt' into a # PostGIS database, adds the data schema and sets some grants # First line is connection string # Following lines are queries to execute # Connection string to mapwingis database: PG:host=localhost dbname=mapwingis user=postgres # Create PostGIS extention: CREATE EXTENSION postgis SCHEMA public # Create data schema , which will hold all new tables: CREATE SCHEMA IF NOT EXISTS data AUTHORIZATION postgres # Set grants: GRANT ALL ON SCHEMA data TO mapwingis; # Set privileges: ALTER DEFAULT PRIVILEGES GRANT INSERT, SELECT, UPDATE, DELETE ON TABLES TO mapwingis; ALTER DEFAULT PRIVILEGES GRANT SELECT, UPDATE, USAGE ON SEQUENCES TO mapwingis; # Update search path: ALTER DATABASE "mapwingis" SET SEARCH_PATH=data,public; ``` -------------------------------- ### Configure CMake Project and Versioning Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Initializes the project, sets the required CMake version, and defines project version variables. ```cmake project(shapelib C) message(STATUS "CMake version = ${CMAKE_VERSION}") message(STATUS "CMAKE_SYSTEM_NAME = ${CMAKE_SYSTEM_NAME}") # Version 3.7 or above of cmake is currently required for all platforms. cmake_minimum_required(VERSION 3.7 FATAL_ERROR) set (PROJECT_VERSION_MAJOR 1) set (PROJECT_VERSION_MINOR 5) set (PROJECT_VERSION_PATCH 0) set (PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") ``` -------------------------------- ### DBFGetRecordCount() - Get Record Count Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Retrieves the number of records present in the DBF file. ```APIDOC ## DBFGetRecordCount() ### Description Returns the number of records that exist in the xBase file. ### Method DBFGetRecordCount ### Parameters #### Path Parameters - **hDBF** (DBFHandle) - Required - The access handle for the file, as returned by DBFOpen() or DBFCreate(). ### Returns - int - The number of records in the DBF file. ``` -------------------------------- ### Create new DBF file Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shapelib-tools.html Use dbfcreate to initialize an empty .dbf file. Specify field names, types (string '-s' or numeric '-n'), widths, and decimal places for numeric fields. ```bash $ dbfcreate testbase -s NAME 20, -n AREA 9 3, -n VALUE 9 2 ``` -------------------------------- ### DBFGetFieldCount() - Get Field Count Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Retrieves the number of fields defined in the DBF file. ```APIDOC ## DBFGetFieldCount() ### Description Returns the number of fields currently defined for the indicated xBase file. ### Method DBFGetFieldCount ### Parameters #### Path Parameters - **hDBF** (DBFHandle) - Required - The access handle for the file, as returned by DBFOpen() or DBFCreate(). ### Returns - int - The number of fields in the DBF file. ``` -------------------------------- ### Define Build Options and Platform Settings Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/CMakeLists.txt Configures shared library building, RPATH usage, and output directories for Windows DLLs. ```cmake # libraries are all shared by default. option(BUILD_SHARED_LIBS "Build shared libraries" ON) # Use rpath? if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") # No rpath on Darwin. Setting it will only cause trouble. else(CMAKE_SYSTEM_NAME STREQUAL "Darwin") option(USE_RPATH "Use -rpath when linking libraries, executables" ON) endif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") # In windows all created dlls are gathered in the dll directory # if you add this directory to your PATH all shared libraries are available if(BUILD_SHARED_LIBS AND WIN32 AND NOT CYGWIN) set(LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR}/dll) endif(BUILD_SHARED_LIBS AND WIN32 AND NOT CYGWIN) ``` -------------------------------- ### DBFGetFieldInfo() - Get Field Information Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Retrieves the type, name, width, and decimal precision of a field. ```APIDOC ## DBFGetFieldInfo() ### Description Returns the type of the requested field, and optionally its name, width, and decimal precision. The field type is one of the DBFFieldType enumerated values. ### Method DBFGetFieldInfo ### Parameters #### Path Parameters - **hDBF** (DBFHandle) - Required - The access handle for the file, as returned by DBFOpen() or DBFCreate(). - **iField** (int) - Required - The index of the field to query (0 to n-1). - **pszFieldName** (char *) - Optional - Buffer to store the field name (at least 12 characters). - **pnWidth** (int *) - Optional - Pointer to store the field width. - **pnDecimals** (int *) - Optional - Pointer to store the number of decimal places. ### Returns - DBFFieldType - The type of the field (FTString, FTInteger, FTDouble, FTLogical, FTInvalid). ``` -------------------------------- ### Create new Shapefile Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shapelib-tools.html Use shpcreate to initialize a new shapefile. Specify the base filename and the shape type (point, arc, polygon, multipoint). ```bash $ shpcreate testpolygon polygon ``` -------------------------------- ### DBFGetFieldIndex() - Get Field Index by Name Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Finds the index of a field given its name. The search is case-insensitive. ```APIDOC ## DBFGetFieldIndex() ### Description Returns the index of the field matching the provided name. The comparison is case-insensitive, but lengths must match exactly. ### Method DBFGetFieldIndex ### Parameters #### Path Parameters - **hDBF** (DBFHandle) - Required - The access handle for the file, as returned by DBFOpen() or DBFCreate(). - **pszFieldName** (const char *) - Required - The name of the field to search for. ### Returns - int - The index of the field, or -1 if the field is not found. ``` -------------------------------- ### Configure labels and thematic visualization Source: https://context7.com/mapwindow/mapwingis/llms.txt Shows how to generate labels, apply thematic categories, and configure drawing options for a Shapefile. ```csharp using MapWinGIS; var sf = new Shapefile(); sf.Open(@"C:\data\cities.shp"); // Generate labels from field values int nameFieldIndex = sf.FieldIndexByName["CityName"]; long labelCount = sf.GenerateLabels(nameFieldIndex, tkLabelPositioning.lpCenter, false, -1, -1); Console.WriteLine($"Generated {labelCount} labels"); // Configure label appearance var labels = sf.Labels; labels.FontName = "Arial"; labels.FontSize = 10; labels.FontColor = 0x000000; // Black labels.FontBold = true; labels.FrameVisible = true; labels.FrameType = tkLabelFrameType.lfRectangle; labels.FrameBackColor = 0xFFFFFF; labels.HaloVisible = true; labels.HaloColor = 0xFFFFFF; labels.HaloSize = 2; // Configure default drawing options var options = sf.DefaultDrawingOptions; options.FillColor = 0xFF0000; // Red fill options.FillTransparency = 128; // 50% transparent options.LineColor = 0x000000; // Black outline options.LineWidth = 2; options.PointSize = 10; options.PointShape = tkPointShapeType.ptShapeCircle; // Create categories for thematic mapping int populationField = sf.FieldIndexByName["Population"]; sf.Categories.Generate(populationField, tkClassificationType.ctNaturalBreaks, 5); sf.Categories.ApplyExpressions(); // Apply color scheme to categories var colorScheme = new ColorScheme(); colorScheme.SetColors2(tkMapColor.Blue, tkMapColor.Red); sf.Categories.ApplyColorScheme(tkColorSchemeType.ctSchemeGraduated, colorScheme); // Access individual categories for (int i = 0; i < sf.Categories.Count; i++) { var category = sf.Categories.Item[i]; Console.WriteLine($"Category {i}: {category.Name}, Expression: {category.Expression}"); } // Set visibility expression (show only features matching condition) sf.VisibilityExpression = "[Population] > 10000"; // Selection styling sf.SelectionColor = 0x00FF00; // Green sf.SelectionTransparency = 200; sf.SelectionAppearance = tkSelectionAppearance.saDrawingOptions; sf.Close(); ``` -------------------------------- ### dbfcreate Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shapelib-tools.html Creates a new and empty .dbf file with specified fields. ```APIDOC ## dbfcreate ### Description Creates a new and empty .dbf file. ### Usage dbfcreate xbase_file [[-s field_name width],[-n field_name width decimals]]... ### Parameters - **xbase_file** (string) - Required - The name of the xBase file to be created (extension not required). - **-s field_name width** (string) - Optional - Creates a string field with name field_name and size width. - **-n field_name width decimals** (string) - Optional - Creates a numeric field with name field_name, width of width and with decimals places sized by decimals. ``` -------------------------------- ### Configure MSVC and Cross-Compilation Variables Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/cmake/CMakeLists.txt Sets up MSVC toolset versioning and cross-compilation status for use in configuration files. ```cmake if (MSVC) # For checking the compatibility of MSVC_TOOLSET_VERSION; see # https://docs.microsoft.com/en-us/cpp/porting/overview-of-potential-upgrade-issues-visual-cpp # Assume major version number is obtained by dropping the last decimal # digit. math (EXPR MSVC_TOOLSET_MAJOR "${MSVC_TOOLSET_VERSION}/10") else () set (MSVC_TOOLSET_VERSION 0) set (MSVC_TOOLSET_MAJOR 0) endif () if (CMAKE_CROSSCOMPILING) # Ensure that all "true" (resp. "false") settings are represented by # the same string. set (CMAKE_CROSSCOMPILING_STR "ON") else () set (CMAKE_CROSSCOMPILING_STR "OFF") endif () ``` -------------------------------- ### DBFCreate() - Create DBF File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Creates a new DBF file. The file is initially empty with no fields or records. ```APIDOC ## DBFCreate() ### Description Creates a new xBase format file with the given name. The returned handle can be used with other DBF functions. The newly created file will have no fields and no records initially. ### Method DBFCreate ### Parameters #### Path Parameters - **pszDBFFile** (const char *) - Required - The name of the xBase (.dbf) file to create. ### Returns - DBFHandle - A handle for accessing the newly created DBF file. ``` -------------------------------- ### shpcreate Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shapelib-tools.html Creates a new and empty shapefile. ```APIDOC ## shpcreate ### Description Creates a new and empty shapefile. ### Usage shpcreate shp_file [point|arc|polygon|multipoint] ### Parameters - **shp_file** (string) - Required - The name of the shapefile to be created. - **type** (enum) - Required - The type of shapefile: point, arc, polygon, or multipoint. ``` -------------------------------- ### Enable QTree and Caching for Performance Source: https://context7.com/mapwindow/mapwingis/llms.txt Enables the QTree in-memory spatial index, caches extents for faster access, and sets the FastMode for improved performance with numerous shapes. ```csharp using MapWinGIS; var sf = new Shapefile(); sf.Open(@"C:\data\large_dataset.shp"); // Enable QTree (in-memory spatial index) sf.UseQTree = true; // Cache extents for faster access sf.CacheExtents = true; // Fast mode for better performance with many shapes sf.FastMode = true; sf.Close(); ``` -------------------------------- ### Get Related Shapes Using Spatial Relationship Source: https://context7.com/mapwindow/mapwingis/llms.txt Retrieves shapes from a Shapefile that intersect with a given test shape. The result is an array of shape indices. ```csharp using MapWinGIS; var sf = new Shapefile(); sf.Open(@"C:\data\large_dataset.shp"); var testShape = new Shape(); testShape.ImportFromWKT("POLYGON ((0 0, 100 0, 100 100, 0 100, 0 0))"); object resultArray = null; if (sf.GetRelatedShapes2(testShape, tkSpatialRelation.srIntersects, ref resultArray)) { int[] relatedIndices = resultArray as int[]; Console.WriteLine($"Found {relatedIndices.Length} intersecting shapes"); } sf.Close(); ``` -------------------------------- ### SHPOpen Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/shp_api.html Opens a .shp/.shx file pair for reading or writing. ```APIDOC ## SHPOpen ### Description Establishes access to the .shp and .shx files. The returned SHPHandle is used for subsequent operations. ### Method Function Call ### Parameters #### Path Parameters - **pszShapeFile** (const char*) - Required - The path and basename of the shapefile pair. - **pszAccess** (const char*) - Required - Access mode, typically "rb" (read-only) or "rb+" (read/write). ### Response - **SHPHandle** - A handle to the opened shapefile. ``` -------------------------------- ### Open, Create, and Edit Shapefiles with MapWinGIS Source: https://context7.com/mapwindow/mapwingis/llms.txt Demonstrates opening an existing shapefile, creating a new one programmatically, adding fields, inserting shapes with attributes, and saving changes. Includes error handling for file operations. ```csharp using MapWinGIS; // Open an existing shapefile var sf = new Shapefile(); if (!sf.Open(@"C:\data\parcels.shp")) { Console.WriteLine("Error: " + sf.ErrorMsg[sf.LastErrorCode]); return; } Console.WriteLine($"Shapefile has {sf.NumShapes} shapes and {sf.NumFields} fields"); // Create a new shapefile programmatically var newSf = new Shapefile(); if (!newSf.CreateNewWithShapeID(@"C:\output\new_points.shp", ShpfileType.SHP_POINT)) { Console.WriteLine("Error creating shapefile: " + newSf.ErrorMsg[newSf.LastErrorCode]); return; } // Add fields to the shapefile int nameFieldIdx = newSf.EditAddField("Name", FieldType.STRING_FIELD, 0, 50); int valueFieldIdx = newSf.EditAddField("Value", FieldType.DOUBLE_FIELD, 2, 10); int dateFieldIdx = newSf.EditAddField("Date", FieldType.DATE_FIELD, 0, 12); int activeFieldIdx = newSf.EditAddField("Active", FieldType.BOOLEAN_FIELD, 0, 1); // Create and add a point shape var shp = new Shape(); shp.Create(ShpfileType.SHP_POINT); var pnt = new Point { x = -122.4194, y = 37.7749 }; int pointIndex = 0; shp.InsertPoint(pnt, ref pointIndex); int shapeIndex = newSf.EditAddShape(shp); // Set attribute values newSf.EditCellValue(nameFieldIdx, shapeIndex, "San Francisco"); newSf.EditCellValue(valueFieldIdx, shapeIndex, 123.45); newSf.EditCellValue(dateFieldIdx, shapeIndex, DateTime.Now); newSf.EditCellValue(activeFieldIdx, shapeIndex, true); // Save the shapefile if (!newSf.Save()) { Console.WriteLine("Error saving: " + newSf.ErrorMsg[newSf.LastErrorCode]); } // Read attribute values for (int i = 0; i < sf.NumShapes; i++) { string name = sf.CellValue[sf.FieldIndexByName["Name"], i] as string; double? value = sf.CellValue[sf.FieldIndexByName["Value"], i] as double?; Console.WriteLine($"Shape {i}: {name} = {value}"); } // Query using SQL-like expression object result = null; string errorString = null; if (sf.Table.Query("[Population] > 100000 AND [State] = \"California\"", ref result, ref errorString)) { int[] matchingIndices = result as int[]; Console.WriteLine($"Found {matchingIndices.Length} matching records"); } // Select shapes by extent var extent = new Extents(); extent.SetBounds(-123, 37, 0, -122, 38, 0); object selectedShapes = null; if (sf.SelectShapes(extent, 0.0, SelectMode.INTERSECTION, ref selectedShapes)) { int[] indices = selectedShapes as int[]; foreach (int idx in indices) { sf.ShapeSelected[idx] = true; } } sf.Close(); newSf.Close(); ``` -------------------------------- ### Create and Fill New GeoTIFF Grid Source: https://context7.com/mapwindow/mapwingis/llms.txt Creates a new GeoTIFF grid file with specified dimensions and cell size, then fills it with calculated values. Requires write permissions for the output directory. ```csharp // Create a new grid var newGrid = new Grid(); var newHeader = new GridHeader(); newHeader.NumberCols = 100; newHeader.NumberRows = 100; newHeader.dX = 10; newHeader.dY = 10; newHeader.XllCenter = 0; newHeader.YllCenter = 0; newHeader.NodataValue = -9999; if (newGrid.CreateNew(@"C:\output\new_grid.tif", newHeader, GridDataType.FloatDataType, -9999, true, GridFileType.GeoTiff)) { // Fill with values for (int r = 0; r < 100; r++) { for (int c = 0; c < 100; c++) { newGrid.Value[c, r] = Math.Sqrt(c * c + r * r); } } newGrid.Save(); } ``` -------------------------------- ### Connect to PostGIS Datasource Source: https://context7.com/mapwindow/mapwingis/llms.txt Establishes a connection to a PostGIS spatial database using a connection string. Ensure the database server is accessible and credentials are correct. ```csharp using MapWinGIS; // Connect to PostGIS database var ds = new OgrDatasource(); string connectionString = "PG:host=localhost dbname=gis_db user=postgres password=secret"; if (!ds.Open(connectionString)) { Console.WriteLine("Connection failed: " + ds.GdalLastErrorMsg); return; } ``` -------------------------------- ### Stop Timer and Print Results Source: https://github.com/mapwindow/mapwingis/blob/develop/src/OptimizeTestCode.txt Stops the timer, prints the elapsed time for a specific operation (e.g., 'fread : Disk') to an output stream, and closes the file. Provides user feedback upon completion. Ensure the output stream is valid and the timer has been started. ```cpp Stop_Timer(); Print_Timer(out,"fread : Disk"); AfxMessageBox("Stopping timer"); out.close(); ``` -------------------------------- ### Configure and Manipulate AxMap Control Source: https://context7.com/mapwindow/mapwingis/llms.txt Demonstrates initializing the map, adding vector and raster layers, performing zoom operations, managing cursor modes, and handling batch updates. ```csharp using AxMapWinGIS; using MapWinGIS; // Create and configure the map control var axMap = new AxMap(); axMap.TileProvider = tkTileProvider.OpenStreetMap; axMap.ZoomBehavior = tkZoomBehavior.zbDefault; axMap.KnownExtents = tkKnownExtents.keWorld; // Add a shapefile layer int layerHandle = axMap.AddLayerFromFilename(@"C:\data\states.shp", tkFileOpenStrategy.fosVectorLayer, true); if (layerHandle == -1) { Console.WriteLine("Error: " + axMap.get_ErrorMsg(axMap.LastErrorCode)); } // Add an image layer var img = new Image(); if (img.Open(@"C:\data\aerial.tif")) { int imgHandle = axMap.AddLayer(img, true); axMap.ZoomToLayer(imgHandle); } // Zoom operations axMap.ZoomToMaxExtents(); axMap.ZoomToLayer(layerHandle); axMap.ZoomIn(0.3); // Zoom in 30% // Set cursor mode for user interaction axMap.CursorMode = tkCursorMode.cmPan; // Pan mode axMap.CursorMode = tkCursorMode.cmZoomIn; // Zoom in on click axMap.CursorMode = tkCursorMode.cmSelection; // Select features // Lock window for batch operations (improves performance) axMap.LockWindow(tkLockMode.lmLock); try { // Add multiple layers... } finally { axMap.LockWindow(tkLockMode.lmUnlock); } // Save current view as image snapshot var snapshot = axMap.SnapShot(axMap.Extents); snapshot.Save(@"C:\output\map_snapshot.png", false, ImageType.PNG_FILE); // Save and load layer options/styling axMap.SaveLayerOptions(layerHandle, "", true, ""); string description = ""; axMap.LoadLayerOptions(layerHandle, "", ref description); ``` -------------------------------- ### Open and Read Grid File Properties Source: https://context7.com/mapwindow/mapwingis/llms.txt Opens an ASCII Grid file and retrieves its properties like dimensions, cell size, and data range. Ensure the file path is correct. ```csharp using MapWinGIS; // Open a grid file var grid = new Grid(); if (!grid.Open(@"C:\data\elevation.asc", GridDataType.UnknownDataType, true)) { Console.WriteLine("Error: " + grid.ErrorMsg[grid.LastErrorCode]); return; } // Get grid properties var header = grid.Header; Console.WriteLine($"Grid size: {header.NumberCols} x {header.NumberRows}"); Console.WriteLine($"Cell size: {header.dX} x {header.dY}"); Console.WriteLine($"NoData value: {header.NodataValue}"); Console.WriteLine($"Data type: {grid.DataType}"); Console.WriteLine($"Min value: {grid.Minimum}, Max value: {grid.Maximum}"); ``` -------------------------------- ### DBFOpen() - Open DBF File Source: https://github.com/mapwindow/mapwingis/blob/develop/support/ShapeLib/web/dbf_api.html Opens an existing DBF file for access. Supports read-only or read/write binary modes. ```APIDOC ## DBFOpen() ### Description Opens an existing xBase format table file for access. Returns a DBFHandle that is used for other access functions. DBFClose() should be called to release resources. ### Method DBFOpen ### Parameters #### Path Parameters - **pszDBFFile** (const char *) - Required - The name of the xBase (.dbf) file to access. - **pszAccess** (const char *) - Required - The fopen() style access string. Only "rb" (read-only binary) and "rb+" (read/write binary) are supported. ### Returns - DBFHandle - A handle for accessing the DBF file. ```