Skip to content

Instantly share code, notes, and snippets.

@icchan
Created October 18, 2014 07:37
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save icchan/bd42095afd8305594778 to your computer and use it in GitHub Desktop.
Save icchan/bd42095afd8305594778 to your computer and use it in GitHub Desktop.
Geospatial Querying with GoLang and MongoDB
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))
}
@saito-sv
Copy link

is this still working?

@saito-sv
Copy link

I guess my question is, how are you saving this data to the db. The coordinates system to precise?

@shackra
Copy link

shackra commented Jan 22, 2018

@Marlon-Monroy my guess is that you need to take a look to https://docs.mongodb.com/manual/geospatial-queries/

@Emixam23
Copy link

Doesn't seems to work anymore :/

@Lebski
Copy link

Lebski commented Jul 15, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment