### Using Orb Geometry Interface with Sub-packages Source: https://github.com/paulmach/orb/blob/master/README.md Illustrates how the `Geometry` interface is used by sub-package functions, allowing them to operate on different geometric types polymorphically. For example, `clip.Geometry` adapts to the input type. ```go l := clip.Geometry(bound, geom) ``` -------------------------------- ### Clip Geometries in GeoJSON Feature Collection Source: https://github.com/paulmach/orb/blob/master/README.md Example of unmarshalling a GeoJSON FeatureCollection and clipping each feature's geometry using the clip.Geometry function. Requires data to be unmarshalled first. ```go fc, err := geojson.UnmarshalFeatureCollection(data) for _, f := range fc { f.Geometry = clip.Geometry(bound, f.Geometry) } ``` -------------------------------- ### Idiomatic Usage of Orb Geometric Types Source: https://github.com/paulmach/orb/blob/master/README.md Demonstrates idiomatic Go usage of Orb's geometric types, such as initializing, appending points, and accessing elements using built-in functions and slice notation. ```go ls := make(orb.LineString, 0, 100) ls = append(ls, orb.Point{1, 1}) point := ls[0] ``` -------------------------------- ### Marshalling a FeatureCollection to JSON Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Demonstrates how to create a GeoJSON FeatureCollection and marshal it into a JSON byte slice using Orb's MarshalJSON or Go's standard json.Marshal. ```go fc := geojson.NewFeatureCollection() fc.Append(geojson.NewFeature(orb.Point{1, 2})) rawJSON, _ := fc.MarshalJSON() // or blob, _ := json.Marshal(fc) ``` -------------------------------- ### Calculate Planar Area and Centroid of a Polygon Source: https://github.com/paulmach/orb/blob/master/README.md Demonstrates how to compute the planar area and centroid of an `orb.Polygon` using the `planar.CentroidArea` function. This is useful for projected or planar geometric calculations. ```go poly := orb.Polygon{...} centroid, area := planar.CentroidArea(poly) ``` -------------------------------- ### Scan EWKB Geometry from MySQL/MariaDB (ST_AsBinary) Source: https://github.com/paulmach/orb/blob/master/encoding/ewkb/README.md When using ST_AsBinary in MySQL/MariaDB, scan the SRID and the geometry data separately. The ewkb.Scanner can be used to scan the geometry data. ```go // using the ST_AsBinary function row := db.QueryRow("SELECT st_srid(geom), ST_AsBinary(geom) FROM geodata") row.Scan(&srid, ewkb.Scanner(&data)) ``` -------------------------------- ### Scan EWKB Geometry from Database Source: https://github.com/paulmach/orb/blob/master/README.md Use ewkb.Scanner to scan WKB/EWKB data directly from a database query result into an Orb geometry type. ```go row := db.QueryRow("SELECT ST_AsBinary(point_column) FROM postgis_table") var p orb.Point err := row.Scan(ewkb.Scanner(&p)) ``` -------------------------------- ### Type Conversion for Feature Properties Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Use these methods to safely convert feature properties to specific types, providing a default value if the property is missing or of the wrong type. ```go f.Properties.MustBool(key string, def ...bool) bool f.Properties.MustFloat64(key string, def ...float64) float64 f.Properties.MustInt(key string, def ...int) int f.Properties.MustString(key string, def ...string) string ``` -------------------------------- ### Configuring Custom JSON Marshaler/Unmarshaler for Performance Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Enables the use of a high-performance JSON library like github.com/json-iterator/go by setting Orb's global CustomJSONMarshaler and CustomJSONUnmarshaler. This requires importing and configuring the third-party library. ```go import ( jsoniter "github.com/json-iterator/go" "github.com/paulmach/orb/geojson" ) // in an init() or main(), etc. c := jsoniter.Config{ EscapeHTML: true, SortMapKeys: false, MarshalFloatWith6Digits: true, }.Froze() geojson.CustomJSONMarshaler = c geojson.CustomJSONUnmarshaler = c ``` -------------------------------- ### Radial Simplification (Euclidean) Source: https://github.com/paulmach/orb/blob/master/simplify/README.md Radial simplification using Euclidean distance. Removes points that are close together based on a threshold. The original geometry may be modified. ```go original := geo.Polygon{} // this method uses a Euclidean distance measure. reduced := simplify.Radial(planar.Distance, threshold).Simplify(path) ``` -------------------------------- ### Insert EWKB Geometry into Database Source: https://github.com/paulmach/orb/blob/master/README.md Use ewkb.Value to format Orb geometries into EWKB format for insertion into a database. The SRID is specified as the second argument. ```go db.Exec( "INSERT INTO postgis_table (point_column) VALUES (ST_GeomFromEWKB(?))", ewkb.Value(orb.Point{1, 2}, 4326), ) ``` -------------------------------- ### Scan EWKB Geometry from MySQL/MariaDB (Raw Encoding) Source: https://github.com/paulmach/orb/blob/master/encoding/ewkb/README.md Scan raw encoded EWKB geometry from MySQL/MariaDB using ewkb.ScannerPrefixSRID. This scanner handles the 4-byte SRID prefix and decodes the geometry. ```go // relying on the raw encoding row := db.QueryRow("SELECT geom FROM geodata") // if you don't need the SRID p := orb.Point{} err := row.Scan(ewkb.ScannerPrefixSRID(&p)) log.Printf("geom: %v", p) // if you need the SRID p := orb.Point{} gs := ewkb.ScannerPrefixSRID(&p) err := row.Scan(gs) log.Printf("srid: %v", gs.SRID) log.Printf("geom: %v", gs.Geometry) ``` -------------------------------- ### ProjectToTile Source: https://github.com/paulmach/orb/blob/master/encoding/mvt/README.md Projects geometries within a layer to the specified tile coordinates. ```APIDOC ## ProjectToTile ### Description Projects geometries within a layer to the specified tile coordinates. ### Method `func (l Layer) ProjectToTile(tile maptile.Tile)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tile** (maptile.Tile) - Required - The target tile for projection. ### Response No explicit return value, modifies the layer in place. ``` -------------------------------- ### Use Generic Properties with GeoJSON in Go Source: https://github.com/paulmach/orb/blob/master/README.md Demonstrates using a custom struct 'MyProperties' with the generic FeatureCollectionOf type for unmarshalling GeoJSON data. Access custom properties directly. ```go type MyProperties struct { Name string `json:"name"` Age int `json:"age"` } fc := geojson.FeatureCollectionOf[MyProperties]{} err := json.Unmarshal(rawJSON, &fc) fc.Features[0].Properties.Name // == "Alice" ``` -------------------------------- ### Radial Simplification (Geodesic) Source: https://github.com/paulmach/orb/blob/master/simplify/README.md Radial simplification using geodesic distance for lng/lat coordinates. Removes points that are close together based on a threshold in meters. The original geometry may be modified. ```go original := geo.Polygon{} // if the points are in the lng/lat space Radial Geo will // compute the geo distance between the coordinates. reduced:= simplify.Radial(geo.Distance, meters).Simplify(path) ``` -------------------------------- ### ProjectToWGS84 Source: https://github.com/paulmach/orb/blob/master/encoding/mvt/README.md Projects geometries within a layer from tile coordinates to WGS84 (lon/lat). ```APIDOC ## ProjectToWGS84 ### Description Projects geometries within a layer from tile coordinates to WGS84 (lon/lat). ### Method `func (l Layer) ProjectToWGS84(tile maptile.Tile)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tile** (maptile.Tile) - Required - The tile from which to project. ### Response No explicit return value, modifies the layer in place. ``` -------------------------------- ### Using Generics for Custom Feature Properties Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Define a custom struct for your feature properties and use Go 1.18 generics to create type-safe FeatureCollections and Features. This simplifies unmarshalling and property access. ```go type MyProperties struct { Name string `json:"name"` Age int `json:"age"` } fc := geojson.FeatureCollectionOf[MyProperties]{} fc.Append( &geojson.FeatureOf[MyProperties]{ Geometry: orb.Point{1, 2}, Properties: MyProperties{Name: "Alice", Age: 30}, }, ) // unmarshalling can be even easier fc2 := geojson.FeatureCollectionOf[MyProperties]{} er := json.Unmarshal(rawJSON, &fc2) fc2.Features[0].Properties.Name // == "Alice" ``` -------------------------------- ### Calculate Geo Distance Between Points Source: https://github.com/paulmach/orb/blob/master/README.md Shows how to calculate the geographic distance between two `orb.Point` types using the `geo.Distance` function. This operation is context-aware for geographic coordinates. ```go p1 := orb.Point{-72.796408, -45.407131} p2 := orb.Point{-72.688541, -45.384987} geo.Distance(p1, p2) ``` -------------------------------- ### Unmarshal Source: https://github.com/paulmach/orb/blob/master/encoding/mvt/README.md Decodes Mapbox Vector Tile data (not gzipped) into layers. ```APIDOC ## Unmarshal ### Description Decodes Mapbox Vector Tile data (not gzipped) into layers. ### Method `Unmarshal(data []byte) (Layers, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** ([]byte) - Required - The vector tile data. ### Response #### Success Response (200) - **Layers** - The decoded layers. - **error** - An error if the decoding fails. ### Request Example ```go layers, err := mvt.Unmarshal(data) ``` ``` -------------------------------- ### Unmarshalling GeoJSON with Extra Members Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Shows how to unmarshal a JSON byte slice into a FeatureCollection, preserving any 'extra' members present in the top-level object. These extra members can be accessed via the ExtraMembers map. ```go rawJSON := []byte(` { "type": "FeatureCollection", "generator": "myapp", "timestamp": "2020-06-15T01:02:03Z", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} } ] }`) fc, _ := geojson.UnmarshalFeatureCollection(rawJSON) fc.ExtraMembers["generator"] // == "myApp" fc.ExtraMembers["timestamp"] // == "2020-06-15T01:02:03Z" // Marshalling will include values in `ExtraMembers` in the // base featureCollection object. ``` -------------------------------- ### Orb Geometry Interface Definition Source: https://github.com/paulmach/orb/blob/master/README.md Defines the shared `Geometry` interface implemented by all base Orb types. This interface includes methods for retrieving the GeoJSON type, dimensions, and bounding box. ```go type Geometry interface { GeoJSONType() string Dimensions() int // e.g. 0d, 1d, 2d Bound() Bound } ``` -------------------------------- ### Define GeoJSON Feature Type in Go Source: https://github.com/paulmach/orb/blob/master/README.md Defines the structure for a GeoJSON Feature, including ID, type, geometry, and properties. Supports generic properties for custom types. ```go type Feature struct { ID any `json:"id,omitempty"` Type string `json:"type"` Geometry orb.Geometry `json:"geometry"` Properties Properties `json:"properties"` } // or a generic version with user defined properties type: type FeatureOf[P] struct { ID any `json:"id,omitempty"` Type string `json:"type"` Geometry orb.Geometry `json:"geometry"` Properties P `json:"properties"` } ``` -------------------------------- ### Define Orb Geometric Types in Go Source: https://github.com/paulmach/orb/blob/master/README.md Defines core geometric types like Point, LineString, Polygon, and their multi-part variants. These types leverage Go's slice capabilities for idiomatic usage with built-in functions. ```go type Point [2]float64 type MultiPoint []Point type LineString []Point type MultiLineString []LineString type Ring LineString type Polygon []Ring type MultiPolygon []Polygon type Collection []Geometry type Bound struct { Min, Max Point } ``` -------------------------------- ### Marshal Mapbox Vector Tiles Source: https://github.com/paulmach/orb/blob/master/README.md Use Marshal to encode GeoJSON FeatureCollections into Mapbox Vector Tile format. MarshalGzipped is available for gzip-compressed output. ```go collections := map[string]*geojson.FeatureCollection{} // Convert to a layers object and project to tile coordinates. layers := mvt.NewLayers(collections) layers.ProjectToTile(maptile.New(x, y, z)) // In order to be used as source for MapboxGL geometries need to be clipped // to max allowed extent. (uncomment next line) // layers.Clip(mvt.MapboxGLDefaultExtentBound) // Simplify the geometry now that it's in tile coordinate space. layers.Simplify(simplify.DouglasPeucker(1.0)) // Depending on use-case remove empty geometry, those too small to be // represented in this tile space. // In this case lines shorter than 1, and areas smaller than 2. layers.RemoveEmpty(1.0, 2.0) // encoding using the Mapbox Vector Tile protobuf encoding. data, err := mvt.Marshal(layers) // this data is NOT gzipped. ``` ```go data, err := mvt.MarshalGzipped(layers) ``` -------------------------------- ### UnmarshalCollection Source: https://github.com/paulmach/orb/blob/master/encoding/wkt/README.md Unmarshals a Well-Known Text (WKT) string specifically into an Orb Collection. ```APIDOC ## UnmarshalCollection ### Description Unmarshals a Well-Known Text (WKT) string specifically into an Orb Collection. ### Signature ```go func UnmarshalCollection(string) (orb.Collection, error) ``` ### Parameters - **string** (string) - The WKT string representing a Collection. ### Returns - **orb.Collection** - The unmarshaled Collection. - **error** - An error if the unmarshaling fails or the input is not a Collection. ``` -------------------------------- ### Unmarshal GeoJSON FeatureCollection Source: https://github.com/paulmach/orb/blob/master/geojson/README.md Use UnmarshalFeatureCollection to decode raw JSON bytes into a FeatureCollection. Alternatively, use the standard json.Unmarshal with a geojson.FeatureCollection type. ```go rawJSON := []byte(` { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} } ] }`) fc, _ := geojson.UnmarshalFeatureCollection(rawJSON) // or fc := geojson.NewFeatureCollection() er := json.Unmarshal(rawJSON, &fc) // Geometry will be unmarshalled into the correct geo.Geometry type. point := fc.Features[0].Geometry.(orb.Point) ``` -------------------------------- ### UnmarshalMultiPolygon Source: https://github.com/paulmach/orb/blob/master/encoding/wkt/README.md Unmarshals a Well-Known Text (WKT) string specifically into an Orb MultiPolygon. ```APIDOC ## UnmarshalMultiPolygon ### Description Unmarshals a Well-Known Text (WKT) string specifically into an Orb MultiPolygon. ### Signature ```go func UnmarshalMultiPolygon(string) (orb.MultiPolygon, error) ``` ### Parameters - **string** (string) - The WKT string representing a MultiPolygon. ### Returns - **orb.MultiPolygon** - The unmarshaled MultiPolygon. - **error** - An error if the unmarshaling fails or the input is not a MultiPolygon. ```