godal

package module
v0.0.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2024 License: Apache-2.0 Imports: 12 Imported by: 7

README

Golang bindings for GDAL

Go Reference License Build Status Coverage Status Go Report Card

Goals

Godal aims at providing an idiomatic go wrapper around the GDAL library:

  • Function calls return a result and an error. The result will be valid if no error was returned. The error message will contain the root cause of why the error happened.
  • Calls between go and native libraries incur some overhead. As such godal does not strictly expose GDAL's API, but groups often-used calls in a single cgo function to reduce this overhead. For example, C code like
    hDS = GDALOpen(filename, GA_Readonly)
    if (hDS == NULL) exit(1);
    int sx = GDALGetRasterXSize(hDS);
    int sy = GDALGetRasterYSize(hDS);
    int nBands = GDALGetRasterCount(hDS);
    printf("dataset size: %dx%dx%d\n",sx,sy,nBands);
    for (int i=1; i<=nBands; i++) {
        hBand = GDALGetRasterBand(hDS,i);
        int ovrCount = GDALGetOverviewCount(hBand)
        for(int o=0; o<=ovrCount; o++) {
            GDALRasterBandH oBand = GDALGetOverview(hBand,o);
            int osx = GDALGetRasterBandXSize(oBand);
            int osy = GDALGetRasterBandYSize(oBand);
            printf("overview %d size: %dx%d\n",o,osx,osy);
        }
    }

will be written as

    hDS,err := godal.Open(filename)
    if err!=nil {
        panic(err)
    }
    structure := hDS.Structure()
    fmt.Printf("dataset size: %dx%dx%d\n", structure.SizeX,structure.SizeY,structure.NBands)
    for _,band := range hDS.Bands() {
        for o,ovr := range band.Overviews() {
            bstruct := ovr.Structure()
            fmt.Printf("overview %d size: %dx%d\n",o,bstruct.SizeX,bstruct.SizeY)
        }
    }
  • Unfrequently used or non-default parameters are passed as options:
    ds,err := godal.Open(filename) //read-only
    ds,err := godal.Open(filename, Update()) //read-write
  • Godal exposes a VSI handler that can easily allow you to expose an io.ReaderAt as a filename that can be opened by GDAL. A handler for opening gs:// google cloud storage URIs is provided through https://github.com/airbusgeo/osio
Documentation

GoReference contains the API reference and example code to get you started. The *_test.go files can also be used as reference.

Status

Godal is not feature complete. The raster side is nearing completion and should remain stable. The vector and spatial-referencing sides are far from complete, meaning that the API might evolve in backwards incompatible ways until essential functionality is covered.

Contributing

Contributions are welcome. Please read the contribution guidelines before submitting fixes or enhancements.

Installation

Godal requires a GDAL version greater than 3.0. Make sure the GDAL headers are installed on the system used for compiling go+godal code. If using a GDAL installation in a non standard location, you can set your PKG_CONFIG_PATH environment variable, e.g. export PKG_CONFIG_PATH=/opt/include/pkgconfig.

Licensing

Godal is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Documentation

Overview

Example (RasterTutorial)

This is the godal port of the official gdal raster tutorial located at https://gdal.org/tutorials/raster_api_tut.html .

package main

import (
	"fmt"

	"github.com/airbusgeo/godal"
)

func main() {
	/*
		GDALDatasetH  hDataset;
		GDALAllRegister();
		hDataset = GDALOpen( pszFilename, GA_ReadOnly );
		if( hDataset == NULL )
		{
			...;
		}
	*/
	godal.RegisterAll()
	hDataset, err := godal.Open("testdata/test.tif")
	if err != nil {
		panic(err)
	}

	/*
		hDriver = GDALGetDatasetDriver( hDataset );
		printf( "Driver: %s/%s\n",
			GDALGetDriverShortName( hDriver ),
			GDALGetDriverLongName( hDriver ) );
	*/
	//not implemented

	/*
		printf( "Size is %dx%dx%d\n",
			GDALGetRasterXSize( hDataset ),
			GDALGetRasterYSize( hDataset ),
			GDALGetRasterCount( hDataset ) );
	*/
	structure := hDataset.Structure()
	fmt.Printf("Size is %dx%dx%d\n", structure.SizeX, structure.SizeY, structure.NBands)

	/*
		if( GDALGetProjectionRef( hDataset ) != NULL )
			printf( "Projection is '%s'\n", GDALGetProjectionRef( hDataset ) );
	*/
	if pj := hDataset.Projection(); pj != "" {
		fmt.Printf("Projection is '%s...'\n", pj[0:20])
	}

	/*
		if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
		{
			printf( "Origin = (%.6f,%.6f)\n",
				adfGeoTransform[0], adfGeoTransform[3] );
			printf( "Pixel Size = (%.6f,%.6f)\n",
				adfGeoTransform[1], adfGeoTransform[5] );
		}
	*/
	if gt, err := hDataset.GeoTransform(); err == nil {
		fmt.Printf("Origin = (%.6f,%.6f)\n", gt[0], gt[3])
		fmt.Printf("Pixel Size = (%.6f,%.6f)\n", gt[1], gt[5])
	}

	/*
		GDALRasterBandH hBand;
		int             nBlockXSize, nBlockYSize;
		int             bGotMin, bGotMax;
		double          adfMinMax[2];
		hBand = GDALGetRasterBand( hDataset, 1 );
		GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize );
		printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
				nBlockXSize, nBlockYSize,
				GDALGetDataTypeName(GDALGetRasterDataType(hBand)),
				GDALGetColorInterpretationName(
					GDALGetRasterColorInterpretation(hBand)) );
	*/
	band := hDataset.Bands()[0] //Note that in godal, bands are indexed starting from 0, not 1
	bandStructure := band.Structure()
	fmt.Printf("Block=%dx%d Type=%s, ColorInterp=%s\n",
		bandStructure.BlockSizeX, bandStructure.BlockSizeY,
		bandStructure.DataType,
		band.ColorInterp().Name())

	/*
		adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin );
		adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax );
		if( ! (bGotMin && bGotMax) )
			GDALComputeRasterMinMax( hBand, TRUE, adfMinMax );
		printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] );
	*/
	//not implemented

	/*
		if( GDALGetOverviewCount(hBand) > 0 )
			printf( "Band has %d overviews.\n", GDALGetOverviewCount(hBand));
	*/
	if overviews := band.Overviews(); len(overviews) > 0 {
		fmt.Printf("Band has %d overviews.\n", len(overviews))
	}

	/*
		if( GDALGetRasterColorTable( hBand ) != NULL )
			printf( "Band has a color table with %d entries.\n",
					GDALGetColorEntryCount(
						GDALGetRasterColorTable( hBand ) ) );
	*/
	if ct := band.ColorTable(); len(ct.Entries) > 0 {
		fmt.Printf("Band has a color table with %d entries.\n", len(ct.Entries))
	}

	/*
		float *pafScanline;
		int   nXSize = GDALGetRasterBandXSize( hBand );
		pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize);
		GDALRasterIO( hBand, GF_Read, 0, 0, nXSize, 1,
			pafScanline, nXSize, 1, GDT_Float32,
			0, 0 );
	*/

	pafScanline := make([]float32, structure.SizeX)
	err = band.Read(0, 0, pafScanline, bandStructure.SizeX, 1)
	if err != nil {
		panic(err)
	}

	err = hDataset.Close()
	// we don't really need to check for errors here as we have a read-only dataset.
	if err != nil {
		panic(err)
	}

	/*
		const char *pszFormat = "GTiff";
		GDALDriverH hDriver = GDALGetDriverByName( pszFormat );
		char **papszMetadata;
		if( hDriver == NULL )
		    exit( 1 );
		papszMetadata = GDALGetMetadata( hDriver, NULL );
		if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) )
		    printf( "Driver %s supports Create() method.\n", pszFormat );
		if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATECOPY, FALSE ) )
		    printf( "Driver %s supports CreateCopy() method.\n", pszFormat );
	*/

	hDriver, ok := godal.RasterDriver("Gtiff")
	if !ok {
		panic("Gtiff not found")
	}
	md := hDriver.Metadatas()
	if md["DCAP_CREATE"] == "YES" {
		fmt.Printf("Driver GTiff supports Create() method.\n")
	}
	if md["DCAP_CREATECOPY"] == "YES" {
		fmt.Printf("Driver Gtiff supports CreateCopy() method.\n")
	}

	/*	GDALDataset *poSrcDS = (GDALDataset *) GDALOpen( pszSrcFilename, GA_ReadOnly );
		GDALDataset *poDstDS;
		char **papszOptions = NULL;
		papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" );
		papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "PACKBITS" );
		poDstDS = poDriver->CreateCopy( pszDstFilename, poSrcDS, FALSE,
										papszOptions, GDALTermProgress, NULL );
		if( poDstDS != NULL )
			GDALClose( (GDALDatasetH) poDstDS );
		CSLDestroy( papszOptions );

		GDALClose( (GDALDatasetH) poSrcDS );
	*/

	//Left out: dealing with error handling
	poSrcDS, _ := godal.Open("testdata/test.tif")
	pszDstFilename := "/vsimem/tempfile.tif"
	defer godal.VSIUnlink(pszDstFilename)
	//godal doesn't expose createCopy directly, but the same result can be obtained with Translate
	poDstDS, _ := poSrcDS.Translate(pszDstFilename, nil, godal.CreationOption("TILED=YES", "COMPRESS=PACKBITS"), godal.GTiff)
	poDstDS.Close()
	poSrcDS.Close()

	/*
		GDALDataset *poDstDS;
		char **papszOptions = NULL;
		poDstDS = poDriver->Create( pszDstFilename, 512, 512, 1, GDT_Byte,
									papszOptions );
		double adfGeoTransform[6] = { 444720, 30, 0, 3751320, 0, -30 };
		OGRSpatialReference oSRS;
		char *pszSRS_WKT = NULL;
		GDALRasterBand *poBand;
		GByte abyRaster[512*512];
		poDstDS->SetGeoTransform( adfGeoTransform );
		oSRS.SetUTM( 11, TRUE );
		oSRS.SetWellKnownGeogCS( "NAD27" );
		oSRS.exportToWkt( &pszSRS_WKT );
		poDstDS->SetProjection( pszSRS_WKT );
		CPLFree( pszSRS_WKT );
		poBand = poDstDS->GetRasterBand(1);
		poBand->RasterIO( GF_Write, 0, 0, 512, 512,
						abyRaster, 512, 512, GDT_Byte, 0, 0 );
		GDALClose( (GDALDatasetH) poDstDS );
	*/

	poDstDS, _ = godal.Create(godal.GTiff, pszDstFilename, 1, godal.Byte, 512, 512)
	defer poDstDS.Close() //Close can be defered / called more than once (second+ calls are no-ops)

	poDstDS.SetGeoTransform([6]float64{444720, 30, 0, 3751320, 0, -30})

	//SetUTM and SetWellKnownGeogCS not implemented. godal allows populating
	// a SpatialRef from a WKT or PROJ4 string, or an epsg code
	sr, _ := godal.NewSpatialRefFromEPSG(4326)
	defer sr.Close()
	poDstDS.SetSpatialRef(sr)

	abyRaster := make([]byte, 512*512)
	// ... now populate with data
	poDstDS.Bands()[0].Write(0, 0, abyRaster, 512, 512)
	poDstDS.Close()

}
Output:

Size is 10x10x3
Projection is 'GEOGCS["WGS 84",DATU...'
Origin = (45.000000,35.000000)
Pixel Size = (1.000000,-1.000000)
Block=256x256 Type=Byte, ColorInterp=Red
Driver GTiff supports Create() method.
Driver Gtiff supports CreateCopy() method.
Example (VectorTutorial)

This is the godal port of the official gdal vector tutorial located at https://gdal.org/tutorials/vector_api_tut.html.

Vector support in godal is incomplete and should be considered a work in progress. The API may change in backwards incompatible ways.

package main

import (
	"bufio"
	"fmt"
	"strings"

	"github.com/airbusgeo/godal"
)

