Forked from icchan/geospatial-querying-with-go-and-mongodb.go
Last active
November 26, 2016 22:37
-
-
Save varver/d62813247c4eceb8d11e5ced1eb05a14 to your computer and use it in GitHub Desktop.
Geospatial Querying with GoLang and MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"gopkg.in/mgo.v2" | |
"gopkg.in/mgo.v2/bson" | |
"log" | |
) | |
// ===== models ===== | |
type ShopLocation struct { | |
ID bson.ObjectId `bson:"_id,omitempty" json:"shopid"` | |
Name string `bson:"name" json:"name"` | |
Location GeoJson `bson:"location" json:"location"` | |
} | |
type GeoJson struct { | |
Type string `json:"-"` | |
Coordinates []float64 `json:"coordinates"` | |
} | |
// ===== application ===== | |
func main() { | |
cluster := "localhost" // mongodb host | |
// connect to mongo | |
session, err := mgo.Dial(cluster) | |
if err != nil { | |
log.Fatal("could not connect to db: ", err) | |
panic(err) | |
} | |
defer session.Close() | |
session.SetMode(mgo.Monotonic, true) | |
// search criteria | |
long := 139.701642 | |
lat := 35.690647 | |
scope := 3000 // max distance in metres | |
var results []ShopLocation // to hold the results | |
// query the database | |
c := session.DB("test").C("shops") | |
err = c.Find(bson.M{ | |
"location": bson.M{ | |
"$nearSphere": bson.M{ | |
"$geometry": bson.M{ | |
"type": "Point", | |
"coordinates": []float64{long, lat}, | |
}, | |
"$maxDistance": scope, | |
}, | |
}, | |
}).All(&results) | |
if err != nil { | |
panic(err) | |
} | |
// convert it to JSON so it can be displayed | |
formatter := json.MarshalIndent | |
response, err := formatter(results, " ", " ") | |
fmt.Println(string(response)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment