Home > Article > Backend Development > How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?
Problem:
In Go, using Gorm to insert and retrieve PostGIS geometry types via the Orb library poses challenges due to Gorm's automatic insertion and data scanning. Simply inserting binary data into geometry columns doesn't suffice, and querying returns hex results.
Solution:
Using the @robbieperry22 answer as inspiration, an approach with a different encoding library eliminates the need for byte manipulation.
<code class="go">type EWKBGeomPoint geom.Point func (g *EWKBGeomPoint) Scan(input interface{}) error { gt, err := ewkb.Unmarshal(input.([]byte)) if err != nil { return err } g = gt.(*EWKBGeomPoint) return nil } func (g EWKBGeomPoint) Value() (driver.Value, error) { b := geom.Point(g) bp := &b ewkbPt := ewkb.Point{Point: bp.SetSRID(4326)} return ewkbPt.Value() }</code>
<code class="go">type Track struct { gorm.Model GeometryPoint EWKBGeomPoint `gorm:"column:geom"` }</code>
<code class="go">err = db.Exec(`CREATE TABLE IF NOT EXISTS tracks ( id SERIAL PRIMARY KEY, geom geometry(POINT, 4326) NOT NULL );`).Error if err != nil { return err } // Create table without geom column mig := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{ { ID: "tracks_except_geom", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(Track{}).Error }, }, } mig.Migrate()</code>
This approach seamlessly converts between EWKB bytes and the PostGIS geometry type, allowing for insertion and selection of geometries without additional customization or manual query generation.
The above is the detailed content of How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?. For more information, please follow other related articles on the PHP Chinese website!