func main() {
	/*
		#include "gdal.h"

		int main() {
			GDALAllRegister();
	*/
	godal.RegisterAll()
	/*
		GDALDatasetH hDS;
		OGRLayerH hLayer;
		OGRFeatureH hFeature;
		OGRFeatureDefnH hFDefn;

		hDS = GDALOpenEx( "point.shp", GDAL_OF_VECTOR, NULL, NULL, NULL );
		if( hDS == NULL ) {
			printf( "Open failed.\n" );
			exit( 1 );
		}
	*/

	//by using the VectorOnly() option Open() will return an error if given
	//a raster dataset
	hDS, err := godal.Open("testdata/test.geojson", godal.VectorOnly())
	if err != nil {
		panic(err)
	}
	/*
		hLayer = GDALDatasetGetLayerByName( hDS, "point" );
		hFDefn = OGR_L_GetLayerDefn(hLayer);
		OGR_L_ResetReading(hLayer);
		while( (hFeature = OGR_L_GetNextFeature(hLayer)) != NULL ) {
	*/
	layers := hDS.Layers()
	for _, layer := range layers {
		layer.ResetReading()
		for {
			/*
				int iField;
				OGRGeometryH hGeometry;
				for( iField = 0; iField < OGR_FD_GetFieldCount(hFDefn); iField++ ) {
					OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn, iField );
					switch( OGR_Fld_GetType(hFieldDefn) ) {
					case OFTInteger:
						printf( "%d,", OGR_F_GetFieldAsInteger( hFeature, iField ) );
						break;
					case OFTInteger64:
						printf( CPL_FRMT_GIB ",", OGR_F_GetFieldAsInteger64( hFeature, iField ) );
						break;
					case OFTReal:
						printf( "%.3f,", OGR_F_GetFieldAsDouble( hFeature, iField) );
						break;
					case OFTString:
						printf( "%s,", OGR_F_GetFieldAsString( hFeature, iField) );
						break;
					default:
						printf( "%s,", OGR_F_GetFieldAsString( hFeature, iField) );
						break;
					}
				}
			*/
			feat := layer.NextFeature()
			if feat == nil {
				break
			}
			fields := feat.Fields()
			fmt.Printf("%v\n", fields)

			/*
				hGeometry = OGR_F_GetGeometryRef(hFeature);
				if( hGeometry != NULL
					&& wkbFlatten(OGR_G_GetGeometryType(hGeometry)) == wkbPoint )
					printf( "%.3f,%3.f\n", OGR_G_GetX(hGeometry, 0), OGR_G_GetY(hGeometry, 0) );
				else
					printf( "no point geometry\n" );
			*/
			geom := feat.Geometry()
			wkt, _ := geom.WKT()
			fmt.Printf("geom: %s\n", wkt)

			/*
					OGR_F_Destroy( hFeature );
				}
			*/
			//geom.Close is a no-op in this case. We call it nonetheless, as it is strongly recommended
			//to call Close on an object that implements the method to avoid potential memory leaks.
			geom.Close()

			//calling feat.Close is mandatory to prevent memory leaks
			feat.Close()
		}
	}
	/*
			GDALClose( hDS );
		}
	*/
	hDS.Close()

	/*
		const char *pszDriverName = "ESRI Shapefile";
		GDALDriverH hDriver;
		GDALDatasetH hDS;
		OGRLayerH hLayer;
		OGRFieldDefnH hFieldDefn;
		double x, y;
		char szName[33];

		GDALAllRegister();

		hDriver = GDALGetDriverByName( pszDriverName );
		if( hDriver == NULL )
		{
			printf( "%s driver not available.\n", pszDriverName );
			exit( 1 );
		}

		hDS = GDALCreate( hDriver, "point_out.shp", 0, 0, 0, GDT_Unknown, NULL );
		if( hDS == NULL )
		{
			printf( "Creation of output file failed.\n" );
			exit( 1 );
		}
	*/
	hDS, err = godal.CreateVector(godal.GeoJSON, "/vsimem/point_out.geojson")
	if err != nil {
		panic(err)
	}
	defer godal.VSIUnlink("/vsimem/point_out.geojson")

	/*
	   hLayer = GDALDatasetCreateLayer( hDS, "point_out", NULL, wkbPoint, NULL );
	   if( hLayer == NULL )
	   {
	       printf( "Layer creation failed.\n" );
	       exit( 1 );
	   }

	   hFieldDefn = OGR_Fld_Create( "Name", OFTString );

	   OGR_Fld_SetWidth( hFieldDefn, 32);

	   if( OGR_L_CreateField( hLayer, hFieldDefn, TRUE ) != OGRERR_NONE )
	   {
	       printf( "Creating Name field failed.\n" );
	       exit( 1 );
	   }

	   OGR_Fld_Destroy(hFieldDefn);
	*/

	layer, err := hDS.CreateLayer("point_out", nil, godal.GTPoint,
		godal.NewFieldDefinition("Name", godal.FTString))
	if err != nil {
		panic(fmt.Errorf("Layer creation failed: %w", err))
	}

	/*
	   while( !feof(stdin)
	       && fscanf( stdin, "%lf,%lf,%32s", &x, &y, szName ) == 3 )
	   {
	       OGRFeatureH hFeature;
	       OGRGeometryH hPt;

	       hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
	       OGR_F_SetFieldString( hFeature, OGR_F_GetFieldIndex(hFeature, "Name"), szName );

	       hPt = OGR_G_CreateGeometry(wkbPoint);
	       OGR_G_SetPoint_2D(hPt, 0, x, y);

	       OGR_F_SetGeometry( hFeature, hPt );
	       OGR_G_DestroyGeometry(hPt);

	       if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE )
	       {
	       printf( "Failed to create feature in shapefile.\n" );
	       exit( 1 );
	       }

	       OGR_F_Destroy( hFeature );
	   }
	*/
	//scanner := bufio.NewScanner(os.Stdin)
	scanner := bufio.NewScanner(strings.NewReader(`POINT (1 1)`))
	for scanner.Scan() {
		//fmt.Println(scanner.Text())
		geom, _ := godal.NewGeometryFromWKT(scanner.Text(), nil)
		feat, err := layer.NewFeature(geom)
		//godal does not yet support setting fields on newly created features
		if err != nil {
			panic(fmt.Errorf("Failed to create feature in shapefile: %w", err))
		}
		gj, _ := feat.Geometry().GeoJSON()
		fmt.Printf("created geometry %s\n", gj)

		feat.Close()
	}
	/*

	   GDALClose( hDS );
	*/
	err = hDS.Close() //Close must be called and the error must be checked when writing
	if err != nil {
		panic(fmt.Errorf("failed to close shapefile: %w", err))
	}

}
Output:

map[foo:bar]
geom: POLYGON ((100 0,101 0,101 1,100 1,100 0))
map[foo:baz]
geom: POLYGON ((100 0,101 0,101 1,100 1,100 0))
created geometry { "type": "Point", "coordinates": [ 1.0, 1.0 ] }

Index

Examples

Constants

View Source
const (
	//Unknown / Unset Datatype
	Unknown = DataType(C.GDT_Unknown)
	//Byte / UInt8
	Byte = DataType(C.GDT_Byte)
	//UInt16 DataType
	UInt16 = DataType(C.GDT_UInt16)
	//Int16 DataType
	Int16 = DataType(C.GDT_Int16)
	//UInt32 DataType
	UInt32 = DataType(C.GDT_UInt32)
	//Int32 DataType
	Int32 = DataType(C.GDT_Int32)
	//Float32 DataType
	Float32 = DataType(C.GDT_Float32)
	//Float64 DataType
	Float64 = DataType(C.GDT_Float64)
	//CInt16 is a complex Int16
	CInt16 = DataType(C.GDT_CInt16)
	//CInt32 is a complex Int32
	CInt32 = DataType(C.GDT_CInt32)
	//CFloat32 is a complex Float32
	CFloat32 = DataType(C.GDT_CFloat32)
	//CFloat64 is a complex Float64
	CFloat64 = DataType(C.GDT_CFloat64)
)
View Source
const (
	// CE_None is not an error
	CE_None = ErrorCategory(C.CE_None)
	// CE_Debug is a debug level
	CE_Debug = ErrorCategory(C.CE_Debug)
	// CE_Warning is a warning levele
	CE_Warning = ErrorCategory(C.CE_Warning)
	// CE_Failure is an error
	CE_Failure = ErrorCategory(C.CE_Failure)
	// CE_Fatal is an unrecoverable error
	CE_Fatal = ErrorCategory(C.CE_Fatal)
)
View Source
const (
	//CIUndefined is an undefined ColorInterp
	CIUndefined = ColorInterp(C.GCI_Undefined)
	//CIGray is a gray level ColorInterp
	CIGray = ColorInterp(C.GCI_GrayIndex)
	//CIPalette is an undefined ColorInterp
	CIPalette = ColorInterp(C.GCI_PaletteIndex)
	//CIRed is a paletted ColorInterp
	CIRed = ColorInterp(C.GCI_RedBand)
	//CIGreen is a Green ColorInterp
	CIGreen = ColorInterp(C.GCI_GreenBand)
	//CIBlue is a Blue ColorInterp
	CIBlue = ColorInterp(C.GCI_BlueBand)
	//CIAlpha is an Alpha/Transparency ColorInterp
	CIAlpha = ColorInterp(C.GCI_AlphaBand)
	//CIHue is an HSL Hue ColorInterp
	CIHue = ColorInterp(C.GCI_HueBand)
	//CISaturation is an HSL Saturation ColorInterp
	CISaturation = ColorInterp(C.GCI_SaturationBand)
	//CILightness is an HSL Lightness ColorInterp
	CILightness = ColorInterp(C.GCI_LightnessBand)
	//CICyan is an CMYK Cyan ColorInterp
	CICyan = ColorInterp(C.GCI_CyanBand)
	//CIMagenta is an CMYK Magenta ColorInterp
	CIMagenta = ColorInterp(C.GCI_MagentaBand)
	//CIYellow is an CMYK Yellow ColorInterp
	CIYellow = ColorInterp(C.GCI_YellowBand)
	//CIBlack is an CMYK Black ColorInterp
	CIBlack = ColorInterp(C.GCI_BlackBand)
	//CIY is a YCbCr Y ColorInterp
	CIY = ColorInterp(C.GCI_YCbCr_YBand)
	//CICb is a YCbCr Cb ColorInterp
	CICb = ColorInterp(C.GCI_YCbCr_CbBand)
	//CICr is a YCbCr Cr ColorInterp
	CICr = ColorInterp(C.GCI_YCbCr_CrBand)
	//CIMax is an maximum ColorInterp
	CIMax = ColorInterp(C.GCI_Max)
)
View Source
const (
	//GTUnknown is a GeometryType
	GTUnknown = GeometryType(C.wkbUnknown)
	//GTPoint is a GeometryType
	GTPoint = GeometryType(C.wkbPoint)
	//GTPoint25D is a GeometryType
	GTPoint25D = GeometryType(C.wkbPoint25D)
	//GTLinearRing is a GeometryType
	GTLinearRing = GeometryType(C.wkbLinearRing)
	//GTLineString is a GeometryType
	GTLineString = GeometryType(C.wkbLineString)
	//GTLineString25D is a GeometryType
	GTLineString25D = GeometryType(C.wkbLineString25D)
	//GTPolygon is a GeometryType
	GTPolygon = GeometryType(C.wkbPolygon)
	//GTPolygon25D is a GeometryType
	GTPolygon25D = GeometryType(C.wkbPolygon25D)
	//GTMultiPoint is a GeometryType
	GTMultiPoint = GeometryType(C.wkbMultiPoint)
	//GTMultiPoint25D is a GeometryType
	GTMultiPoint25D = GeometryType(C.wkbMultiPoint25D)
	//GTMultiLineString is a GeometryType
	GTMultiLineString = GeometryType(C.wkbMultiLineString)
	//GTMultiLineString25D is a GeometryType
	GTMultiLineString25D = GeometryType(C.wkbMultiLineString25D)
	//GTMultiPolygon is a GeometryType
	GTMultiPolygon = GeometryType(C.wkbMultiPolygon)
	//GTMultiPolygon25D is a GeometryType
	GTMultiPolygon25D = GeometryType(C.wkbMultiPolygon25D)
	//GTGeometryCollection is a GeometryType
	GTGeometryCollection = GeometryType(C.wkbGeometryCollection)
	//GTGeometryCollection25D is a GeometryType
	GTGeometryCollection25D = GeometryType(C.wkbGeometryCollection25D)
	//GTNone is a GeometryType
	GTNone = GeometryType(C.wkbNone)
)
View Source
const (
	//FTInt is a Simple 32bit integer.
	FTInt = FieldType(C.OFTInteger)
	//FTReal is a Double Precision floating point.
	FTReal = FieldType(C.OFTReal)
	//FTString is a String of ASCII chars.
	FTString = FieldType(C.OFTString)
	//FTInt64 is a Single 64bit integer.
	FTInt64 = FieldType(C.OFTInteger64)
	//FTIntList is a List of 32bit integers.
	FTIntList = FieldType(C.OFTIntegerList)
	//FTRealList is a List of doubles.
	FTRealList = FieldType(C.OFTRealList)
	//FTStringList is a Array of strings.
	FTStringList = FieldType(C.OFTStringList)
	//FTBinary is a Raw Binary data.
	FTBinary = FieldType(C.OFTBinary)
	//FTDate is a Date.
	FTDate = FieldType(C.OFTDate)
	//FTTime is a Time.
	FTTime = FieldType(C.OFTTime)
	//FTDateTime is a Date and Time.
	FTDateTime = FieldType(C.OFTDateTime)
	//FTInt64List is a List of 64bit integers.
	FTInt64List = FieldType(C.OFTInteger64List)
	//FTUnknown allow to handle deprecated types like WideString or WideStringList
	FTUnknown = FieldType(C.OFTMaxType + 1)
)

Variables

View Source
var SkipWarnings = ErrLogger(
	func(ec ErrorCategory, code int, message string) error {
		if ec > CE_Warning {
			return errors.New(message)
		}
		return nil
	})

Functions

func AllTouched

func AllTouched() interface {
	RasterizeGeometryOption
}

AllTouched is an option that can be passed to Dataset.RasterizeGeometries() where all pixels touched by lines or polygons will be updated, not just those on the line render path, or whose center point is within the polygon.

func Approximate

