### Validate Geometry Properties in Go Source: https://context7.com/spatial-go/geoos/llms.txt Provides Go code examples for validating geometric properties such as simplicity, closed status, and emptiness, as well as extracting properties like length, boundary, and envelope. It utilizes the 'wkt' and 'planar' packages from the geoos library. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Test various geometry properties line, _ := wkt.UnmarshalString(`LINESTRING(0 0, 1 1, 2 2)`) // Check if geometry is simple (no self-intersections) isSimple, _ := strategy.IsSimple(line) fmt.Printf("Line is simple: %v\n", isSimple) // Check if line is closed (start equals end) isClosed, _ := strategy.IsClosed(line) fmt.Printf("Line is closed: %v\n", isClosed) // Check if line is a ring (closed and simple) isRing, _ := strategy.IsRing(line) fmt.Printf("Line is ring: %v\n", isRing) // Test with a closed ring ring, _ := wkt.UnmarshalString(`LINESTRING(0 0, 4 0, 4 4, 0 4, 0 0)`) ringClosed, _ := strategy.IsClosed(ring) ringIsRing, _ := strategy.IsRing(ring) fmt.Printf("\nRing is closed: %v\n", ringClosed) fmt.Printf("Ring is ring: %v\n", ringIsRing) // Check if geometry is empty isEmpty, _ := strategy.IsEmpty(line) fmt.Printf("Line is empty: %v\n", isEmpty) // Get length of line length, _ := strategy.Length(line) fmt.Printf("Line length: %f\n", length) // Get number of geometries (for collections) numGeom, _ := strategy.NGeometry(line) fmt.Printf("Number of geometries: %d\n", numGeom) // Get boundary of geometry boundary, _ := strategy.Boundary(line) fmt.Printf("Boundary: %s\n", wkt.MarshalString(boundary)) // Get envelope (bounding box) envelope, _ := strategy.Envelope(line) fmt.Printf("Envelope: %s\n", wkt.MarshalString(envelope)) } ``` -------------------------------- ### Coordinate Transformation: Lat/Lon to Mercator in Go Source: https://context7.com/spatial-go/geoos/llms.txt Demonstrates transforming coordinates between different systems, specifically from Latitude/Longitude to the Mercator projection and back. It also shows how to transform single points, multiple points, and lines using the geoos library. Requires the 'geoos/algorithm/matrix' and 'geoos/coordtransform' packages. ```go package main import ( "fmt" "github.com/spatial-go/geoos/algorithm/matrix" "github.com/spatial-go/geoos/coordtransform" ) func main() { // Create transformer for converting between coordinate systems // Transform from Lat/Lon to Mercator projection llToMercator := coordtransform.NewTransformer(coordtransform.LLTOMERCATOR) lon, lat := -73.935242, 40.730610 // New York coordinates mercatorX, mercatorY := llToMercator.TransformLatLng(lon, lat) fmt.Printf("Lat/Lon: [%f, %f]\n", lon, lat) fmt.Printf("Mercator: [%f, %f]\n", mercatorX, mercatorY) // Transform from Mercator back to Lat/Lon mercatorToLL := coordtransform.NewTransformer(coordtransform.MERCATORTOLL) origLon, origLat := mercatorToLL.TransformLatLng(mercatorX, mercatorY) fmt.Printf("Back to Lat/Lon: [%f, %f]\n", origLon, origLat) // Transform a point using matrix point := matrix.Matrix{-118.243683, 34.052235} // Los Angeles transformedPoint := llToMercator.TransformPoint(point) fmt.Printf("Transformed point: %v\n", transformedPoint) // Transform multiple points multiPoint := []matrix.Matrix{ {0, 0}, {-73.935242, 40.730610}, {-118.243683, 34.052235}, } transformedMulti := llToMercator.TransformMultiPoint(multiPoint) fmt.Printf("Transformed multiple points: %v\n", transformedMulti) // Transform a line line := matrix.LineMatrix{ {0, 0}, {10, 10}, {20, 20}, } transformedLine := llToMercator.TransformLine(line) fmt.Printf("Transformed line: %v\n", transformedLine) } ``` -------------------------------- ### Build Spatial Index with HPR-tree in Go Source: https://context7.com/spatial-go/geoos/llms.txt Demonstrates how to build a spatial index using the HPR-tree data structure in Go for efficient geometric queries. It covers inserting points with their bounding boxes and querying based on a search envelope. Dependencies include the 'hprtree', 'envelope', and 'space' packages from the geoos library. ```go package main import ( "fmt" "github.com/spatial-go/geoos/algorithm/matrix/envelope" "github.com/spatial-go/geoos/index/hprtree" "github.com/spatial-go/geoos/space" ) func main() { // Create Hilbert-Packed R-tree index tree := hprtree.NewHPRTree() // Insert geometries with their bounding boxes points := []space.Point{ {0, 0}, {1, 1}, {5, 5}, {10, 10}, {15, 15}, {20, 20}, } for i, pt := range points { // Create envelope (bounding box) for each point env := &envelope.Envelope{ MinX: pt.Lon() - 0.1, MinY: pt.Lat() - 0.1, MaxX: pt.Lon() + 0.1, MaxY: pt.Lat() + 0.1, } // Insert into spatial index with associated data err := tree.Insert(env, map[string]interface{}{ "id": i, "point": pt, "name": fmt.Sprintf("Point_%d", i), }) if err != nil { fmt.Printf("Error inserting into index: %v\n", err) return } } fmt.Printf("Inserted %d items into spatial index\n", tree.Size()) // Query spatial index with search envelope searchEnv := &envelope.Envelope{ MinX: 4, MinY: 4, MaxX: 11, MaxY: 11, } results := tree.Query(searchEnv) fmt.Printf("\nQuery results for envelope [%f,%f,%f,%f]:\n", searchEnv.MinX, searchEnv.MinY, searchEnv.MaxX, searchEnv.MaxY) if resultSlice, ok := results.([]interface{}); ok { fmt.Printf("Found %d items\n", len(resultSlice)) for _, item := range resultSlice { fmt.Printf(" Item: %v\n", item) } } } ``` -------------------------------- ### Geometry Simplification: Douglas-Peucker in Go Source: https://context7.com/spatial-go/geoos/llms.txt Illustrates simplifying complex geometries, such as lines and polygons, using the Douglas-Peucker algorithm. It demonstrates both a standard simplification that may alter topology and a topology-preserving version (SimplifyP). Requires the 'geoos/geoencoding/wkt' and 'geoos/planar' packages. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Complex line with many vertices complexLine, _ := wkt.UnmarshalString( `LINESTRING(0 0, 1 0.1, 2 -0.1, 3 0.1, 4 -0.1, 5 0, 10 0, 15 5, 20 5)`, ) // Simplify - may not preserve topology tolerance := 0.5 simplified, err := strategy.Simplify(complexLine, tolerance) if err != nil { fmt.Printf("Error simplifying: %v\n", err) return } fmt.Printf("Original: %s\n", wkt.MarshalString(complexLine)) fmt.Printf("Simplified: %s\n", wkt.MarshalString(simplified)) // SimplifyP - preserves topology (important for polygons) complexPolygon, _ := wkt.UnmarshalString( `POLYGON((0 0, 1 0, 1.1 0.1, 2 0, 3 0, 3 1, 3 2, 3 3, 2 3, 1 3, 0 3, 0 2, 0 1, 0 0))`, ) simplifiedPolygon, err := strategy.SimplifyP(complexPolygon, 0.5) if err != nil { fmt.Printf("Error in topology-preserving simplification: %v\n", err) return } fmt.Printf("Original polygon vertices: %d\n", complexPolygon.Nums()) fmt.Printf("Simplified polygon: %s\n", wkt.MarshalString(simplifiedPolygon)) } ``` -------------------------------- ### Create Buffer Zones Around Geometries - Go Source: https://context7.com/spatial-go/geoos/llms.txt Generates buffer zones around geometric shapes (points, lines) with specified distance and quality parameters. Supports both planar and geographic coordinates (in meters). Dependencies include `fmt`, `wkt` for parsing, `planar` and `buffer` for operations. The function `Buffer` takes a geometry, distance, and segments per quadrant, while `BufferInMeter` handles geographic coordinates. ```go package main import ( "fmt" "github.com/spatial-go/geoos/algorithm/buffer" "github.com/spatial-go/geoos/algorithm/matrix" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" "github.com/spatial-go/geoos/space" ) func main() { strategy := planar.NormalStrategy() // Buffer a point - creates a circular polygon point, _ := wkt.UnmarshalString(`POINT(0 0)`) bufferedPoint := strategy.Buffer(point, 5.0, 8) // 5 units radius, 8 segments per quadrant fmt.Printf("Buffered point: %s\n", wkt.MarshalString(bufferedPoint)) // Buffer a line - creates a corridor line, _ := wkt.UnmarshalString(`LINESTRING(0 0, 10 0, 10 10)`) bufferedLine := strategy.Buffer(line, 2.0, 8) // 2 units on each side fmt.Printf("Buffered line type: %s\n", bufferedLine.GeoJSONType()) // Buffer using matrix directly for more control pointMatrix := matrix.Matrix{5.0, 5.0} bufferedMatrix := buffer.Buffer(pointMatrix, 3.0, 16) fmt.Printf("Direct buffer result: %v\n", bufferedMatrix) // Buffer in meters (for geographic coordinates) geoPoint := space.Point{-73.935242, 40.730610} // New York coordinates bufferedInMeters := strategy.BufferInMeter(geoPoint, 1000, 8) // 1km buffer fmt.Printf("Buffered in meters: %s\n", wkt.MarshalString(bufferedInMeters)) } ``` -------------------------------- ### Generate Hexagonal and Square Grids in Go Source: https://context7.com/spatial-go/geoos/llms.txt Illustrates the creation of hexagonal and square grids within a specified bounding box using the geoos library. The `HexagonGrid` and `SquareGrid` functions allow for defining cell size in meters. ```Go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/grid" "github.com/spatial-go/geoos/space" ) func main() { // Define bounding box for grid generation bound := space.Bound{ Min: space.Point{-74.0, 40.7}, // Southwest corner (lon, lat) Max: space.Point{-73.9, 40.8}, // Northeast corner } // Generate hexagonal grid cellSizeKm := 0.5 // 500 meters hexGrid := grid.HexagonGrid(bound, cellSizeKm*1000) // convert to meters fmt.Printf("Hexagonal grid generated:\n") fmt.Printf(" Columns: %d\n", len(hexGrid)) if len(hexGrid) > 0 { fmt.Printf(" Rows in first column: %d\n", len(hexGrid[0])) fmt.Printf(" Total cells: %d\n", len(hexGrid)*len(hexGrid[0])) // Print first cell geometry if len(hexGrid[0]) > 0 { firstCell := hexGrid[0][0] fmt.Printf(" First cell: %s\n", wkt.MarshalString(firstCell.Geometry)) } } // Generate square grid squareGrid := grid.SquareGrid(bound, cellSizeKm*1000) fmt.Printf("\nSquare grid generated:\n") fmt.Printf(" Columns: %d\n", len(squareGrid)) if len(squareGrid) > 0 { fmt.Printf(" Rows in first column: %d\n", len(squareGrid[0])) fmt.Printf(" Total cells: %d\n", len(squareGrid)*len(squareGrid[0])) // Access individual cells for i := 0; i < min(3, len(squareGrid)); i++ { for j := 0; j < min(3, len(squareGrid[i])); j++ { cell := squareGrid[i][j] fmt.Printf(" Cell [%d,%d]: %s\n", i, j, wkt.MarshalString(cell.Geometry)) } } } } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Calculate Convex Hull and Centroid of Geometries in Go Source: https://context7.com/spatial-go/geoos/llms.txt Demonstrates how to compute the convex hull and centroid for multi-point and polygon geometries using the geoos library. It utilizes the `planar.NormalStrategy` for calculations and `wkt` for unmarshalling and marshalling geometries. ```Go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Create a multi-point geometry multiPoint, _ := wkt.UnmarshalString( `MULTIPOINT((0 0), (1 1), (2 0), (1 -1), (1.5 0.5), (0.5 0.5))`, ) // Calculate convex hull - smallest convex polygon containing all points hull, err := strategy.ConvexHull(multiPoint) if err != nil { fmt.Printf("Error calculating convex hull: %v\n", err) return } fmt.Printf("Convex hull: %s\n", wkt.MarshalString(hull)) // Calculate centroid - geometric center centroid, err := strategy.Centroid(multiPoint) if err != nil { fmt.Printf("Error calculating centroid: %v\n", err) return } fmt.Printf("Centroid: %s\n", wkt.MarshalString(centroid)) // Works with polygons too polygon, _ := wkt.UnmarshalString(`POLYGON((0 0, 4 0, 4 3, 0 3, 0 0))`) polyCentroid, _ := strategy.Centroid(polygon) fmt.Printf("Polygon centroid: %s\n", wkt.MarshalString(polyCentroid)) // Expected: POINT(2 1.5) } ``` -------------------------------- ### Perform DBSCAN Clustering on Point Datasets in Go Source: https://context7.com/spatial-go/geoos/llms.txt Implements DBSCAN (Density-Based Spatial Clustering of Applications with Noise) for point datasets using the geoos library. It takes a list of points, an epsilon (maximum distance), and a minimum number of points to form a cluster. ```Go package main import ( "fmt" "github.com/spatial-go/geoos/clusters" "github.com/spatial-go/geoos/clusters/dbscan" "github.com/spatial-go/geoos/space" ) func main() { // Create a set of points to cluster points := clusters.PointList{ space.Point{0, 0}, space.Point{0.5, 0.5}, space.Point{1, 1}, space.Point{10, 10}, space.Point{10.5, 10.5}, space.Point{11, 11}, space.Point{20, 20}, // noise point } // DBSCAN parameters: // eps: maximum distance between points in a cluster (in km) // minPoints: minimum number of points to form a cluster eps := 2.0 // 2 km radius minPoints := 2 clusterArray, noise := dbscan.DBScan(points, eps, minPoints) fmt.Printf("Found %d clusters\n", len(clusterArray)) for i, cluster := range clusterArray { fmt.Printf("\nCluster %d (ID: %d):\n", i, cluster.C) fmt.Printf(" Center: [%f, %f]\n", cluster.Center.Lon(), cluster.Center.Lat()) fmt.Printf(" Points: %d\n", len(cluster.Points)) for _, idx := range cluster.Points { point := points[idx] fmt.Printf(" - [%f, %f]\n", point.Lon(), point.Lat()) } } fmt.Printf("\nNoise points: %v\n", noise) for _, idx := range noise { fmt.Printf(" - [%f, %f]\n", points[idx].Lon(), points[idx].Lat()) } } ``` -------------------------------- ### Calculate Area using Geoos Planar Package in Go Source: https://github.com/spatial-go/geoos/blob/main/README.md This Go code snippet demonstrates how to calculate the area of a polygon using the Geoos library. It initializes a planar strategy, reads polygon data in WKT format using geoencoding, and then computes the area. Ensure the 'geoencoding' and 'planar' packages are imported. ```go package main import ( "bytes" "fmt" "github.com/spatial-go/geoos/geoencoding" "github.com/spatial-go/geoos/planar" ) func main() { // First, choose the default algorithm. strategy := planar.NormalStrategy() // Secondly, manufacturing test data and convert it to geometry const polygon = `POLYGON((-1 -1, 1 -1, 1 1, -1 1, -1 -1))` // geometry, _ := wkt.UnmarshalString(polygon) buf0 := new(bytes.Buffer) buf0.Write([]byte(polygon)) geometry, _ := geoencoding.Read(buf0, geoencoding.WKT) // Last, call the Area () method and get result. area, e := strategy.Area(geometry) if e != nil { fmt.Printf(e.Error()) } fmt.Printf("%f", area) // get result 4.0 } ``` -------------------------------- ### Calculate Polygon Area using Planar Strategy in Go Source: https://context7.com/spatial-go/geoos/llms.txt Computes the area of a polygon by parsing a WKT string and applying the planar strategy. Requires the 'geoos/geoencoding' and 'geoos/planar' packages. Input is a WKT polygon string, output is the calculated area. ```go package main import ( "bytes" "fmt" "github.com/spatial-go/geoos/geoencoding" "github.com/spatial-go/geoos/planar" ) func main() { // Initialize the spatial algorithm strategy strategy := planar.NormalStrategy() // Define a square polygon in WKT format const polygon = `POLYGON((-1 -1, 1 -1, 1 1, -1 1, -1 -1))` // Parse the WKT string into a geometry object buf := new(bytes.Buffer) buf.Write([]byte(polygon)) geometry, err := geoencoding.Read(buf, geoencoding.WKT) if err != nil { fmt.Printf("Error parsing geometry: %v\n", err) return } // Calculate the area area, err := strategy.Area(geometry) if err != nil { fmt.Printf("Error calculating area: %v\n", err) return } fmt.Printf("Polygon area: %f\n", area) // Output: Polygon area: 4.000000 } ``` -------------------------------- ### Spatial Predicates: Contains, Intersects, Within in Go Source: https://context7.com/spatial-go/geoos/llms.txt Demonstrates testing spatial relationships between geometries like polygons and points using the geoos library. It showcases functions such as Contains, Within, Intersects, Disjoint, Touches, and Overlaps. Requires the 'geoos/geoencoding/wkt' and 'geoos/planar' packages. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Define geometries for testing outerPolygon, _ := wkt.UnmarshalString(`POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))`) innerPoint, _ := wkt.UnmarshalString(`POINT(5 5)`) outsidePoint, _ := wkt.UnmarshalString(`POINT(15 15)`) overlappingPoly, _ := wkt.UnmarshalString(`POLYGON((5 5, 15 5, 15 15, 5 15, 5 5))`) // Contains - check if geometry fully contains another contains, err := strategy.Contains(outerPolygon, innerPoint) if err == nil { fmt.Printf("Polygon contains inner point: %v\n", contains) // true } // Within - inverse of Contains within, err := strategy.Within(innerPoint, outerPolygon) if err == nil { fmt.Printf("Inner point within polygon: %v\n", within) // true } // Intersects - check if geometries share any space intersects, err := strategy.Intersects(outerPolygon, overlappingPoly) if err == nil { fmt.Printf("Polygons intersect: %v\n", intersects) // true } // Disjoint - check if geometries do not intersect disjoint, err := strategy.Disjoint(outerPolygon, outsidePoint) if err == nil { fmt.Printf("Polygon and outside point are disjoint: %v\n", disjoint) // true } // Touches - geometries share boundary but not interior line1, _ := wkt.UnmarshalString(`LINESTRING(0 0, 5 0)`) line2, _ := wkt.UnmarshalString(`LINESTRING(5 0, 10 0)`) touches, err := strategy.Touches(line1, line2) if err == nil { fmt.Printf("Lines touch: %v\n", touches) } // Overlaps - geometries share some but not all space overlaps, err := strategy.Overlaps(outerPolygon, overlappingPoly) if err == nil { fmt.Printf("Polygons overlap: %v\n", overlaps) } } ``` -------------------------------- ### GeoJSON FeatureCollection Processing in Go Source: https://context7.com/spatial-go/geoos/llms.txt Demonstrates parsing a GeoJSON FeatureCollection and extracting geometry data and properties. Utilizes the 'encoding/json' package along with 'geoos/geoencoding/geojson' and 'geoos/space'. Input is a byte slice representing GeoJSON, output includes extracted coordinates and properties. ```go package main import ( "encoding/json" "fmt" "github.com/spatial-go/geoos/geoencoding/geojson" "github.com/spatial-go/geoos/space" ) func main() { // Parse GeoJSON FeatureCollection rawJSON := []byte(`{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [102.0, 0.5] }, "properties": { "name": "Sample Point", "category": "test" } }, { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [[100.0, 0.0], [101.0, 1.0]] }, "properties": { "name": "Sample Line" } } ] }`) fc := geojson.NewFeatureCollection() err := json.Unmarshal(rawJSON, &fc) if err != nil { fmt.Printf("Error parsing GeoJSON: %v\n", err) return } // Extract geometry from first feature point := fc.Features[0].Geometry.Coordinates.(space.Point) fmt.Printf("Point coordinates: [%f, %f]\n", point.Lon(), point.Lat()) // Access feature properties fmt.Printf("Feature name: %v\n", fc.Features[0].Properties["name"]) fmt.Printf("Total features: %d\n", len(fc.Features)) // Output: Point coordinates: [102.000000, 0.500000] } ``` -------------------------------- ### WKT Encoding and Decoding Geometries in Go Source: https://context7.com/spatial-go/geoos/llms.txt Handles parsing Well-Known Text (WKT) strings into geometry objects and encoding Go geometry types back into WKT format. Uses the 'geoos/geoencoding/wkt' and 'geoos/space' packages. Input can be a WKT string or a Go geometry struct. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/space" ) func main() { // Decode WKT string to geometry wktString := `LINESTRING(0 0, 1 1, 2 2, 3 3)` geometry, err := wkt.UnmarshalString(wktString) if err != nil { fmt.Printf("Error parsing WKT: %v\n", err) return } fmt.Printf("Geometry type: %s\n", geometry.GeoJSONType()) fmt.Printf("Is empty: %v\n", geometry.IsEmpty()) // Encode geometry back to WKT lineString := space.LineString{ space.Point{0, 0}, space.Point{10, 10}, space.Point{20, 20}, } wktOutput := wkt.MarshalString(lineString) fmt.Printf("WKT output: %s\n", wktOutput) // Output: WKT output: LINESTRING(0 0,10 10,20 20) } ``` -------------------------------- ### Calculate Planar and Spherical Distances - Go Source: https://context7.com/spatial-go/geoos/llms.txt Calculates the planar and spherical distances between two point geometries using the geoos library. It utilizes the `planar.NormalStrategy` for calculations. Dependencies include `fmt`, `wkt` for geometry parsing, and `planar` for distance functions. Outputs are float64 for planar distance and float64 (in meters) for spherical distance. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Create two point geometries point1, _ := wkt.UnmarshalString(`POINT(0 0)`) point2, _ := wkt.UnmarshalString(`POINT(3 4)`) // Calculate planar distance distance, err := strategy.Distance(point1, point2) if err != nil { fmt.Printf("Error calculating distance: %v\n", err) return } fmt.Printf("Planar distance: %f\n", distance) // Output: Planar distance: 5.000000 // Calculate spherical distance (for lat/lon coordinates in degrees) pointA, _ := wkt.UnmarshalString(`POINT(-73.935242 40.730610)`) // New York pointB, _ := wkt.UnmarshalString(`POINT(-118.243683 34.052235)`) // Los Angeles sphericalDist, err := strategy.SphericalDistance(pointA, pointB) if err != nil { fmt.Printf("Error calculating spherical distance: %v\n", err) return } fmt.Printf("Spherical distance (meters): %f\n", sphericalDist) } ``` -------------------------------- ### Perform Spatial Operations (Intersection, Union, Difference) - Go Source: https://context7.com/spatial-go/geoos/llms.txt Performs topological spatial operations such as Intersection, Union, and Difference between two polygon geometries using the geoos library. Requires `fmt`, `wkt` for geometry handling, and `planar` for operations. The function takes two geometries as input and returns a new geometry representing the result of the operation. Outputs are WKT strings. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Define two overlapping polygons poly1, _ := wkt.UnmarshalString(`POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))`) poly2, _ := wkt.UnmarshalString(`POLYGON((2 2, 6 2, 6 6, 2 6, 2 2))`) // Intersection - area where both polygons overlap intersection, err := strategy.Intersection(poly1, poly2) if err != nil { fmt.Printf("Error calculating intersection: %v\n", err) return } fmt.Printf("Intersection: %s\n", wkt.MarshalString(intersection)) // Union - combined area of both polygons union, err := strategy.Union(poly1, poly2) if err != nil { fmt.Printf("Error calculating union: %v\n", err) return } fmt.Printf("Union: %s\n", wkt.MarshalString(union)) // Difference - area of poly1 not in poly2 difference, err := strategy.Difference(poly1, poly2) if err != nil { fmt.Printf("Error calculating difference: %v\n", err) return } fmt.Printf("Difference: %s\n", wkt.MarshalString(difference)) // SymDifference - areas in either polygon but not both symDiff, err := strategy.SymDifference(poly1, poly2) if err != nil { fmt.Printf("Error calculating symmetric difference: %v\n", err) return } fmt.Printf("Symmetric Difference: %s\n", wkt.MarshalString(symDiff)) } ``` -------------------------------- ### Calculate Hausdorff Distance in Go Source: https://context7.com/spatial-go/geoos/llms.txt Calculates the Hausdorff distance between geometries in Go to measure their similarity. This function supports both standard and densified calculations for improved accuracy, especially for complex shapes. It requires the 'wkt' and 'planar' packages from the geoos library. ```go package main import ( "fmt" "github.com/spatial-go/geoos/geoencoding/wkt" "github.com/spatial-go/geoos/planar" ) func main() { strategy := planar.NormalStrategy() // Create two similar but not identical lines line1, _ := wkt.UnmarshalString(`LINESTRING(0 0, 1 0, 2 0, 3 0)`) line2, _ := wkt.UnmarshalString(`LINESTRING(0 0.1, 1 0.1, 2 0.2, 3 0.1)`) // Calculate Hausdorff distance - maximum distance between closest points hausdorff, err := strategy.HausdorffDistance(line1, line2) if err != nil { fmt.Printf("Error calculating Hausdorff distance: %v\n", err) return } fmt.Printf("Hausdorff distance: %f\n", hausdorff) // Calculate with densification for more accurate results // densifyFrac: fraction of line segment to add intermediate points densifyFrac := 0.5 hausdorffDense, err := strategy.HausdorffDistanceDensify(line1, line2, densifyFrac) if err != nil { fmt.Printf("Error calculating densified Hausdorff distance: %v\n", err) return } fmt.Printf("Hausdorff distance (densified): %f\n", hausdorffDense) // Compare two polygons poly1, _ := wkt.UnmarshalString(`POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))`) poly2, _ := wkt.UnmarshalString(`POLYGON((0.1 0.1, 3.9 0, 4 3.9, 0 4, 0.1 0.1))`) polyDistance, _ := strategy.HausdorffDistance(poly1, poly2) fmt.Printf("Polygon Hausdorff distance: %f\n", polyDistance) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.