func Approximate() interface {
	HistogramOption
	StatisticsOption
}

Approximate allows the histogram algorithm to operate on a subset of the full resolution data

func AssertMinVersion

func AssertMinVersion(major, minor, revision int)

AssertMinVersion will panic if the runtime version is not at least major.minor.revision

func BandInterleaved

func BandInterleaved() interface {
	DatasetIOOption
}

BandInterleaved makes Read return a band interleaved buffer instead of a pixel interleaved one.

For example, pixels of a three band RGB image will be returned in order r1r2r3...rn, g1g2g3...gn, b1b2b3...bn instead of the default r1g1b1, r2g2b2, r3g3b3, ... rnbngn

BandInterleaved should not be used in conjunction with BandSpacing, LineSpacing, PixelSpacing, BandStride, LineStride, or PixelStride

func BandSpacing

func BandSpacing(stride int) interface {
	DatasetIOOption
}

BandSpacing sets the number of bytes from one pixel to the next band of the same pixel. If not provided, it will be calculated from the pixel type

Warning: BandSpacing expects a stride given in *bytes*. Use BandStride to supply a stride compatible with indexes of the buffer slice

func BandStride added in v0.0.4

func BandStride(stride int) interface {
	DatasetIOOption
}

BandStride sets the offset in the provided buffer from one pixel to the next band of the same pixel. If not provided, it will be calculated from the pixel type

func Bands

Bands specifies which dataset bands should be read/written. By default all dataset bands are read/written.

Note: bnds is 0-indexed so as to be consistent with Dataset.Bands(), whereas in GDAL terminology, bands are 1-indexed. i.e. for a 3 band dataset you should pass Bands(0,1,2) and not Bands(1,2,3).

func ConfigOption

ConfigOption sets a configuration option for a gdal library call. See the specific gdal function doc page and specific driver docs for allowed values.

Notable options are GDAL_NUM_THREADS=8

func CreationOption

CreationOption are options to pass to a driver when creating a dataset, to be passed in the form KEY=VALUE

Examples are: BLOCKXSIZE=256, COMPRESS=LZW, NUM_THREADS=8, etc...

func Destination added in v0.0.3

func Destination(band Band) interface {
	SieveFilterOption
}

Destination makes SieveFilter output its result to the given band, instead of updating in-place

func Domain

func Domain(mdDomain string) interface {
	MetadataOption
}

Domain specifies the gdal metadata domain to use

func DriverOpenOption

func DriverOpenOption(keyval ...string) interface {
	OpenOption
	BuildVRTOption
}

DriverOpenOption adds a list of Open Options (-oo switch) to the open command. Each keyval must be provided in a "KEY=value" format

func Drivers

func Drivers(drivers ...string) interface {
	OpenOption
}

Drivers specifies the list of drivers that are allowed to try opening the dataset

func EightConnected

func EightConnected() interface {
	PolygonizeOption
	SieveFilterOption
}

EightConnected is an option that switches pixel connectivity from 4 to 8

func ErrLogger

ErrLogger is an option to override default error handling.

See ErrorHandler.

func GCPProjection added in v0.0.9

func GCPProjection(projStr string) interface {
	SetGCPsOption
}

GCPProjection sets the projection string as an option for SetGCPs

NOTE: A non-nil `sr` takes precedence over `projString`

func GCPSpatialRef added in v0.0.9

func GCPSpatialRef(sr *SpatialRef) interface {
	SetGCPsOption
}

GCPSpatialRef sets the *SpatialRef as an option for SetGCPs

NOTE: A non-nil `sr` takes precedence over `projString

func GCPsToGeoTransform added in v0.0.10

func GCPsToGeoTransform(GCPList []GCP, opts ...GCPsToGeoTransformOption) ([6]float64, error)

Convert list of GCPs to a GDAL GeoTransorm array

func GridCreate added in v0.0.8

func GridCreate(pszAlgorithm string,
	xCoords []float64,
	yCoords []float64,
	zCoords []float64,
	dfXMin float64,
	dfXMax float64,
	dfYMin float64,
	dfYMax float64,
	nXSize int,
	nYSize int,
	buffer interface{},
	opts ...GridCreateOption,
) error

GridCreate, creates a grid from scattered data, given provided gridding parameters as a string (pszAlgorithm) and the arguments required for `godalGridCreate()` (binding for GDALGridCreate)

NOTE: For valid gridding algorithm strings see: https://gdal.org/programs/gdal_grid.html#interpolation-algorithms

func IncludeOutOfRange

func IncludeOutOfRange() interface {
	HistogramOption
}

IncludeOutOfRange populates the first and last bucket with values under/over the specified min/max when used in conjuntion with Intervals()

func Intervals

func Intervals(count int, min, max float64) interface {
	HistogramOption
}

Intervals computes a histogram with count buckets, spanning [min,max]. Each bucket will be (max-min)/count wide. If not provided, the default histogram will be returned.

func Levels

func Levels(levels ...int) interface {
	BuildOverviewsOption
}

Levels set the overview levels to be computed. This is usually:

Levels(2,4,8,16,32)

func LineSpacing

func LineSpacing(stride int) interface {
	DatasetIOOption
	BandIOOption
}

LineSpacing sets the number of bytes from one pixel to the pixel of the same band one row below. If not provided, it will be calculated from the number of bands, pixel type and image width

Warning: LineSpacing expects a stride given in *bytes*. Use LineStride to supply a stride compatible with indexes of the buffer slice

func LineStride added in v0.0.4

func LineStride(stride int) interface {
	DatasetIOOption
	BandIOOption
}

LineStride sets the offset in the provided buffer from one pixel to the pixel of the same band one row below. If not provided, it will be calculated from the number of bands, pixel type and image width

func Mask

Mask makes Polygonize or FillNoData use the given band as a nodata mask instead of using the source band's nodata mask

func MaxDistance added in v0.0.2

func MaxDistance(d float64) interface {
	FillNoDataOption
}

MaxDistance is an option that can be passed to Band.FillNoData which sets the maximum number of pixels to search in all directions to find values to interpolate from.

func MinSize

func MinSize(s int) interface {
	BuildOverviewsOption
}

MinSize makes BuildOverviews automatically compute the overview levels until the smallest overview size is less than s.

Should not be used together with Levels()

func NoMask

func NoMask() interface {
	PolygonizeOption
	SieveFilterOption
}

NoMask makes Polygonize ignore band nodata mask

func PixelSpacing

func PixelSpacing(stride int) interface {
	DatasetIOOption
	BandIOOption
}

PixelSpacing sets the number of bytes from one pixel to the next pixel in the same row. If not provided, it will be calculated from the number of bands and pixel type

Warning: PixelSpacing expects a stride given in *bytes*. Use PixelStride to supply a stride compatible with indexes of the buffer slice

func PixelStride added in v0.0.4

func PixelStride(stride int) interface {
	DatasetIOOption
	BandIOOption
}

PixelStride sets the offset in the provided buffer from one pixel to the next pixel in the same row. If not provided, it will be calculated from the number of bands and pixel type

func PixelValueFieldIndex

func PixelValueFieldIndex(fld int) interface {
	PolygonizeOption
}

PixelValueFieldIndex makes Polygonize write the polygon's pixel value into the layer's fld'th field

func RasterOnly

func RasterOnly() interface {
	OpenOption
}

RasterOnly limits drivers to vector ones (incompatible with VectorOnly() )

func RegisterAll

func RegisterAll()

RegisterAll calls GDALAllRegister which registers all available raster and vector drivers.

Alternatively, you may also register a select number of drivers by calling one or more of

  • godal.RegisterInternal() // MEM, VRT, GTiff and GeoJSON
  • godal.RegisterRaster(godal.GTiff,godal.VRT)
  • godal.RegisterVector(godal.Shapefile)

func RegisterInternalDrivers

func RegisterInternalDrivers()

RegisterInternalDrivers is a shorthand for registering "essential" gdal/ogr drivers.

It is equivalent to calling RegisterRaster("VRT","MEM","GTiff") and RegisterVector("MEM","VRT","GeoJSON")

func RegisterPlugin added in v0.0.9

func RegisterPlugin(name string, opts ...RegisterPluginOption) error

func RegisterPlugins added in v0.0.9

func RegisterPlugins()

func RegisterRaster

func RegisterRaster(drivers ...DriverName) error

RegisterRaster registers a raster driver by name.

Calling RegisterRaster(DriverName) with one of the predefined DriverNames provided by the library will register the corresponding raster driver.

Calling RegisterRaster(DriverName("XXX")) with "XXX" any string will result in calling the function GDALRegister_XXX() if it could be found inside the ligdal.so binary. This allows to register any raster driver known to gdal but not explicitly defined inside this golang wrapper. Note that "XXX" must be provided exactly (i.e. respecting uppercase/lowercase) the same as the names of the C functions GDALRegister_XXX() that can be found in gdal.h

func RegisterVSIHandler

func RegisterVSIHandler(prefix string, handler KeySizerReaderAt, opts ...VSIHandlerOption) error

RegisterVSIHandler registers an osio.Adapter on the given prefix. When registering an adapter with

RegisterVSIHandler("scheme://",handler)

calling Open("scheme://myfile.txt") will result in godal making calls to

adapter.Reader("myfile.txt").ReadAt(buf,offset)

func RegisterVector

func RegisterVector(drivers ...DriverName) error

RegisterVector registers a vector driver by name.

Calling RegisterVector(DriverName) with one of the predefined DriverNames provided by the library will register the corresponding vector driver.

Calling RegisterVector(DriverName("XXX")) with "XXX" any string will result in calling the function RegisterOGRXXX() if it could be found inside the ligdal.so binary. This allows to register any vector driver known to gdal but not explicitly defined inside this golang wrapper. Note that "XXX" must be provided exactly (i.e. respecting uppercase/lowercase) the same as the names of the C functions RegisterOGRXXX() that can be found in ogrsf_frmts.h

func Resampling

Resampling defines the resampling algorithm to use. If unset will usually default to NEAREST. See gdal docs for which algorithms are available.

func Shared

func Shared() interface {
	OpenOption
}

Shared opens the dataset with OF_OPEN_SHARED

func SiblingFiles

func SiblingFiles(files ...string) interface {
	OpenOption
}

SiblingFiles specifies the list of files that may be opened alongside the prinicpal dataset name.

files must not contain a directory component (i.e. are expected to be in the same directory as the main dataset)

SiblingFiles may be used in 3 different manners:

  • By default, i.e. by not using the option, godal will consider that there are no sibling files at all and will prevent any scanning or probing of specific sibling files by passing a list of sibling files to gdal containing only the main file
  • By passing a list of files, only those files will be probed
  • By passing SiblingFiles() (i.e. with an empty list of files), the default gdal behavior of

reading the directory content and/or probing for well-known sidecar filenames will be used.

func SignificantDigits

func SignificantDigits(n int) interface {
	GeoJSONOption
}

SignificantDigits sets the number of significant digits after the decimal separator should be kept for geojson output

func SmoothingIterations added in v0.0.2

func SmoothingIterations(iterations int) interface {
	FillNoDataOption
}

SmoothingIterations is an option that can be passed to Band.FillNoData which sets the number of 3x3 smoothing filter passes to run (0 or more).

func Update

func Update() interface {
	OpenOption
}

Update is an OpenOption that instructs gdal to open the dataset for writing/updating

func VSIUnlink(path string, opts ...VSIUnlinkOption) error

VSIUnlink deletes path

func Values

func Values(vals ...float64) interface {
	RasterizeGeometryOption
}

Values sets the value(s) that must be rasterized in the dataset bands. vals must either be a single value that will be applied to all bands, or exactly match the number of requested bands

func VectorOnly

func VectorOnly() interface {
	OpenOption
}

VectorOnly limits drivers to vector ones (incompatible with RasterOnly() )

func Window

func Window(sx, sy int) interface {
	DatasetIOOption
	BandIOOption
}

Window specifies the size of the dataset window to read/write. By default use the size of the input/output buffer (i.e. no resampling)

Types

type AddGeometryOption added in v0.0.7

type AddGeometryOption interface {
	// contains filtered or unexported methods
}

AddGeometryOption is an option passed to Geometry.AddGeometry()

Available options are:

  • ErrLogger

type Band

type Band struct {
	// contains filtered or unexported fields
}

Band is a wrapper around a GDALRasterBandH

func (Band) ClearMetadata added in v0.0.6

func (mo Band) ClearMetadata(opts ...MetadataOption) error

func (Band) ClearNoData

func (band Band) ClearNoData(opts ...SetNoDataOption) error

ClearNoData clears the band's nodata value

func (Band) ClearScaleOffset added in v0.0.7

func (band Band) ClearScaleOffset(opts ...SetScaleOffsetOption) error

ClearScaleOffset clears the band's scale and offset

func (Band) ColorInterp

func (band Band) ColorInterp() ColorInterp

ColorInterp returns the band's color interpretation (defaults to Gray)

func (Band) ColorTable

func (band Band) ColorTable() ColorTable

ColorTable returns the bands color table. The returned ColorTable will have a 0-length Entries if the band has no color table assigned

func (Band) ComputeStatistics added in v0.0.6

func (band Band) ComputeStatistics(opts ...StatisticsOption) (Statistics, error)

ComputeStatistics returns from exact computation or approximation.

Band full scan might be necessary. Available options are: - Aproximate() to allow the satistics to be computed on overviews or a subset of all tiles. - ErrLogger

func (Band) CreateMask

func (band Band) CreateMask(flags int, opts ...BandCreateMaskOption) (Band, error)

CreateMask creates a mask (nodata) band for this band.

Any handle returned by a previous call to MaskBand() should not be used after a call to CreateMask See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how flag should be used

func (Band) Description added in v0.0.7

func (mo Band) Description() string

Description returns the description/name

func (Band) Fill

func (band Band) Fill(real, imag float64, opts ...FillBandOption) error

Fill sets the whole band uniformely to (real,imag)

func (Band) FillNoData added in v0.0.2

func (band Band) FillNoData(opts ...FillNoDataOption) error

FillNoData wraps GDALFillNodata()

func (Band) GetStatistics added in v0.0.6

func (band Band) GetStatistics(opts ...StatisticsOption) (Statistics, bool, error)

GetStatistics returns if present and flag as true.

Only cached statistics are returned and no new statistics are computed. Return false and no error if no statistics are availables. Available options are: - Aproximate() to allow the satistics to be computed on overviews or a subset of all tiles. - ErrLogger

func (Band) Histogram

func (band Band) Histogram(opts ...HistogramOption) (Histogram, error)

Histogram returns or computes the bands histogram

func (Band) IO

func (band Band) IO(rw IOOperation, srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error

IO reads or writes the pixels contained in the supplied window

Example
package main

import (
	"io/ioutil"
	"math/rand"
	"os"

	"github.com/airbusgeo/godal"
)

func main() {
	tmpfile, _ := ioutil.TempFile("", "")
	tmpfile.Close()
	dsfile := tmpfile.Name()
	defer os.Remove(dsfile)

	//create a 200x200 one band image, internally tiled with 32x32 blocks
	ds, _ := godal.Create(godal.GTiff, dsfile, 1, godal.Byte, 200, 200, godal.CreationOption("TILED=YES", "BLOCKXSIZE=32", "BLOCKYSIZE=32"))

	//fill the band with random data
	buf := make([]byte, 200*200)
	for i := range buf {
		buf[i] = byte(rand.Intn(255))
	}
	bands := ds.Bands()

	//write the random data to the first band
	bands[0].Write(0, 0, buf, 200, 200)

	//add a mask band to the dataset.
	maskBnd, _ := ds.CreateMaskBand(0x02, godal.ConfigOption("GDAL_TIFF_INTERNAL_MASK=YES"))

	//we now want to populate the mask data. we will do this block by block to optimize data access
	structure := bands[0].Structure()

	//allocate a memory buffer that is big enough to contain a whole block
	blockBuf := make([]byte, 32*32)

	//iterate over all blocks
	for block, ok := structure.FirstBlock(), true; ok; block, ok = block.Next() {
		//read the (previously created random data) into our memory buffer
		bands[0].Read(block.X0, block.Y0, blockBuf, block.W, block.H)

		//populate the mask band, by setting to nodata if the pixel value is under 100
		for pix := 0; pix < block.W*block.H; pix++ {
			if blockBuf[pix] < 100 {
				blockBuf[pix] = 0
			} else {
				blockBuf[pix] = 255
			}
		}

		//write the dynamically created mask data into the mask band
		maskBnd.Write(block.X0, block.Y0, blockBuf, block.W, block.H)

	}

	//write dataset to disk
	ds.Close()
}
Output:

func (Band) MaskBand

func (band Band) MaskBand() Band

MaskBand returns the mask (nodata) band for this band. May be generated from nodata values.

func (Band) MaskFlags

func (band Band) MaskFlags() int

MaskFlags returns the mask flags associated with this band.

See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how this flag should be interpreted

func (Band) Metadata

func (mo Band) Metadata(key string, opts ...MetadataOption) string

func (Band) MetadataDomains

func (mo Band) MetadataDomains() []string

func (Band) Metadatas

func (mo Band) Metadatas(opts ...MetadataOption) map[string]string

func (Band) NoData

func (band Band) NoData() (nodata float64, ok bool)

NoData returns the band's nodata value. if ok is false, the band does not have a nodata value set

func (Band) Overviews

func (band Band) Overviews() []Band

Overviews returns all overviews of band

func (Band) Polygonize

func (band Band) Polygonize(dstLayer Layer, opts ...PolygonizeOption) error

Polygonize wraps GDALPolygonize

func (Band) Read

func (band Band) Read(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error

Read populates the supplied buffer with the pixels contained in the supplied window

func (Band) SetColorInterp

func (band Band) SetColorInterp(colorInterp ColorInterp, opts ...SetColorInterpOption) error

SetColorInterp sets the band's color interpretation

func (Band) SetColorTable

func (band Band) SetColorTable(ct ColorTable, opts ...SetColorTableOption) error

SetColorTable sets the band's color table. if passing in a 0-length ct.Entries, the band's color table will be cleared

func (Band) SetDescription added in v0.0.7

func (mo Band) SetDescription(description string, opts ...SetDescriptionOption) error

SetDescription sets the description

func (Band) SetMetadata

func (mo Band) SetMetadata(key, value string, opts ...MetadataOption) error

func (Band) SetNoData

func (band Band) SetNoData(nd float64, opts ...SetNoDataOption) error

SetNoData sets the band's nodata value

func (Band) SetScaleOffset added in v0.0.7

func (band Band) SetScaleOffset(scale, offset float64, opts ...SetScaleOffsetOption) error

SetScaleOffset sets the band's scale and offset

func (Band) SetStatistics added in v0.0.6

func (band Band) SetStatistics(min, max, mean, std float64, opts ...SetStatisticsOption) error

SetStatistics set statistics (Min, Max, Mean & STD).

Available options are:

-ErrLogger

func (Band) SieveFilter added in v0.0.3

func (band Band) SieveFilter(sizeThreshold int, opts ...SieveFilterOption) error

SieveFilter wraps GDALSieveFilter

func (Band) Structure

func (band Band) Structure() BandStructure

Structure returns the dataset's Structure

func (Band) Write

func (band Band) Write(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error

Write sets the dataset's pixels contained in the supplied window to the content of the supplied buffer

type BandCreateMaskOption

type BandCreateMaskOption interface {
	// contains filtered or unexported methods
}

BandCreateMaskOption is an option that can be passed to Band.CreateMask()

Available BandCreateMaskOptions are:

  • ConfigOption
  • ErrLogger

type BandIOOption

type BandIOOption interface {
	// contains filtered or unexported methods
}

BandIOOption is an option to modify the default behavior of band.IO

Available BandIOOptions are:

  • PixelStride
  • LineStride
  • Window
  • Resampling
  • ConfigOption
  • PixelSpacing
  • LineSpacing

type BandStructure

type BandStructure struct {
	SizeX, SizeY           int
	BlockSizeX, BlockSizeY int
	Scale, Offset          float64
	DataType               DataType
}

BandStructure implements Structure for a Band

func (BandStructure) ActualBlockSize

func (is BandStructure) ActualBlockSize(blockX, blockY int) (int, int)

ActualBlockSize returns the number of pixels in the x and y dimensions that actually contain data for the given x,y block

func (BandStructure) BlockCount

func (is BandStructure) BlockCount() (int, int)

BlockCount returns the number of blocks in the x and y dimensions

func (BandStructure) FirstBlock

func (is BandStructure) FirstBlock() Block

FirstBlock returns the topleft block definition

type Block

type Block struct {
	X0, Y0 int
	W, H   int
	// contains filtered or unexported fields
}

Block is a window inside a dataset, starting at pixel X0,Y0 and spanning W,H pixels.

func BlockIterator

func BlockIterator(sizeX, sizeY int, blockSizeX, blockSizeY int) Block

BlockIterator returns the blocks covering a sizeX,sizeY dataset. All sizes must be strictly positive.

func (Block) Next

func (b Block) Next() (Block, bool)

Next returns the following block in scanline order. It returns Block{},false when there are no more blocks in the scanlines

type BoundsOption

type BoundsOption interface {
	// contains filtered or unexported methods
}

BoundsOption is an option that can be passed to Dataset.Bounds or Geometry.Bounds

Available options are:

  • *SpatialRef
  • ErrLogger

type Bucket

type Bucket struct {
	Min, Max float64
	Count    uint64
}

Bucket is a histogram entry. It spans [Min,Max] and contains Count entries.

type BufferOption

type BufferOption interface {
	// contains filtered or unexported methods
}

BufferOption is an option passed to Geometry.Buffer()

Available options are:

  • ErrLogger

type BuildOverviewsOption

type BuildOverviewsOption interface {
	// contains filtered or unexported methods
}

BuildOverviewsOption is an option to specify how overview building should behave.

Available BuildOverviewsOptions are:

  • ConfigOption
  • Resampling
  • Levels
  • MinSize
  • Bands

type BuildVRTOption

type BuildVRTOption interface {
	// contains filtered or unexported methods
}

BuildVRTOption is an option that can be passed to BuildVRT

Available BuildVRTOptions are:

  • ConfigOption
  • DriverOpenOption
  • Bands
  • Resampling

type ClearOverviewsOption

type ClearOverviewsOption interface {
	// contains filtered or unexported methods
}

ClearOverviewsOption is an option passed to Dataset.ClearOverviews

Available options are:

  • ErrLogger

type ClearStatisticsOption added in v0.0.6

type ClearStatisticsOption interface {
	// contains filtered or unexported methods
}

ClearStatistics is an option passed to Dataset.ClearStatistics Available options are:

-ErrLogger

type CloseOption

type CloseOption interface {
	// contains filtered or unexported methods
}

CloseOption is an option passed to Dataset.Close()

Available options are:

  • ErrLogger

type ColorInterp

type ColorInterp int

ColorInterp is a band's color interpretation

func (ColorInterp) Name

func (colorInterp ColorInterp) Name() string

Name returns the ColorInterp's name

type ColorTable

type ColorTable struct {
	PaletteInterp PaletteInterp
	Entries       [][4]int16
}

ColorTable is a color table associated with a Band

type CopyLayerOption added in v0.0.7

type CopyLayerOption interface {
	// contains filtered or unexported methods
}

CopyLayerOption is an option that can be passed to Dataset.CreateLayer()

type CreateFeatureOption added in v0.0.7

type CreateFeatureOption interface {
	// contains filtered or unexported methods
}

CreateFeatureOption is an option that can be passed to Layer.CreateFeature

Available options are:

  • none yet

type CreateLayerOption

type CreateLayerOption interface {
	// contains filtered or unexported methods
}

CreateLayerOption is an option that can be passed to Dataset.CreateLayer()

type CreateSpatialRefOption

type CreateSpatialRefOption interface {
	// contains filtered or unexported methods
}

CreateSpatialRefOption is an option that can be passed when creating a new spatial reference object

Available options are:

  • ErrLogger

type DataType

type DataType int

DataType is a pixel data types

func (DataType) Size

func (dtype DataType) Size() int

Size retruns the number of bytes needed for one instance of DataType

func (DataType) String

func (dtype DataType) String() string

String implements Stringer

type Dataset

type Dataset struct {
	// contains filtered or unexported fields
}

Dataset is a wrapper around a GDALDatasetH

func BuildVRT

func BuildVRT(dstVRTName string, sourceDatasets []string, switches []string, opts ...BuildVRTOption) (*Dataset, error)

BuildVRT runs the GDALBuildVRT function and creates a VRT dataset from a list of datasets

func Create

func Create(driver DriverName, name string, nBands int, dtype DataType, width, height int, opts ...DatasetCreateOption) (*Dataset, error)

Create wraps GDALCreate and uses driver to creates a new raster dataset with the given name (usually filename), size, type and bands.

func CreateVector

func CreateVector(driver DriverName, name string, opts ...DatasetCreateOption) (*Dataset, error)

CreateVector wraps GDALCreate and uses driver to create a new vector dataset with the given name (usually filename) and options

func Open

func Open(name string, options ...OpenOption) (*Dataset, error)

Open calls GDALOpenEx() with the provided options. It returns nil and an error in case there was an error opening the provided dataset name.

name may be a filename or any supported string supported by gdal (e.g. a /vsixxx path, the xml string representing a vrt dataset, etc...)

func Warp

func Warp(dstDS string, sourceDS []*Dataset, switches []string, opts ...DatasetWarpOption) (*Dataset, error)

Warp writes provided sourceDS Datasets into new dataset and runs the library version of gdalwarp See the gdalwarp doc page to determine the valid flags/opts that can be set in switches.

Example switches :

 []string{
	  "-t_srs","epsg:3857",
   "-dstalpha"}

Creation options and driver may be set either in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

or through Options with

ds.Warp(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)

func (*Dataset) Bands

func (ds *Dataset) Bands() []Band

Bands returns all dataset bands.

func (*Dataset) Bounds

func (ds *Dataset) Bounds(opts ...BoundsOption) ([4]float64, error)

Bounds returns the dataset's bounding box in the order

[MinX, MinY, MaxX, MaxY]

func (*Dataset) BuildOverviews

func (ds *Dataset) BuildOverviews(opts ...BuildOverviewsOption) error

BuildOverviews computes overviews for the dataset.

If neither Levels() or MinSize() is specified, will compute overview levels such that the smallest overview is just under the block size.

Not Setting OvrLevels() or OvrMinSize() if the dataset is not internally tiled is not an error but will probably not create the expected result (i.e. only a single overview will be created).

func (Dataset) ClearMetadata added in v0.0.6

func (mo Dataset) ClearMetadata(opts ...MetadataOption) error

func (*Dataset) ClearOverviews

func (ds *Dataset) ClearOverviews(opts ...ClearOverviewsOption) error

ClearOverviews deletes all dataset overviews

func (*Dataset) ClearStatistics added in v0.0.6

func (ds *Dataset) ClearStatistics(opts ...ClearStatisticsOption) error

ClearStatistics delete dataset statisitics

Since GDAL 3.2 Available options are:

-ErrLogger

func (*Dataset) Close

func (ds *Dataset) Close(opts ...CloseOption) error

Close releases the dataset

func (*Dataset) CopyLayer added in v0.0.7

func (ds *Dataset) CopyLayer(source Layer, name string, opts ...CopyLayerOption) (Layer, error)

CopyLayer Duplicate an existing layer.

func (*Dataset) CreateLayer

func (ds *Dataset) CreateLayer(name string, sr *SpatialRef, gtype GeometryType, opts ...CreateLayerOption) (Layer, error)

CreateLayer creates a new vector layer

Available CreateLayerOptions are

  • FieldDefinition (may be used multiple times) to add attribute fields to the layer

func (*Dataset) CreateMaskBand

func (ds *Dataset) CreateMaskBand(flags int, opts ...DatasetCreateMaskOption) (Band, error)

CreateMaskBand creates a mask (nodata) band shared for all bands of this dataset.

Any handle returned by a previous call to Band.MaskBand() should not be used after a call to CreateMaskBand See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how flag should be used

func (*Dataset) Dem added in v0.0.9

func (ds *Dataset) Dem(destPath, processingMode string, colorFilename string, switches []string, opts ...DemOption) (*Dataset, error)

Dem runs the library version of gdaldem. See the gdaldem doc page to determine the valid flags/opts that can be set in switches.

Example switches (for "hillshade", switches differ per mode):

[]string{"-s", "111120", "-alt", "45"}

Creation options and driver may be set in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

NOTE: `colorFilename` is a "text-based color configuration file" that MUST ONLY be provided when `processingMode` == "color-relief"

func (Dataset) Description added in v0.0.7

func (mo Dataset) Description() string

Description returns the description/name

func (*Dataset) Driver added in v0.0.7

func (ds *Dataset) Driver() Driver

Driver returns dataset driver.

func (*Dataset) GCPProjection added in v0.0.9

func (ds *Dataset) GCPProjection() string

GetGCPProjection runs the GDALGetGCPProjection function

func (*Dataset) GCPSpatialRef added in v0.0.9

func (ds *Dataset) GCPSpatialRef() *SpatialRef

GetGCPSpatialRef runs the GDALGetGCPSpatialRef function

func (*Dataset) GCPs added in v0.0.9

func (ds *Dataset) GCPs() []GCP

GetGCPs runs the GDALGetGCPs function

func (*Dataset) GeoTransform

func (ds *Dataset) GeoTransform(opts ...GetGeoTransformOption) ([6]float64, error)

GeoTransform returns the affine transformation coefficients

func (*Dataset) Grid added in v0.0.8

func (ds *Dataset) Grid(destPath string, switches []string, opts ...GridOption) (*Dataset, error)

Grid runs the library version of gdal_grid. See the gdal_grid doc page to determine the valid flags/opts that can be set in switches.

Example switches :

[]string{"-a", "maximum", "-txe", "0", "1"}

Creation options and driver may be set in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

NOTE: Some switches are NOT compatible with this binding, as a `nullptr` is passed to a later call to `GDALGridOptionsNew()` (as the 2nd argument). Those switches are: "-oo", "-q", "-quiet"

func (*Dataset) IO

func (ds *Dataset) IO(rw IOOperation, srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...DatasetIOOption) error

IO reads or writes the pixels contained in the supplied window

func (*Dataset) LayerByName added in v0.0.7

func (ds *Dataset) LayerByName(name string) *Layer

LayerByName fetch a layer by name. Returns nil if not found.

func (*Dataset) Layers

func (ds *Dataset) Layers() []Layer

Layers returns all dataset layers

func (Dataset) Metadata

func (mo Dataset) Metadata(key string, opts ...MetadataOption) string

func (Dataset) MetadataDomains

func (mo Dataset) MetadataDomains() []string

func (Dataset) Metadatas

func (mo Dataset) Metadatas(opts ...MetadataOption) map[string]string

func (*Dataset) Nearblack added in v0.0.9

func (ds *Dataset) Nearblack(dstDS string, switches []string, opts ...NearblackOption) (*Dataset, error)

Nearblack runs the library version of nearblack

See the nearblack doc page to determine the valid flags/opts that can be set in switches.

Example switches :

[]string{"-white", "-near", "10"}

Creation options and driver may be set in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

NOTE: Some switches are NOT compatible with this binding, as a `nullptr` is passed to a later call to `GDALNearblackOptionsNew()` (as the 2nd argument). Those switches are: "-o", "-q", "-quiet"

func (*Dataset) NearblackInto added in v0.0.9

func (ds *Dataset) NearblackInto(sourceDs *Dataset, switches []string, opts ...NearblackOption) error

NearblackInto writes the provided `sourceDs` into the Dataset that this method was called on, and runs the library version of nearblack.

See the nearblack doc page to determine the valid flags/opts that can be set in switches.

Example switches :

[]string{"-white", "-near", "10"}

Creation options and driver may be set in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

NOTE: Some switches are NOT compatible with this binding, as a `nullptr` is passed to a later call to `GDALNearblackOptionsNew()` (as the 2nd argument). Those switches are: "-o", "-q", "-quiet"

func (*Dataset) Projection

func (ds *Dataset) Projection() string

Projection returns the WKT projection of the dataset. May be empty.

func (*Dataset) Rasterize

func (ds *Dataset) Rasterize(dstDS string, switches []string, opts ...RasterizeOption) (*Dataset, error)

Rasterize wraps GDALRasterize()

func (*Dataset) RasterizeGeometry

func (ds *Dataset) RasterizeGeometry(g *Geometry, opts ...RasterizeGeometryOption) error

RasterizeGeometry "burns" the provided geometry onto ds. By default, the "0" value is burned into all of ds's bands. This behavior can be modified with the following options:

  • Bands(bnd ...int) the list of bands to affect
  • Values(val ...float64) the pixel value to burn. There must be either 1 or len(bands) values

provided

  • AllTouched() pixels touched by lines or polygons will be updated, not just those on the line

render path, or whose center point is within the polygon.

func (*Dataset) RasterizeInto added in v0.0.7

func (ds *Dataset) RasterizeInto(vectorDS *Dataset, switches []string, opts ...RasterizeIntoOption) error

RasterizeInto wraps GDALRasterize() and rasterizes the provided vectorDataset into the ds Dataset

func (*Dataset) Read

func (ds *Dataset) Read(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...DatasetIOOption) error

Read populates the supplied buffer with the pixels contained in the supplied window

func (Dataset) SetDescription added in v0.0.7

func (mo Dataset) SetDescription(description string, opts ...SetDescriptionOption) error

SetDescription sets the description

func (*Dataset) SetGCPs added in v0.0.9

func (ds *Dataset) SetGCPs(GCPList []GCP, opts ...SetGCPsOption) error

SetGCPs runs the GDALSetGCPs function

func (*Dataset) SetGeoTransform

func (ds *Dataset) SetGeoTransform(transform [6]float64, opts ...SetGeoTransformOption) error

SetGeoTransform sets the affine transformation coefficients

func (Dataset) SetMetadata

func (mo Dataset) SetMetadata(key, value string, opts ...MetadataOption) error

func (*Dataset) SetNoData

func (ds *Dataset) SetNoData(nd float64, opts ...SetNoDataOption) error

SetNoData sets the band's nodata value

func (*Dataset) SetProjection

func (ds *Dataset) SetProjection(wkt string, opts ...SetProjectionOption) error

SetProjection sets the WKT projection of the dataset. May be empty.

func (*Dataset) SetScaleOffset added in v0.0.7

func (ds *Dataset) SetScaleOffset(scale, offset float64, opts ...SetScaleOffsetOption) error

SetScaleOffset sets the band's scale and offset

func (*Dataset) SetSpatialRef

func (ds *Dataset) SetSpatialRef(sr *SpatialRef, opts ...SetSpatialRefOption) error

SetSpatialRef sets dataset's projection.

sr can be set to nil to clear an existing projection

func (*Dataset) SpatialRef

func (ds *Dataset) SpatialRef() *SpatialRef

SpatialRef returns dataset projection.

func (*Dataset) Structure

func (ds *Dataset) Structure() DatasetStructure

Structure returns the dataset's Structure

func (*Dataset) Translate

func (ds *Dataset) Translate(dstDS string, switches []string, opts ...DatasetTranslateOption) (*Dataset, error)

Translate runs the library version of gdal_translate. See the gdal_translate doc page to determine the valid flags/opts that can be set in switches.

Example switches :

[]string{
  "-a_nodata", 0,
  "-a_srs", "epsg:4326"}

Creation options and driver may be set either in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

or through Options with

ds.Translate(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)

func (*Dataset) VectorTranslate

func (ds *Dataset) VectorTranslate(dstDS string, switches []string, opts ...DatasetVectorTranslateOption) (*Dataset, error)

VectorTranslate runs the library version of ogr2ogr See the ogr2ogr doc page to determine the valid flags/opts that can be set in switches.

Example switches :

 []string{
   "-f", "GeoJSON",
	  "-t_srs","epsg:3857",
   "-dstalpha"}

Creation options and Driver may be set either in the switches slice with

switches:=[]string{"-dsco","TILED=YES", "-f","GeoJSON"}

or through Options with

ds.VectorTranslate(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GeoJSON)

func (*Dataset) Warp

func (ds *Dataset) Warp(dstDS string, switches []string, opts ...DatasetWarpOption) (*Dataset, error)

Warp runs the library version of gdalwarp See the gdalwarp doc page to determine the valid flags/opts that can be set in switches.

Example switches :

 []string{
	  "-t_srs","epsg:3857",
   "-dstalpha"}

Creation options and driver may be set either in the switches slice with

switches:=[]string{"-co","TILED=YES","-of","GTiff"}

or through Options with

ds.Warp(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)

func (*Dataset) WarpInto

func (ds *Dataset) WarpInto(sourceDS []*Dataset, switches []string, opts ...DatasetWarpIntoOption) error

WarpInto writes provided sourceDS Datasets into self existing dataset and runs the library version of gdalwarp See the gdalwarp doc page to determine the valid flags/opts that can be set in switches.

Example switches :

 []string{
	  "-t_srs","epsg:3857",
   "-dstalpha"}

func (*Dataset) Write

func (ds *Dataset) Write(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...DatasetIOOption) error

Write sets the dataset's pixels contained in the supplied window to the content of the supplied buffer

type DatasetCreateMaskOption

type DatasetCreateMaskOption interface {
	// contains filtered or unexported methods
}

DatasetCreateMaskOption is an option that can be passed to Dataset.CreateMaskBand()

Available DatasetCreateMaskOptions are:

  • ConfigOption

type DatasetCreateOption

type DatasetCreateOption interface {
	// contains filtered or unexported methods
}

DatasetCreateOption is an option that can be passed to Create()

Available DatasetCreateOptions are:

  • CreationOption
  • ConfigOption
  • ErrLogger

type DatasetIOOption

type DatasetIOOption interface {
	// contains filtered or unexported methods
}

DatasetIOOption is an option to modify the default behavior of dataset.IO

Available DatasetIOOptions are:

  • PixelStride
  • LineStride
  • BandStride
  • Window
  • Resampling
  • ConfigOption
  • Bands
  • BandInterleaved
  • PixelSpacing
  • LineSpacing
  • BandSpacing

type DatasetStructure

type DatasetStructure struct {
	BandStructure
	NBands int
}

DatasetStructure implements Structure for a Dataset

type DatasetTranslateOption

type DatasetTranslateOption interface {
	// contains filtered or unexported methods
}

DatasetTranslateOption is an option that can be passed to Dataset.Translate()

Available DatasetTranslateOptions are:

  • ConfigOption
  • CreationOption
  • DriverName

type DatasetVectorTranslateOption

type DatasetVectorTranslateOption interface {
	// contains filtered or unexported methods
}

DatasetVectorTranslateOption is an option that can be passed to Dataset.Warp()

Available Options are:

  • CreationOption
  • ConfigOption
  • DriverName

type DatasetWarpIntoOption

type DatasetWarpIntoOption interface {
	// contains filtered or unexported methods
}

DatasetWarpIntoOption is an option that can be passed to Dataset.WarpInto()

Available DatasetWarpIntoOption is:

  • ConfigOption

type DatasetWarpOption

type DatasetWarpOption interface {
	// contains filtered or unexported methods
}

DatasetWarpOption is an option that can be passed to Dataset.Warp()

Available DatasetWarpOptions are:

  • ConfigOption
  • CreationOption
  • DriverName

type DeleteFeatureOption

type DeleteFeatureOption interface {
	// contains filtered or unexported methods
}

DeleteFeatureOption is an option passed to Layer.DeleteFeature()

Available options are:

  • ErrLogger

type DemOption added in v0.0.9

type DemOption interface {
	// contains filtered or unexported methods
}

DemOption is an option that can be passed to Dataset.Dem()

type DifferenceOption added in v0.0.7

type DifferenceOption interface {
	// contains filtered or unexported methods
}

DifferenceOption is an option passed to Geometry.Difference()

Available options are:

  • ErrLogger

type Driver

type Driver struct {
	// contains filtered or unexported fields
}

Driver is a gdal format driver

func RasterDriver

func RasterDriver(name DriverName) (Driver, bool)

RasterDriver returns a Driver by name. It returns false if the named driver does not exist

func VectorDriver

func VectorDriver(name DriverName) (Driver, bool)

VectorDriver returns a Driver by name. It returns false if the named driver does not exist

func (Driver) ClearMetadata added in v0.0.6

func (mo Driver) ClearMetadata(opts ...MetadataOption) error

func (Driver) Description added in v0.0.7

func (mo Driver) Description() string

Description returns the description/name

func (Driver) LongName added in v0.0.7

func (drv Driver) LongName() string

LongName returns the driver long name.

func (Driver) Metadata

func (mo Driver) Metadata(key string, opts ...MetadataOption) string

func (Driver) MetadataDomains

func (mo Driver) MetadataDomains() []string

func (Driver) Metadatas

func (mo Driver) Metadatas(opts ...MetadataOption) map[string]string

func (Driver) SetDescription added in v0.0.7

func (mo Driver) SetDescription(description string, opts ...SetDescriptionOption) error

SetDescription sets the description

func (Driver) SetMetadata

func (mo Driver) SetMetadata(key, value string, opts ...MetadataOption) error

func (Driver) ShortName added in v0.0.7

func (drv Driver) ShortName() string

ShortName returns the driver short name.

type DriverName

type DriverName string

DriverName is GDAL driver

const (
	//GTiff GeoTIFF
	GTiff DriverName = "GTiff"
	//GeoJSON RFCxxxx geojson
	GeoJSON DriverName = "GeoJSON"
	//Memory in memory driver
	Memory DriverName = "Memory"
	//VRT is a VRT
	VRT DriverName = "VRT"
	//Shapefile is an ESRI Shapefile
	Shapefile DriverName = "ESRI Shapefile"
	//GeoPackage is a geo-package
	GeoPackage DriverName = "GPKG"
	//JP2KAK is a Kakadu Jpeg2000
	JP2KAK DriverName = "JP2KAK"
	//OpenJPEG is an OpenJPEG JPEG2000
	OpenJPEG DriverName = "OpenJPEG"
	//DIMAP is a Dimap
	DIMAP DriverName = "DIMAP"
	//HFA is an erdas img
	HFA DriverName = "HFA"
	//Mitab is a mapinfo mif/tab file
	Mitab DriverName = "Mitab"
	//CSV comma-separated values driver
	CSV DriverName = "CSV"
)

type ErrorCategory

type ErrorCategory int

ErrorCategory wraps GDAL's error types

type ErrorHandler

type ErrorHandler func(ec ErrorCategory, code int, msg string) error

ErrorHandler is a function that can be used to override godal's default behavior of treating all messages with severity >= CE_Warning as errors. When an ErrorHandler is passed as an option to a godal function, all logs/errors emitted by gdal will be passed to this function, which can decide wether the parameters correspond to an actual error or not.

If the ErrorHandler returns nil, the parent function will not return an error. It is up to the ErrorHandler to log the message if needed.

If the ErrorHandler returns an error, that error will be returned as-is to the caller of the parent function

Example (Sentinel)

ExampleErrorHandler_sentinel is an example to make godal.Open return a specific golang error when the gdal emitted error/log matches certain criteria

package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/airbusgeo/godal"
)

func main() {
	sentinel := errors.New("noent")
	eh := func(ec godal.ErrorCategory, code int, msg string) error {
		/* do some advanced checking of ec, code and msg to determine if this is an actual error */
		haveError := true
		if !haveError {
			log.Println(msg)
			return nil
		}
		return sentinel
	}
	_, err := godal.Open("nonexistent.tif", godal.ErrLogger(eh))
	if errors.Is(err, sentinel) {
		fmt.Println(err.Error())
	}

}
Output:

noent
Example (Warnings)

ExampleErrorHandler_warnings is an example to set up an error handler that ignores gdal warnings

package main

import (
	"fmt"
	"log"

	"github.com/airbusgeo/godal"
)

func main() {
	eh := func(ec godal.ErrorCategory, code int, msg string) error {
		if ec <= godal.CE_Warning {
			log.Println(msg)
			return nil
		}
		return fmt.Errorf("GDAL %d: %s", code, msg)
	}
	_, err := godal.Open("nonexistent.tif", godal.ErrLogger(eh))
	// err if returned will not arise from a gdal warning
	_ = err
}
Output:

type Feature

type Feature struct {
	// contains filtered or unexported fields
}

Feature is a Layer feature

func (*Feature) Close

func (f *Feature) Close()

Close releases resources associated to a feature

func (*Feature) Fields

func (f *Feature) Fields() map[string]Field

Fields returns all the Feature's fields

func (*Feature) Geometry

func (f *Feature) Geometry() *Geometry

Geometry returns a handle to the feature's geometry

func (*Feature) SetFID added in v0.0.7

func (f *Feature) SetFID(fid int64)

SetFID set feature identifier

func (*Feature) SetFieldValue added in v0.0.7

func (f *Feature) SetFieldValue(field Field, value interface{}, opts ...SetFieldValueOption) error

SetFieldValue set feature's field value

func (*Feature) SetGeometry

func (f *Feature) SetGeometry(geom *Geometry, opts ...SetGeometryOption) error

SetGeometry overwrites the feature's geometry

func (*Feature) SetGeometryColumnName added in v0.0.7

func (f *Feature) SetGeometryColumnName(name string, opts ...SetGeometryColumnNameOption) error

SetGeometryColumnName set the name of feature first geometry field. Deprecated when running with GDAL 3.6+, use SetGeometryColumnName on Layer instead. No more supported when running with GDAL 3.9+.

type FeatureCountOption

type FeatureCountOption interface {
	// contains filtered or unexported methods
}

FeatureCountOption is an option passed to Layer.FeatureCount()

Available options are:

  • ErrLogger

type Field

type Field struct {
	// contains filtered or unexported fields
}

Field is a Feature attribute

func (Field) Bytes added in v0.0.7

func (fld Field) Bytes() []byte

Bytes returns the field as a byte slice

func (Field) DateTime added in v0.0.7

func (fld Field) DateTime() *time.Time

DateTime returns the field as a date time

func (Field) Float

func (fld Field) Float() float64

Float returns the field as a float64

func (Field) FloatList added in v0.0.7

func (fld Field) FloatList() []float64

FloatList returns the field as a list of float64

func (Field) Int

func (fld Field) Int() int64

Int returns the Field as an integer

func (Field) IntList added in v0.0.7

func (fld Field) IntList() []int64

IntList returns the field as a list of integer

func (Field) IsSet added in v0.0.7

func (fld Field) IsSet() bool

IsSet returns if the field has ever been assigned a value or not.

func (Field) String

func (fld Field) String() string

String returns the field as a string

func (Field) StringList added in v0.0.7

func (fld Field) StringList() []string

StringList returns the field as a list of string

func (Field) Type

func (fld Field) Type() FieldType

Type returns the field's native type

type FieldDefinition

type FieldDefinition struct {
	// contains filtered or unexported fields
}

FieldDefinition defines a single attribute

func NewFieldDefinition

func NewFieldDefinition(name string, fdtype FieldType) *FieldDefinition

NewFieldDefinition creates a FieldDefinition

type FieldType

type FieldType C.OGRFieldType

FieldType is a vector field (attribute/column) type

type FillBandOption

type FillBandOption interface {
	// contains filtered or unexported methods
}

FillBandOption is an option that can be passed to Band.Fill()

Available FillBandOptions are:

  • ErrLogger

type FillNoDataOption added in v0.0.2

type FillNoDataOption interface {
	// contains filtered or unexported methods
}

FillNoDataOption is an option that can be passed to band.FillNoData

Available FillNoDataOptions are:

  • MaxDistance(int): The maximum distance (in pixels) that the algorithm will search out for values to interpolate. The default is 100 pixels.
  • SmoothIterations(int): The number of 3x3 average filter smoothing iterations to run after the interpolation to dampen artifacts. The default is zero smoothing iterations.
  • Mask(band) to use given band as nodata mask. The default uses the internal nodata mask

type GCP added in v0.0.9

type GCP struct {
	PszId      string
	PszInfo    string
	DfGCPPixel float64
	DfGCPLine  float64
	DfGCPX     float64
	DfGCPY     float64
	DfGCPZ     float64
}

GCP mirrors the structure of the GDAL_GCP type

type GCPsToGeoTransformOption added in v0.0.10

type GCPsToGeoTransformOption interface {
	// contains filtered or unexported methods
}

GCPsToGeoTransformOption is an option that can be passed to GCPsToGeoTransform()

type GMLExportOption added in v0.0.7

type GMLExportOption interface {
	// contains filtered or unexported methods
}

GMLExportOption is an option passed to Geometry.GML()

Available options are:

  • CreationOption
  • ErrLogger

type GeoJSONOption

type GeoJSONOption interface {
	// contains filtered or unexported methods
}

GeoJSONOption is an option that can be passed to Geometry.GeoJSON

type Geometry

type Geometry struct {
	// contains filtered or unexported fields
}

Geometry wraps a OGRGeometryH

func NewGeometryFromGeoJSON added in v0.0.6

func NewGeometryFromGeoJSON(geoJSON string, opts ...NewGeometryOption) (*Geometry, error)

NewGeometryFromGeoJSON creates a new Geometry from its GeoJSON representation

func NewGeometryFromWKB

func NewGeometryFromWKB(wkb []byte, sr *SpatialRef, opts ...NewGeometryOption) (*Geometry, error)

NewGeometryFromWKB creates a new Geometry from its WKB representation

func NewGeometryFromWKT

func NewGeometryFromWKT(wkt string, sr *SpatialRef, opts ...NewGeometryOption) (*Geometry, error)

NewGeometryFromWKT creates a new Geometry from its WKT representation

func (*Geometry) AddGeometry added in v0.0.7

func (g *Geometry) AddGeometry(subGeom *Geometry, opts ...AddGeometryOption) error

AddGeometry add a geometry to a geometry container.

func (*Geometry) Area added in v0.0.7

func (g *Geometry) Area() float64

Area computes the area for geometries of type LinearRing, Polygon or MultiPolygon (returns zero for other types). The area is in square units of the spatial reference system in use.

func (*Geometry) Bounds

func (g *Geometry) Bounds(opts ...BoundsOption) ([4]float64, error)

Bounds returns the geometry's envelope in the order minx,miny,maxx,maxy

func (*Geometry) Buffer

func (g *Geometry) Buffer(distance float64, segments int, opts ...BufferOption) (*Geometry, error)

Buffer buffers the geometry

func (*Geometry) Close

func (g *Geometry) Close()

Close may reclaim memory from geometry. Must be called exactly once.

func (*Geometry) Contains added in v0.0.7

func (g *Geometry) Contains(other *Geometry) bool

Contains tests if this geometry contains the other geometry.

func (*Geometry) Difference added in v0.0.7

func (g *Geometry) Difference(other *Geometry, opts ...DifferenceOption) (*Geometry, error)

Difference generates a new geometry which is the region of this geometry with the region of the other geometry removed.

func (*Geometry) Empty

func (g *Geometry) Empty() bool

Empty returns true if the geometry is empty

func (*Geometry) ForceToMultiPolygon added in v0.0.7

func (g *Geometry) ForceToMultiPolygon() *Geometry

ForceToMultiPolygon convert to multipolygon.

func (*Geometry) ForceToPolygon added in v0.0.7

func (g *Geometry) ForceToPolygon() *Geometry

ForceToPolygon convert to polygon.

func (*Geometry) GML added in v0.0.7

func (g *Geometry) GML(opts ...GMLExportOption) (string, error)

GML returns the geometry in GML format. See the GDAL exportToGML doc page to determine the GML conversion options that can be set through CreationOption.

Example of conversion options :

g.GML(CreationOption("FORMAT=GML3","GML3_LONGSRS=YES"))

func (*Geometry) GeoJSON

func (g *Geometry) GeoJSON(opts ...GeoJSONOption) (string, error)

GeoJSON returns the geometry in geojson format. The geometry is expected to be in epsg:4326 projection per RFCxxx

Available GeoJSONOptions are

  • SignificantDigits(n int) to keep n significant digits after the decimal separator (default: 8)

func (*Geometry) GeometryCount added in v0.0.7

func (g *Geometry) GeometryCount() int

GeometryCount fetch the number of elements in a geometry or number of geometries in container. Only geometries of type Polygon, MultiPoint, MultiLineString, MultiPolygon or GeometryCollection may return a valid value. Other geometry types will silently return 0. For a polygon, the returned number is the number of rings (exterior ring + interior rings).

func (*Geometry) Intersection added in v0.0.7

func (g *Geometry) Intersection(other *Geometry, opts ...IntersectionOption) (*Geometry, error)

Intersection generates a new geometry which is the region of intersection of the two geometries operated on.

func (*Geometry) Intersects added in v0.0.6

func (g *Geometry) Intersects(other *Geometry, opts ...IntersectsOption) (bool, error)

Intersects determines whether two geometries intersect. If GEOS is enabled, then this is done in rigorous fashion otherwise TRUE is returned if the envelopes (bounding boxes) of the two geometries overlap.

func (*Geometry) Name added in v0.0.7

func (g *Geometry) Name() string

Name fetch WKT name for geometry type.

func (*Geometry) Reproject

func (g *Geometry) Reproject(to *SpatialRef, opts ...GeometryReprojectOption) error

Reproject reprojects the given geometry to the given SpatialRef

func (*Geometry) SetSpatialRef

func (g *Geometry) SetSpatialRef(sr *SpatialRef)

SetSpatialRef assigns the given SpatialRef to the Geometry. It does not perform an actual reprojection.

func (*Geometry) Simplify

func (g *Geometry) Simplify(tolerance float64, opts ...SimplifyOption) (*Geometry, error)

Simplify simplifies the geometry with the given tolerance

func (*Geometry) SpatialRef

func (g *Geometry) SpatialRef() *SpatialRef

SpatialRef returns the geometry's SpatialRef

func (*Geometry) SubGeometry added in v0.0.7

func (g *Geometry) SubGeometry(subGeomIndex int, opts ...SubGeometryOption) (*Geometry, error)

SubGeometry Fetch geometry from a geometry container.

func (*Geometry) Transform

func (g *Geometry) Transform(trn *Transform, opts ...GeometryTransformOption) error

Transform transforms the given geometry. g is expected to already be in the supplied Transform source SpatialRef.

func (*Geometry) Type added in v0.0.7

func (g *Geometry) Type() GeometryType

Type fetch geometry type.

func (*Geometry) Union added in v0.0.7

func (g *Geometry) Union(other *Geometry, opts ...UnionOption) (*Geometry, error)

Union generates a new geometry which is the region of union of the two geometries operated on.

func (*Geometry) Valid added in v0.0.7

func (g *Geometry) Valid() bool

Valid returns true is the geometry is valid

func (*Geometry) WKB

func (g *Geometry) WKB(opts ...GeometryWKBOption) ([]byte, error)

WKB returns the Geomtry's WKB representation

func (*Geometry) WKT

func (g *Geometry) WKT(opts ...GeometryWKTOption) (string, error)

WKT returns the Geomtry's WKT representation

type GeometryReprojectOption

type GeometryReprojectOption interface {
	// contains filtered or unexported methods
}

GeometryReprojectOption is an option passed to Geometry.Reproject()

Available options are:

  • ErrLogger

type GeometryTransformOption

type GeometryTransformOption interface {
	// contains filtered or unexported methods
}

GeometryTransformOption is an option passed to Geometry.Transform()

Available options are:

  • ErrLogger

type GeometryType

type GeometryType uint32

GeometryType is a geometry type

type GeometryWKBOption

type GeometryWKBOption interface {
	// contains filtered or unexported methods
}

GeometryWKBOption is an option passed to Geometry.WKB()

Available options are:

  • ErrLogger

type GeometryWKTOption

type GeometryWKTOption interface {
	// contains filtered or unexported methods
}

GeometryWKTOption is an option passed to Geometry.WKT()

Available options are:

  • ErrLogger

type GetGeoTransformOption

type GetGeoTransformOption interface {
	// contains filtered or unexported methods
}

GetGeoTransformOption is an option that can be passed to Dataset.GeoTransform()

Available GetGeoTransformOptions are:

  • ErrLogger

type GridCreateOption added in v0.0.8

type GridCreateOption interface {
	// contains filtered or unexported methods
}

GridCreateOption is an option that can be passed to GridCreate Available options are:

  • none yet

type GridOption added in v0.0.8

type GridOption interface {
	// contains filtered or unexported methods
}

GridOption is an option that can be passed to Dataset.Grid()

type Histogram

type Histogram struct {
	// contains filtered or unexported fields
}

Histogram is a band's histogram.

func (Histogram) Bucket

func (h Histogram) Bucket(i int) Bucket

Bucket returns the i'th bucket in the histogram. i must be between 0 and Len()-1.

func (Histogram) Len

func (h Histogram) Len() int

Len returns the number of buckets contained in the histogram

type HistogramOption

type HistogramOption interface {
	// contains filtered or unexported methods
}

HistogramOption is an option that can be passed to Band.Histogram()

Available HistogramOptions are:

  • Approximate() to allow the algorithm to operate on a subset of the full resolution data
  • Intervals(count int, min,max float64) to compute a histogram with count buckets, spanning [min,max]. Each bucket will be (max-min)/count wide. If not provided, the default histogram will be returned.
  • IncludeOutOfRange() to populate the first and last bucket with values under/over the specified min/max when used in conjuntion with Intervals()
  • ErrLogger

type IOOperation

type IOOperation C.GDALRWFlag

IOOperation determines wether Band.IO or Dataset.IO will read pixels into the provided buffer, or write pixels from the provided buffer

const (
	//IORead makes IO copy pixels from the band/dataset into the provided buffer
	IORead IOOperation = C.GF_Read
	//IOWrite makes IO copy pixels from the provided buffer into the band/dataset
	IOWrite = C.GF_Write
)

type IntersectionOption added in v0.0.7

type IntersectionOption interface {
	// contains filtered or unexported methods
}

IntersectionOption is an option passed to Geometry.Intersection()

Available options are:

  • ErrLogger

type IntersectsOption added in v0.0.6

type IntersectsOption interface {
	// contains filtered or unexported methods
}

IntersectsOption is an option passed to Geometry.Intersects()

Available options are:

  • ErrLogger

type KeyMultiReader added in v0.0.5

type KeyMultiReader interface {
	ReadAtMulti(key string, bufs [][]byte, offs []int64) ([]int, error)
}

KeyMultiReader is an optional interface that can be implemented by KeyReaderAtSizer that will be used (only?) by the GTiff driver when reading pixels. If not provided, this VSI implementation will concurrently call ReadAt(key,[]byte,int64)

type KeySizerReaderAt added in v0.0.5

type KeySizerReaderAt interface {
	ReadAt(key string, buf []byte, off int64) (int, error)
	Size(key string) (int64, error)
}

KeySizerReaderAt is the interface expected when calling RegisterVSIHandler

ReadAt() is a standard io.ReaderAt that takes a key (i.e. filename) as argument.

Size() is used as a probe to determine wether the given key exists, and should return an error if no such key exists. The actual file size may or may not be effectively used depending on the underlying GDAL driver opening the file

It may also optionally implement KeyMultiReader which will be used (only?) by the GTiff driver when reading pixels. If not provided, this VSI implementation will concurrently call ReadAt([]byte,int64)

type Layer

type Layer struct {
	// contains filtered or unexported fields
}

Layer wraps an OGRLayerH

func (Layer) Bounds added in v0.0.7

func (layer Layer) Bounds(opts ...BoundsOption) ([4]float64, error)

Bounds returns the layer's envelope in the order minx,miny,maxx,maxy

func (Layer) ClearMetadata added in v0.0.6

func (mo Layer) ClearMetadata(opts ...MetadataOption) error

func (Layer) CreateFeature added in v0.0.7

func (layer Layer) CreateFeature(feat *Feature, opts ...CreateFeatureOption) error

CreateFeature creates a feature on Layer

func (Layer) DeleteFeature

func (layer Layer) DeleteFeature(feat *Feature, opts ...DeleteFeatureOption) error

DeleteFeature deletes feature from the Layer.

func (Layer) Description added in v0.0.7

func (mo Layer) Description() string

Description returns the description/name

func (Layer) FeatureCount

func (layer Layer) FeatureCount(opts ...FeatureCountOption) (int, error)

FeatureCount returns the number of features in the layer

func (Layer) Metadata

func (mo Layer) Metadata(key string, opts ...MetadataOption) string

func (Layer) MetadataDomains

func (mo Layer) MetadataDomains() []string

func (Layer) Metadatas

func (mo Layer) Metadatas(opts ...MetadataOption) map[string]string

func (Layer) Name added in v0.0.7

func (layer Layer) Name() string

Name returns the layer name

func (Layer) NewFeature

func (layer Layer) NewFeature(geom *Geometry, opts ...NewFeatureOption) (*Feature, error)

NewFeature creates a feature on Layer from a geometry

func (Layer) NextFeature

func (layer Layer) NextFeature() *Feature

NextFeature returns the layer's next feature, or nil if there are no mo features

func (Layer) ResetReading

func (layer Layer) ResetReading()

ResetReading makes Layer.NextFeature return the first feature of the layer

func (Layer) SetDescription added in v0.0.7

func (mo Layer) SetDescription(description string, opts ...SetDescriptionOption) error

SetDescription sets the description

func (Layer) SetGeometryColumnName added in v0.0.11

func (layer Layer) SetGeometryColumnName(name string, opts ...SetGeometryColumnNameOption) error

SetGeometryColumnName set the name of feature first geometry field. Only supported when running with GDAL 3.6+.

func (Layer) SetMetadata

func (mo Layer) SetMetadata(key, value string, opts ...MetadataOption) error

func (Layer) SpatialRef

func (layer Layer) SpatialRef() *SpatialRef

SpatialRef returns dataset projection.

func (Layer) Type added in v0.0.7

func (layer Layer) Type() GeometryType

Type returns the layer geometry type.

func (Layer) UpdateFeature

func (layer Layer) UpdateFeature(feat *Feature, opts ...UpdateFeatureOption) error

UpdateFeature rewrites an updated feature in the Layer

type LibVersion

type LibVersion int

LibVersion is the GDAL lib versioning scheme

func Version

func Version() LibVersion

Version returns the runtime version of the gdal library

func (LibVersion) Major

func (lv LibVersion) Major() int

Major returns the GDAL major version (e.g. "3" in 3.2.1)

func (LibVersion) Minor

func (lv LibVersion) Minor() int

Minor return the GDAL minor version (e.g. "2" in 3.2.1)

func (LibVersion) Revision

func (lv LibVersion) Revision() int

Revision returns the GDAL revision number (e.g. "1" in 3.2.1)

type MetadataOption

type MetadataOption interface {
	// contains filtered or unexported methods
}

MetadataOption is an option that can be passed to metadata related calls Available MetadataOptions are:

  • Domain

type NearblackOption added in v0.0.9

type NearblackOption interface {
	// contains filtered or unexported methods
}

NearblackOption is an option that can be passed to Dataset.Nearblack()

type NewFeatureOption

type NewFeatureOption interface {
	// contains filtered or unexported methods
}

NewFeatureOption is an option that can be passed to Layer.NewFeature

Available options are:

  • none yet

type NewGeometryOption

type NewGeometryOption interface {
	// contains filtered or unexported methods
}

NewGeometryOption is an option passed when creating a geometry

Available options are:

  • ErrLogger

type OpenOption

type OpenOption interface {
	// contains filtered or unexported methods
}

OpenOption is an option passed to Open()

Available OpenOptions are:

  • Drivers
  • SiblingFiles
  • Shared
  • ConfigOption
  • Update
  • DriverOpenOption
  • RasterOnly
  • VectorOnly

type PaletteInterp

type PaletteInterp C.GDALPaletteInterp

PaletteInterp defines the color interpretation of a ColorTable

const (
	//GrayscalePalette is a grayscale palette with a single component per entry
	GrayscalePalette PaletteInterp = C.GPI_Gray
	//RGBPalette is a RGBA palette with 4 components per entry
	RGBPalette PaletteInterp = C.GPI_RGB
	//CMYKPalette is a CMYK palette with 4 components per entry
	CMYKPalette PaletteInterp = C.GPI_CMYK
	//HLSPalette is a HLS palette with 3 components per entry
	HLSPalette PaletteInterp = C.GPI_HLS
)

type PolygonizeOption

type PolygonizeOption interface {
	// contains filtered or unexported methods
}

PolygonizeOption is an option to modify the default behavior of band.Polygonize

Available PolygonizeOptions are:

  • EightConnected() to enable 8-connectivity. Leave out completely for 4-connectivity (default)
  • PixelValueFieldIndex(fieldidx) to populate the fieldidx'th field of the output dataset with the polygon's pixel value
  • Mask(band) to use given band as nodata mask instead of the internal nodata mask

type RasterizeGeometryOption

type RasterizeGeometryOption interface {
	// contains filtered or unexported methods
}

RasterizeGeometryOption is an option that can be passed tp Dataset.RasterizeGeometry()

type RasterizeIntoOption added in v0.0.7

type RasterizeIntoOption interface {
	// contains filtered or unexported methods
}

RasterizeIntoOption is an option that can be passed to DatasetRasterizeInto()

Available RasterizeOptions are:

  • ConfigOption
  • ErrLogger

type RasterizeOption

type RasterizeOption interface {
	// contains filtered or unexported methods
}

RasterizeOption is an option that can be passed to Rasterize()

Available RasterizeOptions are:

  • CreationOption
  • ConfigOption
  • DriverName
  • ErrLogger

type RegisterPluginOption added in v0.0.9

type RegisterPluginOption interface {
	// contains filtered or unexported methods
}

RegisterPluginOption is an option that can be passed to RegisterPlugin()

type ResamplingAlg

type ResamplingAlg int

ResamplingAlg is a resampling method

const (
	//Nearest resampling
	Nearest ResamplingAlg = iota
	// Bilinear resampling
	Bilinear
	// Cubic resampling
	Cubic
	// CubicSpline resampling
	CubicSpline
	// Lanczos resampling
	Lanczos
	// Average resampling
	Average
	// Gauss resampling
	Gauss
	// Mode resampling
	Mode
	// Max resampling
	Max
	// Min resampling
	Min
	// Median resampling
	Median
	// Sum resampling
	Sum
	// Q1 resampling
	Q1
	// Q3 resampling
	Q3
)

func (ResamplingAlg) String

func (ra ResamplingAlg) String() string

type SetColorInterpOption

type SetColorInterpOption interface {
	// contains filtered or unexported methods
}

SetColorInterpOption is an option that can be passed to Band.SetColorInterpretation()

Available SetColorInterpOption are:

  • ErrLogger

type SetColorTableOption

type SetColorTableOption interface {
	// contains filtered or unexported methods
}

SetColorTableOption is an option that can be passed to Band.SetColorTable()

Available SetColorTableOption are:

  • ErrLogger

type SetDescriptionOption added in v0.0.7

type SetDescriptionOption interface {
	// contains filtered or unexported methods
}

SetDescriptionOption is an option that can be passed to SetDescription Available SetDescriptionOptions are:

  • ErrLogger

type SetFieldValueOption added in v0.0.7

type SetFieldValueOption interface {
	// contains filtered or unexported methods
}

SetFieldValueOption is an option passed to Feature.SetFieldValue()

Available options are:

  • ErrLogger

type SetGCPsOption added in v0.0.9

type SetGCPsOption interface {
	// contains filtered or unexported methods
}

SetGCPsOption is an option that can be passed to Dataset.SetGCPs()

type SetGeoTransformOption

type SetGeoTransformOption interface {
	// contains filtered or unexported methods
}

SetGeoTransformOption is an option that can be passed to Dataset.SetGeoTransform()

Available SetGeoTransformOptions are:

  • ErrLogger

type SetGeometryColumnNameOption added in v0.0.11

type SetGeometryColumnNameOption interface {
	// contains filtered or unexported methods
}

SetGeometryColumnNameOption is an option passed to Layer.SetGeometryColumnName() or Feature.SetGeometryColumnName()

Available options are:

  • ErrLogger

type SetGeometryOption

type SetGeometryOption interface {
	// contains filtered or unexported methods
}

SetGeometryOption is an option passed to Feature.SetGeometry()

Available options are:

  • ErrLogger

type SetNoDataOption

type SetNoDataOption interface {
	// contains filtered or unexported methods
}

SetNoDataOption is an option that can be passed to Band.SetNodata(), Band.ClearNodata(), Dataset.SetNodata()

Available SetNoDataOptions are:

  • ErrLogger

type SetProjectionOption

type SetProjectionOption interface {
	// contains filtered or unexported methods
}

SetProjectionOption is an option that can be passed to Dataset.SetProjection

Available SetProjection are:

  • ErrLogger

type SetScaleOffsetOption added in v0.0.7

type SetScaleOffsetOption interface {
	// contains filtered or unexported methods
}

SetScaleOffsetOption is an option that can be passed to Band.SetScaleOffset(), Band.ClearScaleOffset(), Dataset.SetScaleOffset()

Available SetScaleOffsetOptions are:

  • ErrLogger

type SetSpatialRefOption

type SetSpatialRefOption interface {
	// contains filtered or unexported methods
}

SetSpatialRefOption is an option that can be passed to Dataset.SetSpatialRef

Available SetProjection are:

  • ErrLogger

type SetStatisticsOption added in v0.0.6

type SetStatisticsOption interface {
	// contains filtered or unexported methods
}

SetStatistics is an option that can passed to Band.SetStatistics() Available options are:

-ErrLogger

type SieveFilterOption added in v0.0.3

type SieveFilterOption interface {
	// contains filtered or unexported methods
}

SieveFilterOption is an option to modify the behavior of Band.SieveFilter

Available SieveFilterOptions are:

  • EightConnected() to enable 8-connectivity. Leave out completely for 4-connectivity (default)
  • Mask(band) to use given band as nodata mask instead of the internal nodata mask
  • NoMask() to ignore the the source band's nodata value or mask band
  • Destination(band) where to output the sieved band, instead of updating in-place

type SimplifyOption

type SimplifyOption interface {
	// contains filtered or unexported methods
}

SimplifyOption is an option passed to Geometry.Simplify()

Available options are:

  • ErrLogger

type SpatialRef

type SpatialRef struct {
	// contains filtered or unexported fields
}

SpatialRef is a wrapper around OGRSpatialReferenceH

func NewSpatialRef added in v0.0.7

func NewSpatialRef(userInput string, opts ...CreateSpatialRefOption) (*SpatialRef, error)

NewSpatialRef creates a SpatialRef from any "user" projection string, e.g. "epsg:4326", "+proj=lonlat", wkt, wkt2 or projjson (as supported by gdal's OSRCreateFromUserInput

func NewSpatialRefFromEPSG

func NewSpatialRefFromEPSG(code int, opts ...CreateSpatialRefOption) (*SpatialRef, error)

NewSpatialRefFromEPSG creates a SpatialRef from an epsg code

func NewSpatialRefFromProj4

func NewSpatialRefFromProj4(proj string, opts ...CreateSpatialRefOption) (*SpatialRef, error)

NewSpatialRefFromProj4 creates a SpatialRef from a proj4 string

func NewSpatialRefFromWKT

func NewSpatialRefFromWKT(wkt string, opts ...CreateSpatialRefOption) (*SpatialRef, error)

NewSpatialRefFromWKT creates a SpatialRef from an opengis WKT description

func (*SpatialRef) AttrValue added in v0.0.7

func (sr *SpatialRef) AttrValue(name string, child int) (string, bool)

AttrValue Fetch indicated attribute of named node from within the WKT tree.

func (*SpatialRef) AuthorityCode

func (sr *SpatialRef) AuthorityCode(target string) string

AuthorityCode is used to query an AUTHORITY[] node from within the WKT tree, and fetch the code value. target is the partial or complete path to the node to get an authority from. i.e. "PROJCS", "GEOGCS", "GEOGCS|UNIT" or "" to search for an authority node on the root element.

While in theory values may be non-numeric, for the EPSG authority all code values should be integral.

func (*SpatialRef) AuthorityName

func (sr *SpatialRef) AuthorityName(target string) string

AuthorityName is used to query an AUTHORITY[] node from within the WKT tree, and fetch the authority name value.

target is the partial or complete path to the node to get an authority from. i.e. "PROJCS", "GEOGCS", "GEOGCS|UNIT" or "" to search for an authority node on the root element.

func (*SpatialRef) AutoIdentifyEPSG

func (sr *SpatialRef) AutoIdentifyEPSG() error

AutoIdentifyEPSG sets EPSG authority info if possible.

func (*SpatialRef) Close

func (sr *SpatialRef) Close()

Close releases memory

func (*SpatialRef) EPSGTreatsAsLatLong added in v0.0.7

func (sr *SpatialRef) EPSGTreatsAsLatLong() bool

EPSGTreatsAsLatLong returns TRUE if EPSG feels the SpatialRef should be treated as having lat/long coordinate ordering.

func (*SpatialRef) Geographic

func (sr *SpatialRef) Geographic() bool

Geographic returns wether the SpatialRef is geographic

func (*SpatialRef) IsSame

func (sr *SpatialRef) IsSame(other *SpatialRef) bool

IsSame returns whether two SpatiaRefs describe the same projection.

func (*SpatialRef) Projected added in v0.0.7

func (sr *SpatialRef) Projected() bool

Projected returns wether the SpatialRef is projected

func (*SpatialRef) SemiMajor

func (sr *SpatialRef) SemiMajor() (float64, error)

SemiMajor returns the SpatialRef's Semi Major Axis

func (*SpatialRef) SemiMinor

func (sr *SpatialRef) SemiMinor() (float64, error)

SemiMinor returns the SpatialRef's Semi Minor Axis

func (*SpatialRef) Validate added in v0.0.7

func (sr *SpatialRef) Validate(opts ...SpatialRefValidateOption) error

Validate SRS tokens.

func (*SpatialRef) WKT

func (sr *SpatialRef) WKT(opts ...WKTExportOption) (string, error)

WKT returns spatialrefernece as WKT

type SpatialRefValidateOption added in v0.0.7

type SpatialRefValidateOption interface {
	// contains filtered or unexported methods
}

SpatialRefValidateOption is an option that can be passed to SpatialRef.Validate()

Available SpatialRefValidateOptions are:

  • ErrLogger

type Statistics added in v0.0.6

type Statistics struct {
	Min, Max, Mean, Std float64
	Approximate         bool
}

Statisitics on a given band.

type StatisticsOption added in v0.0.6

type StatisticsOption interface {
	// contains filtered or unexported methods
}

StatisticsOption is an option that can be passed to Band.Statistics

Available Statistics options are: - Aproximate() to allow the satistics to be computed on overviews or a subset of all tiles. - ErrLogger

type SubGeometryOption added in v0.0.7

type SubGeometryOption interface {
	// contains filtered or unexported methods
}

SubGeometryOption is an option passed to Geometry.SubGeometry()

Available options are:

  • ErrLogger

type Transform

type Transform struct {
	// contains filtered or unexported fields
}

Transform transforms coordinates from one SpatialRef to another

func NewTransform

func NewTransform(src, dst *SpatialRef, opts ...TransformOption) (*Transform, error)

NewTransform creates a transformation object from src to dst

func (*Transform) Close

func (trn *Transform) Close()

Close releases the Transform object

func (*Transform) TransformEx

func (trn *Transform) TransformEx(x []float64, y []float64, z []float64, successful []bool) error

TransformEx reprojects points in place

x and y may not be nil and must be of the same length

z may be nil, or of the same length as x and y

successful may be nil or of the same length as x and y. If non nil, it will contain true or false depending on wether the corresponding point succeeded transformation or not.

TODO: create a version of this function that accepts *C.double to avoid allocs? TODO: create a Transform() method that accepts z and successful as options

type TransformOption

type TransformOption interface {
	// contains filtered or unexported methods
}

TransformOption is an option that can be passed to NewTransform

Available TransformOptions are:

  • ErrLogger

type UnionOption added in v0.0.7

type UnionOption interface {
	// contains filtered or unexported methods
}

UnionOption is an option passed to Geometry.Union()

Available options are:

  • ErrLogger

type UpdateFeatureOption

type UpdateFeatureOption interface {
	// contains filtered or unexported methods
}

UpdateFeatureOption is an option passed to Layer.UpdateFeature()

Available options are:

  • ErrLogger

type VSIFile

type VSIFile struct {
	// contains filtered or unexported fields
}

VSIFile is a handler around gdal's vsi handlers

func VSIOpen

func VSIOpen(path string, opts ...VSIOpenOption) (*VSIFile, error)

VSIOpen opens path. path can be virtual, eg beginning with /vsimem/

func (*VSIFile) Close

func (vf *VSIFile) Close() error

Close closes the VSIFile. Must be called exactly once.

func (*VSIFile) Read

func (vf *VSIFile) Read(buf []byte) (int, error)

Read is the standard io.Reader interface

type VSIHandlerOption

type VSIHandlerOption interface {
	// contains filtered or unexported methods
}

VSIHandlerOption is an option that can be passed to RegisterVSIHandler

func VSIHandlerBufferSize

func VSIHandlerBufferSize(s int) VSIHandlerOption

VSIHandlerBufferSize sets the size of the gdal-native block size used for caching. Must be positive, can be set to 0 to disable this behavior (not recommended).

Defaults to 64Kb

func VSIHandlerCacheSize

func VSIHandlerCacheSize(s int) VSIHandlerOption

VSIHandlerCacheSize sets the total number of gdal-native bytes used as cache *per handle*. Defaults to 128Kb.

func VSIHandlerStripPrefix added in v0.0.4

func VSIHandlerStripPrefix(v bool) VSIHandlerOption

VSIHandlerStripPrefix allows to strip the prefix of the key when calling the underlying VSIKeyReader.

type VSIOpenOption

type VSIOpenOption interface {
	// contains filtered or unexported methods
}

VSIOpenOption is an option passed to VSIOpen()

Available options are:

  • ErrLogger

type VSIUnlinkOption

type VSIUnlinkOption interface {
	// contains filtered or unexported methods
}

VSIUnlinkOption is an option passed to VSIUnlink()

Available options are:

  • ErrLogger

type WKTExportOption

type WKTExportOption interface {
	// contains filtered or unexported methods
}

WKTExportOption is an option that can be passed to SpatialRef.WKT()

Available WKTExportOptions are:

  • ErrLogger

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL